xref: /xnu-10002.61.3/bsd/kern/kern_memorystatus.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
1 /*
2  * Copyright (c) 2006-2019 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/sched_prim.h>
31 #include <kern/kalloc.h>
32 #include <kern/assert.h>
33 #include <kern/debug.h>
34 #include <kern/locks.h>
35 #include <kern/task.h>
36 #include <kern/thread.h>
37 #include <kern/host.h>
38 #include <kern/policy_internal.h>
39 #include <kern/thread_group.h>
40 
41 #include <corpses/task_corpse.h>
42 #include <libkern/libkern.h>
43 #include <mach/mach_time.h>
44 #include <mach/task.h>
45 #include <mach/host_priv.h>
46 #include <mach/mach_host.h>
47 #include <pexpert/pexpert.h>
48 #include <sys/coalition.h>
49 #include <sys/code_signing.h>
50 #include <sys/kern_event.h>
51 #include <sys/proc.h>
52 #include <sys/proc_info.h>
53 #include <sys/reason.h>
54 #include <sys/signal.h>
55 #include <sys/signalvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
58 #include <sys/spawn_internal.h>
59 #include <sys/wait.h>
60 #include <sys/tree.h>
61 #include <sys/priv.h>
62 #include <vm/pmap.h>
63 #include <vm/vm_reclaim_internal.h>
64 #include <vm/vm_pageout.h>
65 #include <vm/vm_protos.h>
66 #include <mach/machine/sdt.h>
67 #include <libkern/section_keywords.h>
68 #include <stdatomic.h>
69 #include <os/atomic_private.h>
70 
71 #include <IOKit/IOBSD.h>
72 
73 #if CONFIG_MACF
74 #include <security/mac_framework.h>
75 #endif
76 
77 #if CONFIG_FREEZE
78 #include <vm/vm_map.h>
79 #endif /* CONFIG_FREEZE */
80 
81 #include <kern/kern_memorystatus_internal.h>
82 #include <sys/kern_memorystatus.h>
83 #include <sys/kern_memorystatus_freeze.h>
84 #include <sys/kern_memorystatus_notify.h>
85 #include <sys/kdebug_triage.h>
86 
87 
88 extern uint32_t vm_compressor_pool_size(void);
89 extern uint32_t vm_compressor_fragmentation_level(void);
90 extern uint32_t vm_compression_ratio(void);
91 
92 int block_corpses = 0; /* counter to block new corpses if jetsam purges them */
93 
94 /* For logging clarity */
95 static const char *memorystatus_kill_cause_name[] = {
96 	"",                                             /* kMemorystatusInvalid							*/
97 	"jettisoned",                                   /* kMemorystatusKilled							*/
98 	"highwater",                                    /* kMemorystatusKilledHiwat						*/
99 	"vnode-limit",                                  /* kMemorystatusKilledVnodes					*/
100 	"vm-pageshortage",                              /* kMemorystatusKilledVMPageShortage			*/
101 	"proc-thrashing",                               /* kMemorystatusKilledProcThrashing				*/
102 	"fc-thrashing",                                 /* kMemorystatusKilledFCThrashing				*/
103 	"per-process-limit",                            /* kMemorystatusKilledPerProcessLimit			*/
104 	"disk-space-shortage",                          /* kMemorystatusKilledDiskSpaceShortage			*/
105 	"idle-exit",                                    /* kMemorystatusKilledIdleExit					*/
106 	"zone-map-exhaustion",                         /* kMemorystatusKilledZoneMapExhaustion			*/
107 	"vm-compressor-thrashing",                     /* kMemorystatusKilledVMCompressorThrashing		*/
108 	"vm-compressor-space-shortage",                /* kMemorystatusKilledVMCompressorSpaceShortage	*/
109 	"low-swap",                                    /* kMemorystatusKilledLowSwap                   */
110 	"sustained-memory-pressure",                   /* kMemorystatusKilledSustainedPressure         */
111 	"vm-pageout-starvation",                       /* kMemorystatusKilledVMPageoutStarvation       */
112 };
113 
114 static const char *
memorystatus_priority_band_name(int32_t priority)115 memorystatus_priority_band_name(int32_t priority)
116 {
117 	switch (priority) {
118 	case JETSAM_PRIORITY_FOREGROUND:
119 		return "FOREGROUND";
120 	case JETSAM_PRIORITY_AUDIO_AND_ACCESSORY:
121 		return "AUDIO_AND_ACCESSORY";
122 	case JETSAM_PRIORITY_CONDUCTOR:
123 		return "CONDUCTOR";
124 	case JETSAM_PRIORITY_DRIVER_APPLE:
125 		return "DRIVER_APPLE";
126 	case JETSAM_PRIORITY_HOME:
127 		return "HOME";
128 	case JETSAM_PRIORITY_EXECUTIVE:
129 		return "EXECUTIVE";
130 	case JETSAM_PRIORITY_IMPORTANT:
131 		return "IMPORTANT";
132 	case JETSAM_PRIORITY_CRITICAL:
133 		return "CRITICAL";
134 	}
135 
136 	return "?";
137 }
138 
139 bool
is_reason_thrashing(unsigned cause)140 is_reason_thrashing(unsigned cause)
141 {
142 	switch (cause) {
143 	case kMemorystatusKilledFCThrashing:
144 	case kMemorystatusKilledVMCompressorThrashing:
145 	case kMemorystatusKilledVMCompressorSpaceShortage:
146 		return true;
147 	default:
148 		return false;
149 	}
150 }
151 
152 bool
is_reason_zone_map_exhaustion(unsigned cause)153 is_reason_zone_map_exhaustion(unsigned cause)
154 {
155 	return cause == kMemorystatusKilledZoneMapExhaustion;
156 }
157 
158 /*
159  * Returns the current zone map size and capacity to include in the jetsam snapshot.
160  * Defined in zalloc.c
161  */
162 extern void get_zone_map_size(uint64_t *current_size, uint64_t *capacity);
163 
164 /*
165  * Returns the name of the largest zone and its size to include in the jetsam snapshot.
166  * Defined in zalloc.c
167  */
168 extern void get_largest_zone_info(char *zone_name, size_t zone_name_len, uint64_t *zone_size);
169 
170 /*
171  * Active / Inactive limit support
172  * proc list must be locked
173  *
174  * The SET_*** macros are used to initialize a limit
175  * for the first time.
176  *
177  * The CACHE_*** macros are use to cache the limit that will
178  * soon be in effect down in the ledgers.
179  */
180 
181 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal)                    \
182 MACRO_BEGIN                                                             \
183 (p)->p_memstat_memlimit_active = (limit);                               \
184    if (is_fatal) {                                                      \
185 	   (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL;     \
186    } else {                                                             \
187 	   (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL;    \
188    }                                                                    \
189 MACRO_END
190 
191 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal)                  \
192 MACRO_BEGIN                                                             \
193 (p)->p_memstat_memlimit_inactive = (limit);                             \
194    if (is_fatal) {                                                      \
195 	   (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL;   \
196    } else {                                                             \
197 	   (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL;  \
198    }                                                                    \
199 MACRO_END
200 
201 #define CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal)                         \
202 MACRO_BEGIN                                                             \
203 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active;               \
204    if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) {        \
205 	   (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT;            \
206 	   is_fatal = TRUE;                                             \
207    } else {                                                             \
208 	   (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT;           \
209 	   is_fatal = FALSE;                                            \
210    }                                                                    \
211 MACRO_END
212 
213 #define CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal)                       \
214 MACRO_BEGIN                                                             \
215 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive;             \
216    if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) {      \
217 	   (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT;            \
218 	   is_fatal = TRUE;                                             \
219    } else {                                                             \
220 	   (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT;           \
221 	   is_fatal = FALSE;                                            \
222    }                                                                    \
223 MACRO_END
224 
225 
226 #pragma mark General Tunables
227 
228 #define MEMORYSTATUS_SMALL_MEMORY_THRESHOLD (3UL * (1UL << 30))
229 #define MEMORYSTATUS_MEDIUM_MEMORY_THRESHOLD (6UL * (1UL << 30))
230 
231 #define MEMORYSTATUS_MORE_FREE_OFFSET_PERCENTAGE 5UL
232 #define MEMORYSTATUS_AGGR_SYSPROC_AGING_PERCENTAGE 7UL
233 #define MEMORYSTATUS_DELTA_PERCENTAGE_LARGE 4UL
234 #define MEMORYSTATUS_DELTA_PERCENTAGE_SMALL 5UL
235 
236 /*
237  * Fall back to these percentages/ratios if a mb value is not provided via EDT
238  *  DRAM (GB) | critical | idle | pressure | freeze
239  *  (0,3]     | 5%       | 10%  | 15%      | 50%
240  *  (3,6]     | 4%       | 9%   | 15%      | 50%
241  *  (6,∞)     | 4%       | 8%   | 12%      | 50%
242  */
243 
244 #define MEMORYSTATUS_CRITICAL_BASE_PERCENTAGE_SMALL 5UL
245 #define MEMORYSTATUS_CRITICAL_BASE_PERCENTAGE_LARGE 4UL
246 
247 #define MEMORYSTATUS_CRITICAL_IDLE_RATIO_NUM 2UL
248 #define MEMORYSTATUS_CRITICAL_IDLE_RATIO_DENOM 1UL
249 #define MEMORYSTATUS_PRESSURE_RATIO_NUM 3UL
250 #define MEMORYSTATUS_PRESSURE_RATIO_DENOM 1UL
251 
252 /*
253  * For historical reasons, devices with "medium"-sized memory configs have a critical:idle:pressure ratio of
254  * 4:9:15. This ratio is preserved for these devices when a fixed-mb base value has not been provided by EDT/boot-arg;
255  * all other devices use a 1:2:3 ratio.
256  */
257 #define MEMORYSTATUS_CRITICAL_IDLE_RATIO_NUM_MEDIUM 9UL
258 #define MEMORYSTATUS_CRITICAL_IDLE_RATIO_DENOM_MEDIUM 4UL
259 #define MEMORYSTATUS_PRESSURE_RATIO_NUM_MEDIUM  15UL
260 #define MEMORYSTATUS_PRESSURE_RATIO_DENOM_MEDIUM  4UL
261 
262 #if CONFIG_JETSAM
263 static int32_t memorystatus_get_default_task_active_limit(proc_t p);
264 #endif /* CONFIG_JETSAM */
265 
266 /*
267  * default jetsam snapshot support
268  */
269 memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot;
270 
271 #if CONFIG_FREEZE
272 memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot_freezer;
273 /*
274  * The size of the freezer snapshot is given by memorystatus_jetsam_snapshot_max / JETSAM_SNAPSHOT_FREEZER_MAX_FACTOR
275  * The freezer snapshot can be much smaller than the default snapshot
276  * because it only includes apps that have been killed and dasd consumes it every 30 minutes.
277  * Since the snapshots are always wired we don't want to overallocate too much.
278  */
279 #define JETSAM_SNAPSHOT_FREEZER_MAX_FACTOR 20
280 unsigned int memorystatus_jetsam_snapshot_freezer_max;
281 unsigned int memorystatus_jetsam_snapshot_freezer_size;
282 TUNABLE(bool, memorystatus_jetsam_use_freezer_snapshot, "kern.jetsam_user_freezer_snapshot", true);
283 
284 #define MEMORYSTATUS_FREEZE_THRESHOLD_PERCENTAGE 50UL
285 TUNABLE_DT(uint32_t, memorystatus_freeze_threshold_mb, "/defaults", "kern.memstat_freeze_mb",
286     "memorystatus_freeze_threshold_mb", 0, TUNABLE_DT_NONE);
287 #endif /* CONFIG_FREEZE */
288 
289 unsigned int memorystatus_jetsam_snapshot_count = 0;
290 unsigned int memorystatus_jetsam_snapshot_max = 0;
291 unsigned int memorystatus_jetsam_snapshot_size = 0;
292 uint64_t memorystatus_jetsam_snapshot_last_timestamp = 0;
293 uint64_t memorystatus_jetsam_snapshot_timeout = 0;
294 
295 #if DEVELOPMENT || DEBUG
296 /*
297  * On development and debug kernels, we allow one pid to take ownership
298  * of some memorystatus data structures for testing purposes (via memorystatus_control).
299  * If there's an owner, then only they may consume the jetsam snapshot & set freezer probabilities.
300  * This is used when testing these interface to avoid racing with other
301  * processes on the system that typically use them (namely OSAnalytics & dasd).
302  */
303 static pid_t memorystatus_testing_pid = 0;
304 SYSCTL_INT(_kern, OID_AUTO, memorystatus_testing_pid, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_testing_pid, 0, "");
305 #endif /* DEVELOPMENT || DEBUG */
306 static void memorystatus_init_jetsam_snapshot_header(memorystatus_jetsam_snapshot_t *snapshot);
307 
308 /* General memorystatus stuff */
309 
310 uint64_t memorystatus_sysprocs_idle_delay_time = 0;
311 uint64_t memorystatus_apps_idle_delay_time = 0;
312 /* 2GB devices support an entitlement for a higher app memory limit of "almost 2GB". */
313 static int32_t memorystatus_ios13extended_footprint_limit_mb = 1800;
314 
315 /* Some devices give entitled apps a higher memory limit */
316 TUNABLE_DT_WRITEABLE(int32_t, memorystatus_entitled_max_task_footprint_mb, "/defaults", "kern.entitled_max_task_pmem", "entitled_max_task_pmem", 0, TUNABLE_DT_NONE);
317 
318 #if __arm64__
319 #if DEVELOPMENT || DEBUG
320 SYSCTL_INT(_kern, OID_AUTO, ios13extended_footprint_limit_mb, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_ios13extended_footprint_limit_mb, 0, "");
321 SYSCTL_INT(_kern, OID_AUTO, entitled_max_task_pmem, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, &memorystatus_entitled_max_task_footprint_mb, 0, "");
322 #else /* !(DEVELOPMENT || DEBUG) */
323 SYSCTL_INT(_kern, OID_AUTO, entitled_max_task_pmem, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED | CTLFLAG_KERN, &memorystatus_entitled_max_task_footprint_mb, 0, "");
324 #endif /* DEVELOPMENT || DEBUG */
325 #endif /* __arm64__ */
326 
327 #pragma mark Logging
328 
329 os_log_t memorystatus_log_handle;
330 
331 TUNABLE_WRITEABLE(memorystatus_log_level_t, memorystatus_log_level, "memorystatus_log_level", MEMORYSTATUS_LOG_LEVEL_DEFAULT);
332 
333 #if DEBUG || DEVELOPMENT
334 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_log_level, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_log_level, MEMORYSTATUS_LOG_LEVEL_DEFAULT, "");
335 #endif
336 
337 static LCK_GRP_DECLARE(memorystatus_jetsam_fg_band_lock_grp,
338     "memorystatus_jetsam_fg_band");
339 LCK_MTX_DECLARE(memorystatus_jetsam_fg_band_lock,
340     &memorystatus_jetsam_fg_band_lock_grp);
341 
342 /* Idle guard handling */
343 
344 static int32_t memorystatus_scheduled_idle_demotions_sysprocs = 0;
345 static int32_t memorystatus_scheduled_idle_demotions_apps = 0;
346 
347 static void memorystatus_perform_idle_demotion(__unused void *spare1, __unused void *spare2);
348 static void memorystatus_schedule_idle_demotion_locked(proc_t p, boolean_t set_state);
349 static void memorystatus_reschedule_idle_demotion_locked(void);
350 int memorystatus_update_priority_for_appnap(proc_t p, boolean_t is_appnap);
351 vm_pressure_level_t convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t);
352 boolean_t is_knote_registered_modify_task_pressure_bits(struct knote*, int, task_t, vm_pressure_level_t, vm_pressure_level_t);
353 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear);
354 void memorystatus_send_low_swap_note(void);
355 boolean_t memorystatus_kill_elevated_process(uint32_t cause, os_reason_t jetsam_reason, unsigned int band, int aggr_count,
356     uint32_t *errors, uint64_t *memory_reclaimed);
357 uint64_t memorystatus_available_memory_internal(proc_t p);
358 void memorystatus_thread_wake(void);
359 
360 unsigned int memorystatus_level = 0;
361 static int memorystatus_list_count = 0;
362 memstat_bucket_t memstat_bucket[MEMSTAT_BUCKET_COUNT];
363 static thread_call_t memorystatus_idle_demotion_call;
364 uint64_t memstat_idle_demotion_deadline = 0;
365 
366 #ifdef XNU_TARGET_OS_OSX
367 /*
368  * Effectively disable the system process and application demotion
369  * logic on macOS. This means system processes and apps won't get the
370  * 10 second protection before landing in the IDLE band after moving
371  * out of their active band. Reasons:-
372  * - daemons + extensions + apps on macOS don't behave the way they
373  *   do on iOS and so they are confusing the demotion logic. For example,
374  *   not all apps go from FG to IDLE. Some sit in higher bands instead. This
375  *   is causing multiple asserts to fire internally.
376  * - we use the aging bands to protect processes from jetsam. But on macOS,
377  *   we have a very limited jetsam that is only invoked under extreme conditions
378  *   where we have no more swap / compressor space OR are under critical pressure.
379  */
380 int system_procs_aging_band = 0;
381 int applications_aging_band = 0;
382 #else /* XNU_TARGET_OS_OSX */
383 int system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
384 int applications_aging_band = JETSAM_PRIORITY_AGING_BAND2;
385 #endif /* XNU_TARGET_OS_OSX */
386 
387 _Atomic bool memorystatus_zone_map_is_exhausted = false;
388 _Atomic bool memorystatus_compressor_space_shortage = false;
389 _Atomic bool memorystatus_pageout_starved = false;
390 #if CONFIG_PHANTOM_CACHE
391 _Atomic bool memorystatus_phantom_cache_pressure = false;
392 #endif /* CONFIG_PHANTOM_CACHE */
393 
394 #define isProcessInAgingBands(p)        ((isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) || (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)))
395 
396 /*
397  * For a while we had support for a couple of different aging policies in the kernel,
398  * but the sysproc aging policy is now the default on all platforms.
399  * This flag was exported as RO via sysctl & is only kept for backwards compatability.
400  */
401 unsigned int jetsam_aging_policy = kJetsamAgingPolicySysProcsReclaimedFirst;
402 bool memorystatus_should_issue_fg_band_notify = true;
403 
404 extern uint64_t vm_purgeable_purge_task_owned(task_t task);
405 extern void coalition_mark_swappable(coalition_t coal);
406 extern bool coalition_is_swappable(coalition_t coal);
407 boolean_t memorystatus_allowed_vm_map_fork(task_t, bool *);
408 #if DEVELOPMENT || DEBUG
409 void memorystatus_abort_vm_map_fork(task_t);
410 #endif
411 
412 /*
413  * Idle delay timeout factors for daemons based on relaunch behavior. Only used in
414  * kJetsamAgingPolicySysProcsReclaimedFirst aging policy.
415  */
416 #define kJetsamSysProcsIdleDelayTimeLowRatio    (5)
417 #define kJetsamSysProcsIdleDelayTimeMedRatio    (2)
418 #define kJetsamSysProcsIdleDelayTimeHighRatio   (1)
419 static_assert(kJetsamSysProcsIdleDelayTimeLowRatio <= DEFERRED_IDLE_EXIT_TIME_SECS, "sysproc idle delay time for low relaunch daemons would be 0");
420 
421 /*
422  * For the kJetsamAgingPolicySysProcsReclaimedFirst aging policy, treat apps as well
423  * behaved daemons for aging purposes.
424  */
425 #define kJetsamAppsIdleDelayTimeRatio   (kJetsamSysProcsIdleDelayTimeLowRatio)
426 
427 static uint64_t
memorystatus_sysprocs_idle_time(proc_t p)428 memorystatus_sysprocs_idle_time(proc_t p)
429 {
430 	uint64_t idle_delay_time = 0;
431 	/*
432 	 * For system processes, base the idle delay time on the
433 	 * jetsam relaunch behavior specified by launchd. The idea
434 	 * is to provide extra protection to the daemons which would
435 	 * relaunch immediately after jetsam.
436 	 */
437 	switch (p->p_memstat_relaunch_flags) {
438 	case P_MEMSTAT_RELAUNCH_UNKNOWN:
439 	case P_MEMSTAT_RELAUNCH_LOW:
440 		idle_delay_time = memorystatus_sysprocs_idle_delay_time / kJetsamSysProcsIdleDelayTimeLowRatio;
441 		break;
442 	case P_MEMSTAT_RELAUNCH_MED:
443 		idle_delay_time = memorystatus_sysprocs_idle_delay_time / kJetsamSysProcsIdleDelayTimeMedRatio;
444 		break;
445 	case P_MEMSTAT_RELAUNCH_HIGH:
446 		idle_delay_time = memorystatus_sysprocs_idle_delay_time / kJetsamSysProcsIdleDelayTimeHighRatio;
447 		break;
448 	default:
449 		panic("Unknown relaunch flags on process!");
450 		break;
451 	}
452 	return idle_delay_time;
453 }
454 
455 static uint64_t
memorystatus_apps_idle_time(__unused proc_t p)456 memorystatus_apps_idle_time(__unused proc_t p)
457 {
458 	return memorystatus_apps_idle_delay_time / kJetsamAppsIdleDelayTimeRatio;
459 }
460 
461 
462 static int
463 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
464 {
465 #pragma unused(oidp, arg1, arg2)
466 
467 	int error = 0, val = 0, old_time_in_secs = 0;
468 	uint64_t old_time_in_ns = 0;
469 
470 	absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time, &old_time_in_ns);
471 	old_time_in_secs = (int) (old_time_in_ns / NSEC_PER_SEC);
472 
473 	error = sysctl_io_number(req, old_time_in_secs, sizeof(int), &val, NULL);
474 	if (error || !req->newptr) {
475 		return error;
476 	}
477 
478 	if ((val < 0) || (val > INT32_MAX)) {
479 		memorystatus_log_error("jetsam: new idle delay interval has invalid value.\n");
480 		return EINVAL;
481 	}
482 
483 	nanoseconds_to_absolutetime((uint64_t)val * NSEC_PER_SEC, &memorystatus_sysprocs_idle_delay_time);
484 
485 	return 0;
486 }
487 
488 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_sysprocs_idle_delay_time, CTLTYPE_INT | CTLFLAG_RW,
489     0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time, "I", "Aging window for system processes");
490 
491 
492 static int
493 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
494 {
495 #pragma unused(oidp, arg1, arg2)
496 
497 	int error = 0, val = 0, old_time_in_secs = 0;
498 	uint64_t old_time_in_ns = 0;
499 
500 	absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time, &old_time_in_ns);
501 	old_time_in_secs = (int) (old_time_in_ns / NSEC_PER_SEC);
502 
503 	error = sysctl_io_number(req, old_time_in_secs, sizeof(int), &val, NULL);
504 	if (error || !req->newptr) {
505 		return error;
506 	}
507 
508 	if ((val < 0) || (val > INT32_MAX)) {
509 		memorystatus_log_error("jetsam: new idle delay interval has invalid value.\n");
510 		return EINVAL;
511 	}
512 
513 	nanoseconds_to_absolutetime((uint64_t)val * NSEC_PER_SEC, &memorystatus_apps_idle_delay_time);
514 
515 	return 0;
516 }
517 
518 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_apps_idle_delay_time, CTLTYPE_INT | CTLFLAG_RW,
519     0, 0, sysctl_jetsam_set_apps_idle_delay_time, "I", "Aging window for applications");
520 
521 SYSCTL_INT(_kern, OID_AUTO, jetsam_aging_policy, CTLTYPE_INT | CTLFLAG_RD, &jetsam_aging_policy, 0, "");
522 
523 static unsigned int memorystatus_dirty_count = 0;
524 
525 SYSCTL_INT(_kern, OID_AUTO, max_task_pmem, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED | CTLFLAG_KERN, &max_task_footprint_mb, 0, "");
526 
527 static int memorystatus_highwater_enabled = 1;  /* Update the cached memlimit data. */
528 static boolean_t proc_jetsam_state_is_active_locked(proc_t);
529 
530 #if __arm64__
531 int legacy_footprint_bonus_mb = 50; /* This value was chosen after looking at the top 30 apps
532                                      * that needed the additional room in their footprint when
533                                      * the 'correct' accounting methods were applied to them.
534                                      */
535 
536 #if DEVELOPMENT || DEBUG
537 SYSCTL_INT(_kern, OID_AUTO, legacy_footprint_bonus_mb, CTLFLAG_RW | CTLFLAG_LOCKED, &legacy_footprint_bonus_mb, 0, "");
538 #endif /* DEVELOPMENT || DEBUG */
539 /*
540  * Raise the inactive and active memory limits to new values.
541  * Will only raise the limits and will do nothing if either of the current
542  * limits are 0.
543  * Caller must hold the proc_list_lock
544  */
545 static void
memorystatus_raise_memlimit(proc_t p,int new_memlimit_active,int new_memlimit_inactive)546 memorystatus_raise_memlimit(proc_t p, int new_memlimit_active, int new_memlimit_inactive)
547 {
548 	int memlimit_mb_active = 0, memlimit_mb_inactive = 0;
549 	boolean_t memlimit_active_is_fatal = FALSE, memlimit_inactive_is_fatal = FALSE, use_active_limit = FALSE;
550 
551 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
552 
553 	if (p->p_memstat_memlimit_active > 0) {
554 		memlimit_mb_active = p->p_memstat_memlimit_active;
555 	} else if (p->p_memstat_memlimit_active == -1) {
556 		memlimit_mb_active = max_task_footprint_mb;
557 	} else {
558 		/*
559 		 * Nothing to do for '0' which is
560 		 * a special value only used internally
561 		 * to test 'no limits'.
562 		 */
563 		return;
564 	}
565 
566 	if (p->p_memstat_memlimit_inactive > 0) {
567 		memlimit_mb_inactive = p->p_memstat_memlimit_inactive;
568 	} else if (p->p_memstat_memlimit_inactive == -1) {
569 		memlimit_mb_inactive = max_task_footprint_mb;
570 	} else {
571 		/*
572 		 * Nothing to do for '0' which is
573 		 * a special value only used internally
574 		 * to test 'no limits'.
575 		 */
576 		return;
577 	}
578 
579 	memlimit_mb_active = MAX(new_memlimit_active, memlimit_mb_active);
580 	memlimit_mb_inactive = MAX(new_memlimit_inactive, memlimit_mb_inactive);
581 
582 	memlimit_active_is_fatal = (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL);
583 	memlimit_inactive_is_fatal = (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL);
584 
585 	SET_ACTIVE_LIMITS_LOCKED(p, memlimit_mb_active, memlimit_active_is_fatal);
586 	SET_INACTIVE_LIMITS_LOCKED(p, memlimit_mb_inactive, memlimit_inactive_is_fatal);
587 
588 	if (proc_jetsam_state_is_active_locked(p) == TRUE) {
589 		use_active_limit = TRUE;
590 		CACHE_ACTIVE_LIMITS_LOCKED(p, memlimit_active_is_fatal);
591 	} else {
592 		CACHE_INACTIVE_LIMITS_LOCKED(p, memlimit_inactive_is_fatal);
593 	}
594 
595 	if (memorystatus_highwater_enabled) {
596 		task_set_phys_footprint_limit_internal(proc_task(p),
597 		    (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1,
598 		    NULL,                                    /*return old value */
599 		    use_active_limit,                                    /*active limit?*/
600 		    (use_active_limit ? memlimit_active_is_fatal : memlimit_inactive_is_fatal));
601 	}
602 }
603 
604 void
memorystatus_act_on_legacy_footprint_entitlement(proc_t p,boolean_t footprint_increase)605 memorystatus_act_on_legacy_footprint_entitlement(proc_t p, boolean_t footprint_increase)
606 {
607 	int memlimit_mb_active = 0, memlimit_mb_inactive = 0;
608 
609 	if (p == NULL) {
610 		return;
611 	}
612 
613 	proc_list_lock();
614 
615 	if (p->p_memstat_memlimit_active > 0) {
616 		memlimit_mb_active = p->p_memstat_memlimit_active;
617 	} else if (p->p_memstat_memlimit_active == -1) {
618 		memlimit_mb_active = max_task_footprint_mb;
619 	} else {
620 		/*
621 		 * Nothing to do for '0' which is
622 		 * a special value only used internally
623 		 * to test 'no limits'.
624 		 */
625 		proc_list_unlock();
626 		return;
627 	}
628 
629 	if (p->p_memstat_memlimit_inactive > 0) {
630 		memlimit_mb_inactive = p->p_memstat_memlimit_inactive;
631 	} else if (p->p_memstat_memlimit_inactive == -1) {
632 		memlimit_mb_inactive = max_task_footprint_mb;
633 	} else {
634 		/*
635 		 * Nothing to do for '0' which is
636 		 * a special value only used internally
637 		 * to test 'no limits'.
638 		 */
639 		proc_list_unlock();
640 		return;
641 	}
642 
643 	if (footprint_increase) {
644 		memlimit_mb_active += legacy_footprint_bonus_mb;
645 		memlimit_mb_inactive += legacy_footprint_bonus_mb;
646 	} else {
647 		memlimit_mb_active -= legacy_footprint_bonus_mb;
648 		if (memlimit_mb_active == max_task_footprint_mb) {
649 			memlimit_mb_active = -1; /* reverting back to default system limit */
650 		}
651 
652 		memlimit_mb_inactive -= legacy_footprint_bonus_mb;
653 		if (memlimit_mb_inactive == max_task_footprint_mb) {
654 			memlimit_mb_inactive = -1; /* reverting back to default system limit */
655 		}
656 	}
657 	memorystatus_raise_memlimit(p, memlimit_mb_active, memlimit_mb_inactive);
658 
659 	proc_list_unlock();
660 }
661 
662 void
memorystatus_act_on_ios13extended_footprint_entitlement(proc_t p)663 memorystatus_act_on_ios13extended_footprint_entitlement(proc_t p)
664 {
665 	proc_list_lock();
666 	memorystatus_raise_memlimit(p, memorystatus_ios13extended_footprint_limit_mb,
667 	    memorystatus_ios13extended_footprint_limit_mb);
668 	proc_list_unlock();
669 }
670 
671 void
memorystatus_act_on_entitled_task_limit(proc_t p)672 memorystatus_act_on_entitled_task_limit(proc_t p)
673 {
674 	if (memorystatus_entitled_max_task_footprint_mb == 0) {
675 		// Entitlement is not supported on this device.
676 		return;
677 	}
678 	proc_list_lock();
679 	memorystatus_raise_memlimit(p, memorystatus_entitled_max_task_footprint_mb, memorystatus_entitled_max_task_footprint_mb);
680 	proc_list_unlock();
681 }
682 #endif /* __arm64__ */
683 
684 SYSCTL_INT(_kern, OID_AUTO, memorystatus_level, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_level, 0, "");
685 
686 int
memorystatus_get_level(__unused struct proc * p,struct memorystatus_get_level_args * args,__unused int * ret)687 memorystatus_get_level(__unused struct proc *p, struct memorystatus_get_level_args *args, __unused int *ret)
688 {
689 	user_addr_t     level = 0;
690 
691 	level = args->level;
692 
693 	if (copyout(&memorystatus_level, level, sizeof(memorystatus_level)) != 0) {
694 		return EFAULT;
695 	}
696 
697 	return 0;
698 }
699 
700 static void memorystatus_thread(void *param __unused, wait_result_t wr __unused);
701 
702 /* Memory Limits */
703 
704 static boolean_t memorystatus_kill_specific_process(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason);
705 static boolean_t memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason);
706 
707 
708 static int memorystatus_cmd_set_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
709 
710 #if DEBUG || DEVELOPMENT
711 static int memorystatus_cmd_set_diag_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
712 static int memorystatus_cmd_get_diag_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
713 static int memorystatus_set_diag_memlimit_properties_internal(proc_t p, memorystatus_diag_memlimit_properties_t *p_entry);
714 static int memorystatus_get_diag_memlimit_properties_internal(proc_t p, memorystatus_diag_memlimit_properties_t *p_entry);
715 #endif  // DEBUG || DEVELOPMENT
716 static int memorystatus_set_memlimit_properties(pid_t pid, memorystatus_memlimit_properties_t *entry);
717 
718 static int memorystatus_cmd_get_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
719 
720 static int memorystatus_cmd_get_memlimit_excess_np(pid_t pid, uint32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
721 
722 static void memorystatus_get_memlimit_properties_internal(proc_t p, memorystatus_memlimit_properties_t *p_entry);
723 static int memorystatus_set_memlimit_properties_internal(proc_t p, memorystatus_memlimit_properties_t *p_entry);
724 
725 int proc_get_memstat_priority(proc_t, boolean_t);
726 
727 static boolean_t memorystatus_idle_snapshot = 0;
728 
729 unsigned int memorystatus_delta = 0;
730 
731 /* Jetsam Loop Detection */
732 boolean_t memorystatus_jld_enabled = FALSE;              /* Enable jetsam loop detection */
733 uint32_t memorystatus_jld_eval_period_msecs = 0;         /* Init pass sets this based on device memory size */
734 int      memorystatus_jld_eval_aggressive_count = 3;     /* Raise the priority max after 'n' aggressive loops */
735 int      memorystatus_jld_eval_aggressive_priority_band_max = 15;  /* Kill aggressively up through this band */
736 int      memorystatus_jld_max_kill_loops = 2;            /* How many times should we try and kill up to the target band */
737 
738 /*
739  * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
740  * --- if aggressive jetsam kills an app in the FG band and gets back >=AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD memory, it will stop the aggressive march further into and up the jetsam bands.
741  *
742  * RESTRICTIONS:
743  * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
744  * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
745  *
746  * - If the app is still in the FG band and aggressive jetsam is needed again, there will be no stop-and-check the next time around.
747  *
748  * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
749  */
750 
751 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD        25
752 boolean_t       memorystatus_aggressive_jetsam_lenient_allowed = FALSE;
753 boolean_t       memorystatus_aggressive_jetsam_lenient = FALSE;
754 
755 #if DEVELOPMENT || DEBUG
756 /*
757  * Jetsam Loop Detection tunables.
758  */
759 
760 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_period_msecs, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_jld_eval_period_msecs, 0, "");
761 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_aggressive_count, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_jld_eval_aggressive_count, 0, "");
762 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_aggressive_priority_band_max, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_jld_eval_aggressive_priority_band_max, 0, "");
763 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_max_kill_loops, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_jld_max_kill_loops, 0, "");
764 #endif /* DEVELOPMENT || DEBUG */
765 
766 /*
767  * snapshot support for memstats collected at boot.
768  */
769 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot;
770 
771 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t *od_snapshot, uint32_t ods_list_count);
772 static boolean_t memorystatus_init_jetsam_snapshot_entry_locked(proc_t p, memorystatus_jetsam_snapshot_entry_t *entry, uint64_t gencount);
773 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p, uint32_t kill_cause, uint64_t killtime);
774 
775 static void memorystatus_clear_errors(void);
776 
777 static void memorystatus_get_task_phys_footprint_page_counts(task_t task,
778     uint64_t *internal_pages, uint64_t *internal_compressed_pages,
779     uint64_t *purgeable_nonvolatile_pages, uint64_t *purgeable_nonvolatile_compressed_pages,
780     uint64_t *alternate_accounting_pages, uint64_t *alternate_accounting_compressed_pages,
781     uint64_t *iokit_mapped_pages, uint64_t *page_table_pages, uint64_t *frozen_to_swap_pages);
782 
783 static void memorystatus_get_task_memory_region_count(task_t task, uint64_t *count);
784 
785 static uint32_t memorystatus_build_state(proc_t p);
786 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
787 
788 static bool memorystatus_kill_top_process(bool any, bool sort_flag, uint32_t cause, os_reason_t jetsam_reason,
789     int32_t max_priority, bool only_swappable,
790     int32_t *priority, uint32_t *errors, uint64_t *memory_reclaimed);
791 static boolean_t memorystatus_kill_processes_aggressive(uint32_t cause, int aggr_count, int32_t priority_max, int32_t max_kills, uint32_t *errors, uint64_t *memory_reclaimed);
792 static boolean_t memorystatus_kill_hiwat_proc(uint32_t *errors, boolean_t *purged, uint64_t *memory_reclaimed);
793 
794 /* Priority Band Sorting Routines */
795 static int  memorystatus_sort_bucket(unsigned int bucket_index, int sort_order);
796 static int  memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index, int coal_sort_order);
797 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index);
798 static int  memorystatus_move_list_locked(unsigned int bucket_index, pid_t *pid_list, int list_sz);
799 
800 /* qsort routines */
801 typedef int (*cmpfunc_t)(const void *a, const void *b);
802 extern void qsort(void *a, size_t n, size_t es, cmpfunc_t cmp);
803 static int memstat_asc_cmp(const void *a, const void *b);
804 
805 /* VM pressure */
806 
807 #if CONFIG_SECLUDED_MEMORY
808 extern unsigned int     vm_page_secluded_count;
809 extern unsigned int     vm_page_secluded_count_over_target;
810 #endif /* CONFIG_SECLUDED_MEMORY */
811 
812 /* Aggressive jetsam pages threshold for sysproc aging policy */
813 unsigned int memorystatus_sysproc_aging_aggr_pages = 0;
814 
815 #if CONFIG_JETSAM
816 
817 /* Jetsam Thresholds in MB */
818 TUNABLE_DT(uint32_t, memorystatus_critical_threshold_mb, "/defaults",
819     "kern.memstat_critical_mb", "memorystatus_critical_threshold_mb", 0, TUNABLE_DT_NONE);
820 TUNABLE_DT(uint32_t, memorystatus_idle_threshold_mb, "/defaults",
821     "kern.memstat_idle_mb", "memorystatus_idle_threshold_mb", 0, TUNABLE_DT_NONE);
822 TUNABLE_DT(uint32_t, memorystatus_pressure_threshold_mb, "/defaults",
823     "kern.memstat_pressure_mb", "memorystatus_pressure_threshold_mb", 0, TUNABLE_DT_NONE);
824 TUNABLE_DT(uint32_t, memorystatus_more_free_offset_mb, "/defaults",
825     "kern.memstat_more_free_mb", "memorystatus_more_free_offset_mb", 0, TUNABLE_DT_NONE);
826 
827 /*
828  * Available Pages Thresholds
829  *     critical_base: jetsam above the idle band
830  *     critical_idle: jetsam in the idle band
831  *     more_free_offset: offset applied to critical/idle upon request from userspace
832  *     sysproc_aging_aggr: allow aggressive jetsam due to sysproc aging
833  *     pressure: jetsam hwm violators
834  */
835 unsigned int memorystatus_available_pages = (unsigned int)-1;
836 unsigned int memorystatus_available_pages_pressure = 0;
837 unsigned int memorystatus_available_pages_critical = 0;
838 unsigned int memorystatus_available_pages_critical_base = 0;
839 unsigned int memorystatus_available_pages_critical_idle = 0;
840 TUNABLE_DT_WRITEABLE(unsigned int, memorystatus_swap_all_apps, "/defaults", "kern.swap_all_apps", "kern.swap_all_apps", false, TUNABLE_DT_NONE);
841 /* Will compact the early swapin queue if there are >= this many csegs on it. */
842 static unsigned int memorystatus_swapin_trigger_segments = 10;
843 unsigned int memorystatus_swapin_trigger_pages = 0;
844 
845 #if DEVELOPMENT || DEBUG
846 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_available_pages, 0, "");
847 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_swapin_trigger_pages, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_swapin_trigger_pages, 0, "");
848 #else
849 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages, CTLFLAG_RD | CTLFLAG_MASKED | CTLFLAG_LOCKED, &memorystatus_available_pages, 0, "");
850 #endif /* DEVELOPMENT || DEBUG */
851 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_swap_all_apps, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_swap_all_apps, 0, "");
852 
853 static unsigned int memorystatus_jetsam_policy = kPolicyDefault;
854 unsigned int memorystatus_policy_more_free_offset_pages = 0;
855 static void memorystatus_update_levels_locked(void);
856 
857 static int memorystatus_cmd_set_jetsam_memory_limit(pid_t pid, int32_t high_water_mark, __unused int32_t *retval, boolean_t is_fatal_limit);
858 
859 int32_t max_kill_priority = JETSAM_PRIORITY_MAX;
860 
861 char        memorystatus_jetsam_proc_name_panic[MAXCOMLEN + 1]; /* Panic when we are about to jetsam this process. */
862 uint32_t    memorystatus_jetsam_proc_cause_panic = 0; /* If specified, panic only when we are about to jetsam the process above for this cause. */
863 uint32_t    memorystatus_jetsam_proc_size_panic = 0; /* If specified, panic only when we are about to jetsam the process above and its footprint is more than this in MB. */
864 
865 /* If set, kill swappable processes when we're low on swap space. Currently off until we can allocate more swap space (rdar://87800902) */
866 uint32_t jetsam_kill_on_low_swap = 0;
867 #else /* CONFIG_JETSAM */
868 
869 uint64_t memorystatus_available_pages = (uint64_t)-1;
870 uint64_t memorystatus_available_pages_pressure = (uint64_t)-1;
871 uint64_t memorystatus_available_pages_critical = (uint64_t)-1;
872 
873 int32_t max_kill_priority = JETSAM_PRIORITY_IDLE;
874 #endif /* CONFIG_JETSAM */
875 
876 #if DEVELOPMENT || DEBUG
877 
878 static LCK_GRP_DECLARE(disconnect_page_mappings_lck_grp, "disconnect_page_mappings");
879 static LCK_MTX_DECLARE(disconnect_page_mappings_mutex, &disconnect_page_mappings_lck_grp);
880 
881 extern bool kill_on_no_paging_space;
882 #endif /* DEVELOPMENT || DEBUG */
883 
884 #if DEVELOPMENT || DEBUG
885 static inline uint32_t
roundToNearestMB(uint32_t in)886 roundToNearestMB(uint32_t in)
887 {
888 	return (in + ((1 << 20) - 1)) >> 20;
889 }
890 
891 static int memorystatus_cmd_increase_jetsam_task_limit(pid_t pid, uint32_t byte_increase);
892 #endif
893 
894 #if __arm64__
895 extern int legacy_footprint_entitlement_mode;
896 #endif /* __arm64__ */
897 
898 /* Debug */
899 
900 extern struct knote *vm_find_knote_from_pid(pid_t, struct klist *);
901 
902 #if DEVELOPMENT || DEBUG
903 
904 static unsigned int memorystatus_debug_dump_this_bucket = 0;
905 
906 static void
memorystatus_debug_dump_bucket_locked(unsigned int bucket_index)907 memorystatus_debug_dump_bucket_locked(unsigned int bucket_index)
908 {
909 	proc_t p = NULL;
910 	uint64_t bytes = 0;
911 	int ledger_limit = 0;
912 	unsigned int b = bucket_index;
913 	boolean_t traverse_all_buckets = FALSE;
914 
915 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
916 		traverse_all_buckets = TRUE;
917 		b = 0;
918 	} else {
919 		traverse_all_buckets = FALSE;
920 		b = bucket_index;
921 	}
922 
923 	/*
924 	 * footprint reported in [pages / MB ]
925 	 * limits reported as:
926 	 *      L-limit  proc's Ledger limit
927 	 *      C-limit  proc's Cached limit, should match Ledger
928 	 *      A-limit  proc's Active limit
929 	 *     IA-limit  proc's Inactive limit
930 	 *	F==Fatal,  NF==NonFatal
931 	 */
932 
933 	memorystatus_log_debug("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64);
934 	memorystatus_log_debug("bucket [pid]       [pages / MB]     [state]      [EP / RP / AP]   dirty     deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
935 	p = memorystatus_get_first_proc_locked(&b, traverse_all_buckets);
936 	while (p) {
937 		bytes = get_task_phys_footprint(proc_task(p));
938 		task_get_phys_footprint_limit(proc_task(p), &ledger_limit);
939 		memorystatus_log_debug("%2d     [%5d]     [%5lld /%3lldMB]   0x%-8x   [%2d / %2d / %2d]   0x%-3x   %10lld    [%3d / %3d%s / %3d%s / %3d%s]   %s\n",
940 		    b, proc_getpid(p),
941 		    (bytes / PAGE_SIZE_64),             /* task's footprint converted from bytes to pages     */
942 		    (bytes / (1024ULL * 1024ULL)),      /* task's footprint converted from bytes to MB */
943 		    p->p_memstat_state, p->p_memstat_effectivepriority, p->p_memstat_requestedpriority, p->p_memstat_assertionpriority,
944 		    p->p_memstat_dirty, p->p_memstat_idledeadline,
945 		    ledger_limit,
946 		    p->p_memstat_memlimit,
947 		    (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"),
948 		    p->p_memstat_memlimit_active,
949 		    (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL ? "F " : "NF"),
950 		    p->p_memstat_memlimit_inactive,
951 		    (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL ? "F " : "NF"),
952 		    (*p->p_name ? p->p_name : "unknown"));
953 		p = memorystatus_get_next_proc_locked(&b, p, traverse_all_buckets);
954 	}
955 	memorystatus_log_debug("memorystatus_debug_dump ***END***\n");
956 }
957 
958 static int
959 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
960 {
961 #pragma unused(oidp, arg2)
962 	int bucket_index = 0;
963 	int error;
964 	error = SYSCTL_OUT(req, arg1, sizeof(int));
965 	if (error || !req->newptr) {
966 		return error;
967 	}
968 	error = SYSCTL_IN(req, &bucket_index, sizeof(int));
969 	if (error || !req->newptr) {
970 		return error;
971 	}
972 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
973 		/*
974 		 * All jetsam buckets will be dumped.
975 		 */
976 	} else {
977 		/*
978 		 * Only a single bucket will be dumped.
979 		 */
980 	}
981 
982 	proc_list_lock();
983 	memorystatus_debug_dump_bucket_locked(bucket_index);
984 	proc_list_unlock();
985 	memorystatus_debug_dump_this_bucket = bucket_index;
986 	return error;
987 }
988 
989 /*
990  * Debug aid to look at jetsam buckets and proc jetsam fields.
991  *	Use this sysctl to act on a particular jetsam bucket.
992  *	Writing the sysctl triggers the dump.
993  *      Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
994  */
995 
996 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_debug_dump_this_bucket, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_debug_dump_this_bucket, 0, sysctl_memorystatus_debug_dump_bucket, "I", "");
997 
998 
999 /* Debug aid to aid determination of limit */
1000 
1001 static int
1002 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
1003 {
1004 #pragma unused(oidp, arg2)
1005 	proc_t p;
1006 	unsigned int b = 0;
1007 	int error, enable = 0;
1008 	boolean_t use_active;   /* use the active limit and active limit attributes */
1009 	boolean_t is_fatal;
1010 
1011 	error = SYSCTL_OUT(req, arg1, sizeof(int));
1012 	if (error || !req->newptr) {
1013 		return error;
1014 	}
1015 
1016 	error = SYSCTL_IN(req, &enable, sizeof(int));
1017 	if (error || !req->newptr) {
1018 		return error;
1019 	}
1020 
1021 	if (!(enable == 0 || enable == 1)) {
1022 		return EINVAL;
1023 	}
1024 
1025 	proc_list_lock();
1026 
1027 	p = memorystatus_get_first_proc_locked(&b, TRUE);
1028 	while (p) {
1029 		use_active = proc_jetsam_state_is_active_locked(p);
1030 
1031 		if (enable) {
1032 			if (use_active == TRUE) {
1033 				CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
1034 			} else {
1035 				CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
1036 			}
1037 		} else {
1038 			/*
1039 			 * Disabling limits does not touch the stored variants.
1040 			 * Set the cached limit fields to system_wide defaults.
1041 			 */
1042 			p->p_memstat_memlimit = -1;
1043 			p->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT;
1044 			is_fatal = TRUE;
1045 		}
1046 
1047 		/*
1048 		 * Enforce the cached limit by writing to the ledger.
1049 		 */
1050 		task_set_phys_footprint_limit_internal(proc_task(p), (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit: -1, NULL, use_active, is_fatal);
1051 
1052 		p = memorystatus_get_next_proc_locked(&b, p, TRUE);
1053 	}
1054 
1055 	memorystatus_highwater_enabled = enable;
1056 
1057 	proc_list_unlock();
1058 
1059 	return 0;
1060 }
1061 
1062 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_highwater_enabled, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_highwater_enabled, 0, sysctl_memorystatus_highwater_enable, "I", "");
1063 
1064 SYSCTL_INT(_kern, OID_AUTO, memorystatus_idle_snapshot, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_idle_snapshot, 0, "");
1065 
1066 #if CONFIG_JETSAM
1067 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_available_pages_critical, 0, "");
1068 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical_base, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_available_pages_critical_base, 0, "");
1069 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical_idle, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_available_pages_critical_idle, 0, "");
1070 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_policy_more_free_offset_pages, CTLFLAG_RD, &memorystatus_policy_more_free_offset_pages, 0, "");
1071 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_aggr_sysproc_aging, CTLFLAG_RD, &memorystatus_sysproc_aging_aggr_pages, 0, "");
1072 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_kill_on_low_swap, CTLFLAG_RW, &jetsam_kill_on_low_swap, 0, "");
1073 #if VM_PRESSURE_EVENTS
1074 
1075 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_pressure, CTLFLAG_RW | CTLFLAG_LOCKED, &memorystatus_available_pages_pressure, 0, "");
1076 
1077 #endif /* VM_PRESSURE_EVENTS */
1078 
1079 #endif /* CONFIG_JETSAM */
1080 
1081 #endif /* DEVELOPMENT || DEBUG */
1082 
1083 extern kern_return_t kernel_thread_start_priority(thread_continue_t continuation,
1084     void *parameter,
1085     integer_t priority,
1086     thread_t *new_thread);
1087 
1088 #if DEVELOPMENT || DEBUG
1089 
1090 static int
1091 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1092 {
1093 #pragma unused(arg1, arg2)
1094 	int     error = 0, pid = 0;
1095 	proc_t  p;
1096 
1097 	error = sysctl_handle_int(oidp, &pid, 0, req);
1098 	if (error || !req->newptr) {
1099 		return error;
1100 	}
1101 
1102 	lck_mtx_lock(&disconnect_page_mappings_mutex);
1103 
1104 	if (pid == -1) {
1105 		vm_pageout_disconnect_all_pages();
1106 	} else {
1107 		p = proc_find(pid);
1108 
1109 		if (p != NULL) {
1110 			error = task_disconnect_page_mappings(proc_task(p));
1111 
1112 			proc_rele(p);
1113 
1114 			if (error) {
1115 				error = EIO;
1116 			}
1117 		} else {
1118 			error = EINVAL;
1119 		}
1120 	}
1121 	lck_mtx_unlock(&disconnect_page_mappings_mutex);
1122 
1123 	return error;
1124 }
1125 
1126 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_disconnect_page_mappings, CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_LOCKED | CTLFLAG_MASKED,
1127     0, 0, &sysctl_memorystatus_disconnect_page_mappings, "I", "");
1128 
1129 #endif /* DEVELOPMENT || DEBUG */
1130 
1131 /*
1132  * Sorts the given bucket.
1133  *
1134  * Input:
1135  *	bucket_index - jetsam priority band to be sorted.
1136  *	sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1137  *		Currently sort_order is only meaningful when handling
1138  *		coalitions.
1139  *
1140  * proc_list_lock must be held by the caller.
1141  */
1142 static void
memorystatus_sort_bucket_locked(unsigned int bucket_index,int sort_order)1143 memorystatus_sort_bucket_locked(unsigned int bucket_index, int sort_order)
1144 {
1145 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
1146 	if (memstat_bucket[bucket_index].count == 0) {
1147 		return;
1148 	}
1149 
1150 	switch (bucket_index) {
1151 	case JETSAM_PRIORITY_FOREGROUND:
1152 		if (memorystatus_sort_by_largest_coalition_locked(bucket_index, sort_order) == 0) {
1153 			/*
1154 			 * Fall back to per process sorting when zero coalitions are found.
1155 			 */
1156 			memorystatus_sort_by_largest_process_locked(bucket_index);
1157 		}
1158 		break;
1159 	default:
1160 		memorystatus_sort_by_largest_process_locked(bucket_index);
1161 		break;
1162 	}
1163 }
1164 
1165 /*
1166  * Picks the sorting routine for a given jetsam priority band.
1167  *
1168  * Input:
1169  *	bucket_index - jetsam priority band to be sorted.
1170  *	sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1171  *		Currently sort_order is only meaningful when handling
1172  *		coalitions.
1173  *
1174  * Return:
1175  *	0     on success
1176  *      non-0 on failure
1177  */
1178 static int
memorystatus_sort_bucket(unsigned int bucket_index,int sort_order)1179 memorystatus_sort_bucket(unsigned int bucket_index, int sort_order)
1180 {
1181 	int coal_sort_order;
1182 
1183 	/*
1184 	 * Verify the jetsam priority
1185 	 */
1186 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
1187 		return EINVAL;
1188 	}
1189 
1190 #if DEVELOPMENT || DEBUG
1191 	if (sort_order == JETSAM_SORT_DEFAULT) {
1192 		coal_sort_order = COALITION_SORT_DEFAULT;
1193 	} else {
1194 		coal_sort_order = sort_order;           /* only used for testing scenarios */
1195 	}
1196 #else
1197 	/* Verify default */
1198 	if (sort_order == JETSAM_SORT_DEFAULT) {
1199 		coal_sort_order = COALITION_SORT_DEFAULT;
1200 	} else {
1201 		return EINVAL;
1202 	}
1203 #endif
1204 
1205 	proc_list_lock();
1206 	memorystatus_sort_bucket_locked(bucket_index, coal_sort_order);
1207 	proc_list_unlock();
1208 
1209 	return 0;
1210 }
1211 
1212 /*
1213  * Sort processes by size for a single jetsam bucket.
1214  */
1215 
1216 static void
memorystatus_sort_by_largest_process_locked(unsigned int bucket_index)1217 memorystatus_sort_by_largest_process_locked(unsigned int bucket_index)
1218 {
1219 	proc_t p = NULL, insert_after_proc = NULL, max_proc = NULL;
1220 	proc_t next_p = NULL, prev_max_proc = NULL;
1221 	uint32_t pages = 0, max_pages = 0;
1222 	memstat_bucket_t *current_bucket;
1223 
1224 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
1225 		return;
1226 	}
1227 
1228 	current_bucket = &memstat_bucket[bucket_index];
1229 
1230 	p = TAILQ_FIRST(&current_bucket->list);
1231 
1232 	while (p) {
1233 		memorystatus_get_task_page_counts(proc_task(p), &pages, NULL, NULL);
1234 		max_pages = pages;
1235 		max_proc = p;
1236 		prev_max_proc = p;
1237 
1238 		while ((next_p = TAILQ_NEXT(p, p_memstat_list)) != NULL) {
1239 			/* traversing list until we find next largest process */
1240 			p = next_p;
1241 			memorystatus_get_task_page_counts(proc_task(p), &pages, NULL, NULL);
1242 			if (pages > max_pages) {
1243 				max_pages = pages;
1244 				max_proc = p;
1245 			}
1246 		}
1247 
1248 		if (prev_max_proc != max_proc) {
1249 			/* found a larger process, place it in the list */
1250 			TAILQ_REMOVE(&current_bucket->list, max_proc, p_memstat_list);
1251 			if (insert_after_proc == NULL) {
1252 				TAILQ_INSERT_HEAD(&current_bucket->list, max_proc, p_memstat_list);
1253 			} else {
1254 				TAILQ_INSERT_AFTER(&current_bucket->list, insert_after_proc, max_proc, p_memstat_list);
1255 			}
1256 			prev_max_proc = max_proc;
1257 		}
1258 
1259 		insert_after_proc = max_proc;
1260 
1261 		p = TAILQ_NEXT(max_proc, p_memstat_list);
1262 	}
1263 }
1264 
1265 proc_t
memorystatus_get_first_proc_locked(unsigned int * bucket_index,boolean_t search)1266 memorystatus_get_first_proc_locked(unsigned int *bucket_index, boolean_t search)
1267 {
1268 	memstat_bucket_t *current_bucket;
1269 	proc_t next_p;
1270 
1271 	if ((*bucket_index) >= MEMSTAT_BUCKET_COUNT) {
1272 		return NULL;
1273 	}
1274 
1275 	current_bucket = &memstat_bucket[*bucket_index];
1276 	next_p = TAILQ_FIRST(&current_bucket->list);
1277 	if (!next_p && search) {
1278 		while (!next_p && (++(*bucket_index) < MEMSTAT_BUCKET_COUNT)) {
1279 			current_bucket = &memstat_bucket[*bucket_index];
1280 			next_p = TAILQ_FIRST(&current_bucket->list);
1281 		}
1282 	}
1283 
1284 	return next_p;
1285 }
1286 
1287 proc_t
memorystatus_get_next_proc_locked(unsigned int * bucket_index,proc_t p,boolean_t search)1288 memorystatus_get_next_proc_locked(unsigned int *bucket_index, proc_t p, boolean_t search)
1289 {
1290 	memstat_bucket_t *current_bucket;
1291 	proc_t next_p;
1292 
1293 	if (!p || ((*bucket_index) >= MEMSTAT_BUCKET_COUNT)) {
1294 		return NULL;
1295 	}
1296 
1297 	next_p = TAILQ_NEXT(p, p_memstat_list);
1298 	while (!next_p && search && (++(*bucket_index) < MEMSTAT_BUCKET_COUNT)) {
1299 		current_bucket = &memstat_bucket[*bucket_index];
1300 		next_p = TAILQ_FIRST(&current_bucket->list);
1301 	}
1302 
1303 	return next_p;
1304 }
1305 
1306 jetsam_thread_state_t *jetsam_threads;
1307 
1308 /* Maximum number of jetsam threads allowed */
1309 #define JETSAM_THREADS_LIMIT   3
1310 
1311 /* Number of active jetsam threads */
1312 _Atomic int active_jetsam_threads = 1;
1313 
1314 /* Number of maximum jetsam threads configured */
1315 int max_jetsam_threads = JETSAM_THREADS_LIMIT;
1316 
1317 /*
1318  * Global switch for enabling fast jetsam. Fast jetsam is
1319  * hooked up via the system_override() system call. It has the
1320  * following effects:
1321  * - Raise the jetsam threshold ("clear-the-deck")
1322  * - Enabled parallel jetsam on eligible devices
1323  */
1324 #if __AMP__
1325 int fast_jetsam_enabled = 1;
1326 #else /* __AMP__ */
1327 int fast_jetsam_enabled = 0;
1328 #endif /* __AMP__ */
1329 
1330 static jetsam_thread_state_t *
jetsam_current_thread()1331 jetsam_current_thread()
1332 {
1333 	for (int thr_id = 0; thr_id < max_jetsam_threads; thr_id++) {
1334 		if (jetsam_threads[thr_id].thread == current_thread()) {
1335 			return &(jetsam_threads[thr_id]);
1336 		}
1337 	}
1338 	return NULL;
1339 }
1340 
1341 #if CONFIG_JETSAM
1342 static void
initialize_entitled_max_task_limit()1343 initialize_entitled_max_task_limit()
1344 {
1345 	/**
1346 	 * We've already stored the potential boot-arg "entitled_max_task_pmem" in
1347 	 * memorystatus_entitled_max_task_footprint_mb as a TUNABLE_DT.  We provide
1348 	 * argptr=NULL and max_len=0 here to check only for existence of the boot-arg.
1349 	 *
1350 	 * The boot-arg takes precedence over memorystatus_swap_all_apps.
1351 	 */
1352 	if (!PE_parse_boot_argn("entitled_max_task_pmem", NULL, 0) && memorystatus_swap_all_apps) {
1353 		/*
1354 		 * When we have swap, we let entitled apps go up to the dram config
1355 		 * regardless of what's set in EDT,
1356 		 * This can still be overriden with the entitled_max_task_pmem boot-arg.
1357 		 */
1358 		memorystatus_entitled_max_task_footprint_mb = (int32_t) (max_mem_actual / (1ULL << 20));
1359 	}
1360 
1361 	if (memorystatus_entitled_max_task_footprint_mb < 0) {
1362 		memorystatus_log_error("Invalid value (%d) for entitled_max_task_pmem. Setting to 0\n",
1363 		    memorystatus_entitled_max_task_footprint_mb);
1364 		memorystatus_entitled_max_task_footprint_mb = 0;
1365 	}
1366 }
1367 
1368 #endif /* CONFIG_JETSAM */
1369 
1370 
1371 __private_extern__ void
memorystatus_init(void)1372 memorystatus_init(void)
1373 {
1374 	kern_return_t result;
1375 	int i;
1376 
1377 #if CONFIG_FREEZE
1378 	memorystatus_freeze_jetsam_band = JETSAM_PRIORITY_FREEZER;
1379 	memorystatus_frozen_processes_max = FREEZE_PROCESSES_MAX;
1380 	memorystatus_frozen_shared_mb_max = ((MAX_FROZEN_SHARED_MB_PERCENT * max_task_footprint_mb) / 100); /* 10% of the system wide task limit */
1381 	memorystatus_freeze_shared_mb_per_process_max = (memorystatus_frozen_shared_mb_max / 4);
1382 	memorystatus_freeze_pages_min = FREEZE_PAGES_MIN;
1383 	memorystatus_freeze_pages_max = FREEZE_PAGES_MAX;
1384 	memorystatus_max_frozen_demotions_daily = MAX_FROZEN_PROCESS_DEMOTIONS;
1385 	memorystatus_thaw_count_demotion_threshold = MIN_THAW_DEMOTION_THRESHOLD;
1386 	memorystatus_min_thaw_refreeze_threshold = MIN_THAW_REFREEZE_THRESHOLD;
1387 #endif /* CONFIG_FREEZE */
1388 
1389 #if DEVELOPMENT || DEBUG
1390 	if (kill_on_no_paging_space) {
1391 		max_kill_priority = JETSAM_PRIORITY_MAX;
1392 	}
1393 #endif
1394 	// Note: no-op pending rdar://27006343 (Custom kernel log handles)
1395 	memorystatus_log_handle = os_log_create("com.apple.xnu", "memorystatus");
1396 
1397 	/* Init buckets */
1398 	for (i = 0; i < MEMSTAT_BUCKET_COUNT; i++) {
1399 		TAILQ_INIT(&memstat_bucket[i].list);
1400 		memstat_bucket[i].count = 0;
1401 		memstat_bucket[i].relaunch_high_count = 0;
1402 	}
1403 	memorystatus_idle_demotion_call = thread_call_allocate((thread_call_func_t)memorystatus_perform_idle_demotion, NULL);
1404 
1405 	nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS * NSEC_PER_SEC, &memorystatus_sysprocs_idle_delay_time);
1406 	nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS * NSEC_PER_SEC, &memorystatus_apps_idle_delay_time);
1407 
1408 #if CONFIG_JETSAM
1409 	bzero(memorystatus_jetsam_proc_name_panic, MAXCOMLEN + 1);
1410 	if (PE_parse_boot_argn("jetsam_proc_name_panic", &memorystatus_jetsam_proc_name_panic, MAXCOMLEN + 1)) {
1411 		/*
1412 		 * No bounds check to see if this is a valid cause.
1413 		 * This is a debugging aid. The callers should know precisely which cause they wish to track.
1414 		 */
1415 		PE_parse_boot_argn("jetsam_proc_cause_panic", &memorystatus_jetsam_proc_cause_panic, sizeof(memorystatus_jetsam_proc_cause_panic));
1416 		PE_parse_boot_argn("jetsam_proc_size_panic", &memorystatus_jetsam_proc_size_panic, sizeof(memorystatus_jetsam_proc_size_panic));
1417 	}
1418 
1419 	if (memorystatus_swap_all_apps && vm_page_donate_mode == VM_PAGE_DONATE_DISABLED) {
1420 		panic("kern.swap_all_apps is not supported on this platform");
1421 	}
1422 
1423 	/*
1424 	 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1425 	 * band and must be below it in priority. This is so that we don't have to make
1426 	 * our 'aging' code worry about a mix of processes, some of which need to age
1427 	 * and some others that need to stay elevated in the jetsam bands.
1428 	 */
1429 	assert(JETSAM_PRIORITY_ELEVATED_INACTIVE > system_procs_aging_band);
1430 	assert(JETSAM_PRIORITY_ELEVATED_INACTIVE > applications_aging_band);
1431 
1432 	/* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1433 	if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot, sizeof(memorystatus_idle_snapshot))) {
1434 		/* ...no boot-arg, so check the device tree */
1435 		PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot, sizeof(memorystatus_idle_snapshot));
1436 	}
1437 
1438 	memorystatus_sysproc_aging_aggr_pages = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_AGGR_SYSPROC_AGING_PERCENTAGE);
1439 
1440 	if (max_mem <= MEMORYSTATUS_SMALL_MEMORY_THRESHOLD) {
1441 		memorystatus_delta = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_DELTA_PERCENTAGE_SMALL);
1442 	} else {
1443 		memorystatus_delta = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_DELTA_PERCENTAGE_LARGE);
1444 	}
1445 
1446 	if (memorystatus_critical_threshold_mb != 0) {
1447 		memorystatus_available_pages_critical_base = (unsigned int)atop_64((uint64_t)memorystatus_critical_threshold_mb << 20);
1448 	} else if (max_mem <= MEMORYSTATUS_SMALL_MEMORY_THRESHOLD) {
1449 		memorystatus_available_pages_critical_base = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_CRITICAL_BASE_PERCENTAGE_SMALL);
1450 	} else {
1451 		memorystatus_available_pages_critical_base = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_CRITICAL_BASE_PERCENTAGE_LARGE);
1452 	}
1453 	assert(memorystatus_available_pages_critical_base < (unsigned int)atop_64(max_mem));
1454 
1455 	/*
1456 	 * For historical reasons, devices with "medium"-sized memory configs have a different critical:idle:pressure ratio
1457 	 */
1458 	if ((memorystatus_idle_threshold_mb != 0)) {
1459 		memorystatus_available_pages_critical_idle = (unsigned int)atop_64((uint64_t)memorystatus_idle_threshold_mb << 20);
1460 	} else {
1461 		if ((max_mem > MEMORYSTATUS_SMALL_MEMORY_THRESHOLD) &&
1462 		    (max_mem <= MEMORYSTATUS_MEDIUM_MEMORY_THRESHOLD)) {
1463 			memorystatus_available_pages_critical_idle = (MEMORYSTATUS_CRITICAL_IDLE_RATIO_NUM_MEDIUM * memorystatus_available_pages_critical_base) /
1464 			    MEMORYSTATUS_CRITICAL_IDLE_RATIO_DENOM_MEDIUM;
1465 		} else {
1466 			memorystatus_available_pages_critical_idle = (MEMORYSTATUS_CRITICAL_IDLE_RATIO_NUM * memorystatus_available_pages_critical_base) /
1467 			    MEMORYSTATUS_CRITICAL_IDLE_RATIO_DENOM;
1468 		}
1469 	}
1470 	assert(memorystatus_available_pages_critical_idle < (unsigned int)atop_64(max_mem));
1471 
1472 	if (memorystatus_pressure_threshold_mb != 0) {
1473 		memorystatus_available_pages_pressure = (unsigned int)atop_64((uint64_t)memorystatus_pressure_threshold_mb << 20);
1474 	} else {
1475 		if ((max_mem > MEMORYSTATUS_SMALL_MEMORY_THRESHOLD) &&
1476 		    (max_mem <= MEMORYSTATUS_MEDIUM_MEMORY_THRESHOLD)) {
1477 			memorystatus_available_pages_pressure = (MEMORYSTATUS_PRESSURE_RATIO_NUM_MEDIUM * memorystatus_available_pages_critical_base) /
1478 			    MEMORYSTATUS_PRESSURE_RATIO_DENOM_MEDIUM;
1479 		} else {
1480 			memorystatus_available_pages_pressure = (MEMORYSTATUS_PRESSURE_RATIO_NUM * memorystatus_available_pages_critical_base) /
1481 			    MEMORYSTATUS_PRESSURE_RATIO_DENOM;
1482 		}
1483 	}
1484 	assert(memorystatus_available_pages_pressure < (unsigned int)atop_64(max_mem));
1485 
1486 	if (memorystatus_more_free_offset_mb != 0) {
1487 		memorystatus_policy_more_free_offset_pages = (unsigned int)atop_64((uint64_t)memorystatus_more_free_offset_mb);
1488 	} else {
1489 		memorystatus_policy_more_free_offset_pages = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_MORE_FREE_OFFSET_PERCENTAGE);
1490 	}
1491 	assert(memorystatus_policy_more_free_offset_pages < (unsigned int)atop_64(max_mem));
1492 
1493 	/* Set the swapin trigger in pages based on the maximum size allocated for each c_seg */
1494 	memorystatus_swapin_trigger_pages = (unsigned int) atop_64(memorystatus_swapin_trigger_segments * c_seg_allocsize);
1495 
1496 	/* Jetsam Loop Detection */
1497 	if (max_mem <= (512 * 1024 * 1024)) {
1498 		/* 512 MB devices */
1499 		memorystatus_jld_eval_period_msecs = 8000;      /* 8000 msecs == 8 second window */
1500 	} else {
1501 		/* 1GB and larger devices */
1502 		memorystatus_jld_eval_period_msecs = 6000;      /* 6000 msecs == 6 second window */
1503 	}
1504 
1505 	memorystatus_jld_enabled = TRUE;
1506 
1507 	/* No contention at this point */
1508 	memorystatus_update_levels_locked();
1509 
1510 	initialize_entitled_max_task_limit();
1511 #endif /* CONFIG_JETSAM */
1512 
1513 	memorystatus_jetsam_snapshot_max = maxproc;
1514 
1515 	memorystatus_jetsam_snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
1516 	    (sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_max);
1517 
1518 	memorystatus_jetsam_snapshot = kalloc_data(memorystatus_jetsam_snapshot_size, Z_WAITOK | Z_ZERO);
1519 	if (!memorystatus_jetsam_snapshot) {
1520 		panic("Could not allocate memorystatus_jetsam_snapshot");
1521 	}
1522 
1523 #if CONFIG_FREEZE
1524 	memorystatus_jetsam_snapshot_freezer_max = memorystatus_jetsam_snapshot_max / JETSAM_SNAPSHOT_FREEZER_MAX_FACTOR;
1525 	memorystatus_jetsam_snapshot_freezer_size = sizeof(memorystatus_jetsam_snapshot_t) +
1526 	    (sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_freezer_max);
1527 
1528 	memorystatus_jetsam_snapshot_freezer =
1529 	    zalloc_permanent(memorystatus_jetsam_snapshot_freezer_size, ZALIGN_PTR);
1530 #endif /* CONFIG_FREEZE */
1531 
1532 	nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS * NSEC_PER_SEC, &memorystatus_jetsam_snapshot_timeout);
1533 
1534 	memset(&memorystatus_at_boot_snapshot, 0, sizeof(memorystatus_jetsam_snapshot_t));
1535 
1536 #if CONFIG_FREEZE
1537 	if (memorystatus_freeze_threshold_mb != 0) {
1538 		memorystatus_freeze_threshold = (unsigned int)atop_64((uint64_t)memorystatus_freeze_threshold_mb << 20);
1539 	} else {
1540 		memorystatus_freeze_threshold = (unsigned int)MEMSTAT_PERCENT_TOTAL_PAGES(MEMORYSTATUS_FREEZE_THRESHOLD_PERCENTAGE);
1541 	}
1542 	assert(memorystatus_freeze_threshold < (unsigned int)atop_64(max_mem));
1543 
1544 	if (memorystatus_swap_all_apps) {
1545 		/*
1546 		 * Swap is enabled, so we expect a larger working set & larger apps.
1547 		 * Adjust thresholds accordingly.
1548 		 */
1549 		memorystatus_freeze_configure_for_swap();
1550 	}
1551 #endif
1552 
1553 	/* Check the boot-arg to see if fast jetsam is allowed */
1554 	if (!PE_parse_boot_argn("fast_jetsam_enabled", &fast_jetsam_enabled, sizeof(fast_jetsam_enabled))) {
1555 		fast_jetsam_enabled = 0;
1556 	}
1557 
1558 	/* Check the boot-arg to configure the maximum number of jetsam threads */
1559 	if (!PE_parse_boot_argn("max_jetsam_threads", &max_jetsam_threads, sizeof(max_jetsam_threads))) {
1560 		max_jetsam_threads = JETSAM_THREADS_LIMIT;
1561 	}
1562 
1563 	/* Restrict the maximum number of jetsam threads to JETSAM_THREADS_LIMIT */
1564 	if (max_jetsam_threads > JETSAM_THREADS_LIMIT) {
1565 		max_jetsam_threads = JETSAM_THREADS_LIMIT;
1566 	}
1567 
1568 	/* For low CPU systems disable fast jetsam mechanism */
1569 	if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
1570 		max_jetsam_threads = 1;
1571 		fast_jetsam_enabled = 0;
1572 	}
1573 
1574 #if DEVELOPMENT || DEBUG
1575 	if (PE_parse_boot_argn("-memorystatus-skip-fg-notify", &i, sizeof(i))) {
1576 		memorystatus_should_issue_fg_band_notify = false;
1577 	}
1578 #endif /* DEVELOPMENT || DEBUG */
1579 
1580 	/* Initialize the jetsam_threads state array */
1581 	jetsam_threads = zalloc_permanent(sizeof(jetsam_thread_state_t) *
1582 	    max_jetsam_threads, ZALIGN(jetsam_thread_state_t));
1583 
1584 	/* Initialize all the jetsam threads */
1585 	for (i = 0; i < max_jetsam_threads; i++) {
1586 		jetsam_threads[i].inited = FALSE;
1587 		jetsam_threads[i].index = i;
1588 		result = kernel_thread_start_priority(memorystatus_thread, NULL, 95 /* MAXPRI_KERNEL */, &jetsam_threads[i].thread);
1589 		if (result != KERN_SUCCESS) {
1590 			panic("Could not create memorystatus_thread %d", i);
1591 		}
1592 		thread_deallocate(jetsam_threads[i].thread);
1593 	}
1594 
1595 #if VM_PRESSURE_EVENTS
1596 	memorystatus_notify_init();
1597 #endif /* VM_PRESSURE_EVENTS */
1598 }
1599 
1600 #if CONFIG_JETSAM
1601 bool
memorystatus_disable_swap(void)1602 memorystatus_disable_swap(void)
1603 {
1604 #if DEVELOPMENT || DEBUG
1605 	int boot_arg_val = 0;
1606 	if (PE_parse_boot_argn("kern.swap_all_apps", &boot_arg_val, sizeof(boot_arg_val))) {
1607 		if (boot_arg_val) {
1608 			/* Can't disable app swap if it was set via a boot-arg */
1609 			return false;
1610 		}
1611 	}
1612 #endif /* DEVELOPMENT || DEBUG */
1613 	memorystatus_swap_all_apps = false;
1614 #if CONFIG_FREEZE
1615 	/* Go back to the smaller freezer thresholds */
1616 	memorystatus_freeze_disable_swap();
1617 #endif /* CONFIG_FREEZE */
1618 	initialize_entitled_max_task_limit();
1619 	return true;
1620 }
1621 #endif /* CONFIG_JETSAM */
1622 
1623 /* Centralised for the purposes of allowing panic-on-jetsam */
1624 extern void
1625 vm_run_compactor(void);
1626 extern void
1627 vm_wake_compactor_swapper(void);
1628 
1629 /*
1630  * The jetsam no frills kill call
1631  *      Return: 0 on success
1632  *		error code on failure (EINVAL...)
1633  */
1634 static int
jetsam_do_kill(proc_t p,int jetsam_flags,os_reason_t jetsam_reason)1635 jetsam_do_kill(proc_t p, int jetsam_flags, os_reason_t jetsam_reason)
1636 {
1637 	int error = 0;
1638 	error = exit_with_reason(p, W_EXITCODE(0, SIGKILL), (int *)NULL, FALSE, FALSE, jetsam_flags, jetsam_reason);
1639 	return error;
1640 }
1641 
1642 /*
1643  * Wrapper for processes exiting with memorystatus details
1644  */
1645 static boolean_t
memorystatus_do_kill(proc_t p,uint32_t cause,os_reason_t jetsam_reason,uint64_t * footprint_of_killed_proc)1646 memorystatus_do_kill(proc_t p, uint32_t cause, os_reason_t jetsam_reason, uint64_t *footprint_of_killed_proc)
1647 {
1648 	int error = 0;
1649 	__unused pid_t victim_pid = proc_getpid(p);
1650 	uint64_t footprint = get_task_phys_footprint(proc_task(p));
1651 #if (KDEBUG_LEVEL >= KDEBUG_LEVEL_STANDARD)
1652 	int32_t memstat_effectivepriority = p->p_memstat_effectivepriority;
1653 #endif /* (KDEBUG_LEVEL >= KDEBUG_LEVEL_STANDARD) */
1654 
1655 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_DO_KILL) | DBG_FUNC_START,
1656 	    victim_pid, cause, vm_page_free_count, footprint);
1657 	DTRACE_MEMORYSTATUS4(memorystatus_do_kill, proc_t, p, os_reason_t, jetsam_reason, uint32_t, cause, uint64_t, footprint);
1658 
1659 #if CONFIG_JETSAM
1660 	if (*p->p_name && !strncmp(memorystatus_jetsam_proc_name_panic, p->p_name, sizeof(p->p_name))) { /* name */
1661 		if ((!memorystatus_jetsam_proc_cause_panic || cause == memorystatus_jetsam_proc_cause_panic) && /* cause */
1662 		    (!memorystatus_jetsam_proc_size_panic || (footprint >> 20) >= memorystatus_jetsam_proc_size_panic)) { /* footprint */
1663 			panic("memorystatus_do_kill(): requested panic on jetsam of %s (cause: %d and footprint: %llu mb)",
1664 			    memorystatus_jetsam_proc_name_panic, cause, footprint >> 20);
1665 		}
1666 	}
1667 #else /* CONFIG_JETSAM */
1668 #pragma unused(cause)
1669 #endif /* CONFIG_JETSAM */
1670 
1671 	if (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND) {
1672 		memorystatus_log(
1673 			"memorystatus: killing process %d [%s] in high band %s (%d) - memorystatus_available_pages: %llu\n",
1674 			proc_getpid(p), (*p->p_name ? p->p_name : "unknown"),
1675 			memorystatus_priority_band_name(p->p_memstat_effectivepriority), p->p_memstat_effectivepriority,
1676 			(uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
1677 	}
1678 
1679 	/*
1680 	 * The jetsam_reason (os_reason_t) has enough information about the kill cause.
1681 	 * We don't really need jetsam_flags anymore, so it's okay that not all possible kill causes have been mapped.
1682 	 */
1683 	int jetsam_flags = P_LTERM_JETSAM;
1684 	switch (cause) {
1685 	case kMemorystatusKilledHiwat:                                          jetsam_flags |= P_JETSAM_HIWAT; break;
1686 	case kMemorystatusKilledVnodes:                                         jetsam_flags |= P_JETSAM_VNODE; break;
1687 	case kMemorystatusKilledVMPageShortage:                         jetsam_flags |= P_JETSAM_VMPAGESHORTAGE; break;
1688 	case kMemorystatusKilledVMCompressorThrashing:
1689 	case kMemorystatusKilledVMCompressorSpaceShortage:      jetsam_flags |= P_JETSAM_VMTHRASHING; break;
1690 	case kMemorystatusKilledFCThrashing:                            jetsam_flags |= P_JETSAM_FCTHRASHING; break;
1691 	case kMemorystatusKilledPerProcessLimit:                        jetsam_flags |= P_JETSAM_PID; break;
1692 	case kMemorystatusKilledIdleExit:                                       jetsam_flags |= P_JETSAM_IDLEEXIT; break;
1693 	}
1694 	/* jetsam_do_kill drops a reference. */
1695 	os_reason_ref(jetsam_reason);
1696 	error = jetsam_do_kill(p, jetsam_flags, jetsam_reason);
1697 	*footprint_of_killed_proc = ((error == 0) ? footprint : 0);
1698 
1699 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_DO_KILL) | DBG_FUNC_END,
1700 	    victim_pid, memstat_effectivepriority, vm_page_free_count, error);
1701 
1702 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_COMPACTOR_RUN) | DBG_FUNC_START,
1703 	    victim_pid, cause, vm_page_free_count, *footprint_of_killed_proc);
1704 
1705 	if (jetsam_reason->osr_code == JETSAM_REASON_VNODE) {
1706 		/*
1707 		 * vnode jetsams are syncronous and not caused by memory pressure.
1708 		 * Running the compactor on this thread adds significant latency to the filesystem operation
1709 		 * that triggered this jetsam.
1710 		 * Kick of compactor thread asyncronously instead.
1711 		 */
1712 		vm_wake_compactor_swapper();
1713 	} else {
1714 		vm_run_compactor();
1715 	}
1716 
1717 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_COMPACTOR_RUN) | DBG_FUNC_END,
1718 	    victim_pid, cause, vm_page_free_count);
1719 
1720 	os_reason_free(jetsam_reason);
1721 	return error == 0;
1722 }
1723 
1724 /*
1725  * Node manipulation
1726  */
1727 
1728 static void
memorystatus_check_levels_locked(void)1729 memorystatus_check_levels_locked(void)
1730 {
1731 #if CONFIG_JETSAM
1732 	/* Update levels */
1733 	memorystatus_update_levels_locked();
1734 #else /* CONFIG_JETSAM */
1735 	/*
1736 	 * Nothing to do here currently since we update
1737 	 * memorystatus_available_pages in vm_pressure_response.
1738 	 */
1739 #endif /* CONFIG_JETSAM */
1740 }
1741 
1742 /*
1743  * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1744  * For an application: that means no longer in the FG band
1745  * For a daemon: that means no longer in its 'requested' jetsam priority band
1746  */
1747 
1748 int
memorystatus_update_inactive_jetsam_priority_band(pid_t pid,uint32_t op_flags,int jetsam_prio,boolean_t effective_now)1749 memorystatus_update_inactive_jetsam_priority_band(pid_t pid, uint32_t op_flags, int jetsam_prio, boolean_t effective_now)
1750 {
1751 	int error = 0;
1752 	boolean_t enable = FALSE;
1753 	proc_t  p = NULL;
1754 
1755 	if (op_flags == MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE) {
1756 		enable = TRUE;
1757 	} else if (op_flags == MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE) {
1758 		enable = FALSE;
1759 	} else {
1760 		return EINVAL;
1761 	}
1762 
1763 	p = proc_find(pid);
1764 	if (p != NULL) {
1765 		if ((enable && ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) ||
1766 		    (!enable && ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) == 0))) {
1767 			/*
1768 			 * No change in state.
1769 			 */
1770 		} else {
1771 			proc_list_lock();
1772 
1773 			if (enable) {
1774 				p->p_memstat_state |= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND;
1775 				memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1776 
1777 				if (effective_now) {
1778 					if (p->p_memstat_effectivepriority < jetsam_prio) {
1779 						if (memorystatus_highwater_enabled) {
1780 							/*
1781 							 * Process is about to transition from
1782 							 * inactive --> active
1783 							 * assign active state
1784 							 */
1785 							boolean_t is_fatal;
1786 							boolean_t use_active = TRUE;
1787 							CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
1788 							task_set_phys_footprint_limit_internal(proc_task(p), (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1, NULL, use_active, is_fatal);
1789 						}
1790 						memorystatus_update_priority_locked(p, jetsam_prio, FALSE, FALSE);
1791 					}
1792 				} else {
1793 					if (isProcessInAgingBands(p)) {
1794 						memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1795 					}
1796 				}
1797 			} else {
1798 				p->p_memstat_state &= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND;
1799 				memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1800 
1801 				if (effective_now) {
1802 					if (p->p_memstat_effectivepriority == jetsam_prio) {
1803 						memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1804 					}
1805 				} else {
1806 					if (isProcessInAgingBands(p)) {
1807 						memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1808 					}
1809 				}
1810 			}
1811 
1812 			proc_list_unlock();
1813 		}
1814 		proc_rele(p);
1815 		error = 0;
1816 	} else {
1817 		error = ESRCH;
1818 	}
1819 
1820 	return error;
1821 }
1822 
1823 static void
memorystatus_perform_idle_demotion(__unused void * spare1,__unused void * spare2)1824 memorystatus_perform_idle_demotion(__unused void *spare1, __unused void *spare2)
1825 {
1826 	proc_t p;
1827 	uint64_t current_time = 0, idle_delay_time = 0;
1828 	int demote_prio_band = 0;
1829 	memstat_bucket_t *demotion_bucket;
1830 
1831 	memorystatus_log_debug("memorystatus_perform_idle_demotion()\n");
1832 
1833 	if (!system_procs_aging_band && !applications_aging_band) {
1834 		return;
1835 	}
1836 
1837 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_IDLE_DEMOTE) | DBG_FUNC_START);
1838 
1839 	current_time = mach_absolute_time();
1840 
1841 	proc_list_lock();
1842 
1843 	demote_prio_band = JETSAM_PRIORITY_IDLE + 1;
1844 
1845 	for (; demote_prio_band < JETSAM_PRIORITY_MAX; demote_prio_band++) {
1846 		if (demote_prio_band != system_procs_aging_band && demote_prio_band != applications_aging_band) {
1847 			continue;
1848 		}
1849 
1850 		demotion_bucket = &memstat_bucket[demote_prio_band];
1851 		p = TAILQ_FIRST(&demotion_bucket->list);
1852 
1853 		while (p) {
1854 			memorystatus_log_debug("memorystatus_perform_idle_demotion() found %d\n", proc_getpid(p));
1855 
1856 			assert(p->p_memstat_idledeadline);
1857 
1858 			assert(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS);
1859 
1860 			if (current_time >= p->p_memstat_idledeadline) {
1861 				if ((isSysProc(p) &&
1862 				    ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED | P_DIRTY_IS_DIRTY)) != P_DIRTY_IDLE_EXIT_ENABLED)) || /* system proc marked dirty*/
1863 				    task_has_assertions((struct task *)(proc_task(p)))) {     /* has outstanding assertions which might indicate outstanding work too */
1864 					idle_delay_time = (isSysProc(p)) ? memorystatus_sysprocs_idle_time(p) : memorystatus_apps_idle_time(p);
1865 
1866 					p->p_memstat_idledeadline += idle_delay_time;
1867 					p = TAILQ_NEXT(p, p_memstat_list);
1868 				} else {
1869 					proc_t next_proc = NULL;
1870 
1871 					next_proc = TAILQ_NEXT(p, p_memstat_list);
1872 					memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1873 
1874 					memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, false, true);
1875 
1876 					p = next_proc;
1877 					continue;
1878 				}
1879 			} else {
1880 				// No further candidates
1881 				break;
1882 			}
1883 		}
1884 	}
1885 
1886 	memorystatus_reschedule_idle_demotion_locked();
1887 
1888 	proc_list_unlock();
1889 
1890 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_IDLE_DEMOTE) | DBG_FUNC_END);
1891 }
1892 
1893 static void
memorystatus_schedule_idle_demotion_locked(proc_t p,boolean_t set_state)1894 memorystatus_schedule_idle_demotion_locked(proc_t p, boolean_t set_state)
1895 {
1896 	boolean_t present_in_sysprocs_aging_bucket = FALSE;
1897 	boolean_t present_in_apps_aging_bucket = FALSE;
1898 	uint64_t  idle_delay_time = 0;
1899 
1900 	if (!system_procs_aging_band && !applications_aging_band) {
1901 		return;
1902 	}
1903 
1904 	if ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) ||
1905 	    (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION)) {
1906 		/*
1907 		 * This process isn't going to be making the trip to the lower bands.
1908 		 */
1909 		return;
1910 	}
1911 
1912 	if (isProcessInAgingBands(p)) {
1913 		assert((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) != P_DIRTY_AGING_IN_PROGRESS);
1914 
1915 		if (isSysProc(p) && system_procs_aging_band) {
1916 			present_in_sysprocs_aging_bucket = TRUE;
1917 		} else if (isApp(p) && applications_aging_band) {
1918 			present_in_apps_aging_bucket = TRUE;
1919 		}
1920 	}
1921 
1922 	assert(!present_in_sysprocs_aging_bucket);
1923 	assert(!present_in_apps_aging_bucket);
1924 
1925 	memorystatus_log_info(
1926 		"memorystatus_schedule_idle_demotion_locked: scheduling demotion to idle band for pid %d (dirty:0x%x, set_state %d, demotions %d).\n",
1927 		proc_getpid(p), p->p_memstat_dirty, set_state, (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps));
1928 
1929 	if (isSysProc(p)) {
1930 		assert((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED);
1931 	}
1932 
1933 	idle_delay_time = (isSysProc(p)) ? memorystatus_sysprocs_idle_time(p) : memorystatus_apps_idle_time(p);
1934 	if (set_state) {
1935 		p->p_memstat_dirty |= P_DIRTY_AGING_IN_PROGRESS;
1936 		p->p_memstat_idledeadline = mach_absolute_time() + idle_delay_time;
1937 	}
1938 
1939 	assert(p->p_memstat_idledeadline);
1940 
1941 	if (isSysProc(p) && present_in_sysprocs_aging_bucket == FALSE) {
1942 		memorystatus_scheduled_idle_demotions_sysprocs++;
1943 	} else if (isApp(p) && present_in_apps_aging_bucket == FALSE) {
1944 		memorystatus_scheduled_idle_demotions_apps++;
1945 	}
1946 }
1947 
1948 void
memorystatus_invalidate_idle_demotion_locked(proc_t p,boolean_t clear_state)1949 memorystatus_invalidate_idle_demotion_locked(proc_t p, boolean_t clear_state)
1950 {
1951 	boolean_t present_in_sysprocs_aging_bucket = FALSE;
1952 	boolean_t present_in_apps_aging_bucket = FALSE;
1953 
1954 	if (!system_procs_aging_band && !applications_aging_band) {
1955 		return;
1956 	}
1957 
1958 	if ((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) == 0) {
1959 		return;
1960 	}
1961 
1962 	if (isProcessInAgingBands(p)) {
1963 		assert((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) == P_DIRTY_AGING_IN_PROGRESS);
1964 
1965 		if (isSysProc(p) && system_procs_aging_band) {
1966 			assert(p->p_memstat_effectivepriority == system_procs_aging_band);
1967 			assert(p->p_memstat_idledeadline);
1968 			present_in_sysprocs_aging_bucket = TRUE;
1969 		} else if (isApp(p) && applications_aging_band) {
1970 			assert(p->p_memstat_effectivepriority == applications_aging_band);
1971 			assert(p->p_memstat_idledeadline);
1972 			present_in_apps_aging_bucket = TRUE;
1973 		}
1974 	}
1975 
1976 	memorystatus_log_info(
1977 		"memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1978 		proc_getpid(p), clear_state, (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps));
1979 
1980 
1981 	if (clear_state) {
1982 		p->p_memstat_idledeadline = 0;
1983 		p->p_memstat_dirty &= ~P_DIRTY_AGING_IN_PROGRESS;
1984 	}
1985 
1986 	if (isSysProc(p) && present_in_sysprocs_aging_bucket == TRUE) {
1987 		memorystatus_scheduled_idle_demotions_sysprocs--;
1988 		assert(memorystatus_scheduled_idle_demotions_sysprocs >= 0);
1989 	} else if (isApp(p) && present_in_apps_aging_bucket == TRUE) {
1990 		memorystatus_scheduled_idle_demotions_apps--;
1991 		assert(memorystatus_scheduled_idle_demotions_apps >= 0);
1992 	}
1993 
1994 	assert((memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps) >= 0);
1995 }
1996 
1997 static void
memorystatus_reschedule_idle_demotion_locked(void)1998 memorystatus_reschedule_idle_demotion_locked(void)
1999 {
2000 	if (!system_procs_aging_band && !applications_aging_band) {
2001 		return;
2002 	}
2003 
2004 	if (0 == (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps)) {
2005 		if (memstat_idle_demotion_deadline) {
2006 			/* Transitioned 1->0, so cancel next call */
2007 			thread_call_cancel(memorystatus_idle_demotion_call);
2008 			memstat_idle_demotion_deadline = 0;
2009 		}
2010 	} else {
2011 		memstat_bucket_t *demotion_bucket;
2012 		proc_t p = NULL, p1 = NULL, p2 = NULL;
2013 
2014 		if (system_procs_aging_band) {
2015 			demotion_bucket = &memstat_bucket[system_procs_aging_band];
2016 			p1 = TAILQ_FIRST(&demotion_bucket->list);
2017 
2018 			p = p1;
2019 		}
2020 
2021 		if (applications_aging_band) {
2022 			demotion_bucket = &memstat_bucket[applications_aging_band];
2023 			p2 = TAILQ_FIRST(&demotion_bucket->list);
2024 
2025 			if (p1 && p2) {
2026 				p = (p1->p_memstat_idledeadline > p2->p_memstat_idledeadline) ? p2 : p1;
2027 			} else {
2028 				p = (p1 == NULL) ? p2 : p1;
2029 			}
2030 		}
2031 
2032 		assert(p);
2033 
2034 		if (p != NULL) {
2035 			assert(p && p->p_memstat_idledeadline);
2036 			if (memstat_idle_demotion_deadline != p->p_memstat_idledeadline) {
2037 				thread_call_enter_delayed(memorystatus_idle_demotion_call, p->p_memstat_idledeadline);
2038 				memstat_idle_demotion_deadline = p->p_memstat_idledeadline;
2039 			}
2040 		}
2041 	}
2042 }
2043 
2044 /*
2045  * List manipulation
2046  */
2047 
2048 int
memorystatus_add(proc_t p,boolean_t locked)2049 memorystatus_add(proc_t p, boolean_t locked)
2050 {
2051 	memstat_bucket_t *bucket;
2052 
2053 	memorystatus_log_debug("memorystatus_list_add(): adding pid %d with priority %d.\n",
2054 	    proc_getpid(p), p->p_memstat_effectivepriority);
2055 
2056 	if (!locked) {
2057 		proc_list_lock();
2058 	}
2059 
2060 	DTRACE_MEMORYSTATUS2(memorystatus_add, proc_t, p, int32_t, p->p_memstat_effectivepriority);
2061 
2062 	/* Processes marked internal do not have priority tracked */
2063 	if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
2064 		goto exit;
2065 	}
2066 
2067 	/*
2068 	 * Opt out system processes from being frozen by default.
2069 	 * For coalition-based freezing, we only want to freeze sysprocs that have specifically opted in.
2070 	 */
2071 	if (isSysProc(p)) {
2072 		p->p_memstat_state |= P_MEMSTAT_FREEZE_DISABLED;
2073 	}
2074 #if CONFIG_FREEZE
2075 	memorystatus_freeze_init_proc(p);
2076 #endif
2077 
2078 	bucket = &memstat_bucket[p->p_memstat_effectivepriority];
2079 
2080 	if (isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) {
2081 		assert(bucket->count == memorystatus_scheduled_idle_demotions_sysprocs - 1);
2082 	} else if (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)) {
2083 		assert(bucket->count == memorystatus_scheduled_idle_demotions_apps - 1);
2084 	} else if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
2085 		/*
2086 		 * Entering the idle band.
2087 		 * Record idle start time.
2088 		 */
2089 		p->p_memstat_idle_start = mach_absolute_time();
2090 	}
2091 
2092 	TAILQ_INSERT_TAIL(&bucket->list, p, p_memstat_list);
2093 	bucket->count++;
2094 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
2095 		bucket->relaunch_high_count++;
2096 	}
2097 
2098 	memorystatus_list_count++;
2099 
2100 	memorystatus_check_levels_locked();
2101 
2102 exit:
2103 	if (!locked) {
2104 		proc_list_unlock();
2105 	}
2106 
2107 	return 0;
2108 }
2109 
2110 /*
2111  * Description:
2112  *	Moves a process from one jetsam bucket to another.
2113  *	which changes the LRU position of the process.
2114  *
2115  *	Monitors transition between buckets and if necessary
2116  *	will update cached memory limits accordingly.
2117  *
2118  *	skip_demotion_check:
2119  *	- if the 'jetsam aging policy' is NOT 'legacy':
2120  *		When this flag is TRUE, it means we are going
2121  *		to age the ripe processes out of the aging bands and into the
2122  *		IDLE band and apply their inactive memory limits.
2123  *
2124  *	- if the 'jetsam aging policy' is 'legacy':
2125  *		When this flag is TRUE, it might mean the above aging mechanism
2126  *		OR
2127  *		It might be that we have a process that has used up its 'idle deferral'
2128  *		stay that is given to it once per lifetime. And in this case, the process
2129  *		won't be going through any aging codepaths. But we still need to apply
2130  *		the right inactive limits and so we explicitly set this to TRUE if the
2131  *		new priority for the process is the IDLE band.
2132  */
2133 void
memorystatus_update_priority_locked(proc_t p,int priority,boolean_t head_insert,boolean_t skip_demotion_check)2134 memorystatus_update_priority_locked(proc_t p, int priority, boolean_t head_insert, boolean_t skip_demotion_check)
2135 {
2136 	memstat_bucket_t *old_bucket, *new_bucket;
2137 
2138 	assert(priority < MEMSTAT_BUCKET_COUNT);
2139 
2140 	/* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2141 	if (proc_list_exited(p)) {
2142 		return;
2143 	}
2144 
2145 	memorystatus_log_info("memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2146 	    (*p->p_name ? p->p_name : "unknown"), proc_getpid(p), priority, head_insert ? "head" : "tail");
2147 
2148 	DTRACE_MEMORYSTATUS3(memorystatus_update_priority, proc_t, p, int32_t, p->p_memstat_effectivepriority, int, priority);
2149 
2150 	old_bucket = &memstat_bucket[p->p_memstat_effectivepriority];
2151 
2152 	if (skip_demotion_check == FALSE) {
2153 		if (isSysProc(p)) {
2154 			/*
2155 			 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2156 			 * the processes from the aging bands and balancing the demotion counts.
2157 			 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2158 			 */
2159 
2160 			if (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) {
2161 				/*
2162 				 * 2 types of processes can use the non-standard elevated inactive band:
2163 				 * - Frozen processes that always land in memorystatus_freeze_jetsam_band
2164 				 * OR
2165 				 * - processes that specifically opt-in to the elevated inactive support e.g. docked processes.
2166 				 */
2167 #if CONFIG_FREEZE
2168 				if (p->p_memstat_state & P_MEMSTAT_FROZEN) {
2169 					if (priority <= memorystatus_freeze_jetsam_band) {
2170 						priority = memorystatus_freeze_jetsam_band;
2171 					}
2172 				} else
2173 #endif /* CONFIG_FREEZE */
2174 				{
2175 					if (priority <= JETSAM_PRIORITY_ELEVATED_INACTIVE) {
2176 						priority = JETSAM_PRIORITY_ELEVATED_INACTIVE;
2177 					}
2178 				}
2179 				assert(!(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS));
2180 			}
2181 		} else if (isApp(p)) {
2182 			/*
2183 			 * Check to see if the application is being lowered in jetsam priority. If so, and:
2184 			 * - it has an 'elevated inactive jetsam band' attribute, then put it in the appropriate band.
2185 			 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2186 			 */
2187 
2188 			if (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) {
2189 #if CONFIG_FREEZE
2190 				if (p->p_memstat_state & P_MEMSTAT_FROZEN) {
2191 					if (priority <= memorystatus_freeze_jetsam_band) {
2192 						priority = memorystatus_freeze_jetsam_band;
2193 					}
2194 				} else
2195 #endif /* CONFIG_FREEZE */
2196 				{
2197 					if (priority <= JETSAM_PRIORITY_ELEVATED_INACTIVE) {
2198 						priority = JETSAM_PRIORITY_ELEVATED_INACTIVE;
2199 					}
2200 				}
2201 			} else {
2202 				if (applications_aging_band) {
2203 					if (p->p_memstat_effectivepriority == applications_aging_band) {
2204 						assert(old_bucket->count == (memorystatus_scheduled_idle_demotions_apps + 1));
2205 					}
2206 
2207 					if (priority <= applications_aging_band) {
2208 						assert(!(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS));
2209 						priority = applications_aging_band;
2210 						memorystatus_schedule_idle_demotion_locked(p, TRUE);
2211 					}
2212 				}
2213 			}
2214 		}
2215 	}
2216 
2217 	if ((system_procs_aging_band && (priority == system_procs_aging_band)) || (applications_aging_band && (priority == applications_aging_band))) {
2218 		assert(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS);
2219 	}
2220 
2221 #if DEVELOPMENT || DEBUG
2222 	if (priority == JETSAM_PRIORITY_IDLE &&                         /* if the process is on its way into the IDLE band */
2223 	    (system_procs_aging_band && applications_aging_band) &&     /* we have support for _both_ aging bands */
2224 	    (skip_demotion_check == FALSE) &&                           /* and it isn't via the path that will set the INACTIVE memlimits */
2225 	    (p->p_memstat_dirty & P_DIRTY_TRACK) &&                     /* and it has 'DIRTY' tracking enabled */
2226 	    ((p->p_memstat_memlimit != p->p_memstat_memlimit_inactive) || /* and we notice that the current limit isn't the right value (inactive) */
2227 	    ((p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) ? (!(p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT)) : (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT)))) { /* OR type (fatal vs non-fatal) */
2228 		memorystatus_log_error("memorystatus_update_priority_locked: on %s with 0x%x, prio: %d and %d\n",
2229 		    p->p_name, p->p_memstat_state, priority, p->p_memstat_memlimit); /* then we must catch this */
2230 	}
2231 #endif /* DEVELOPMENT || DEBUG */
2232 
2233 	TAILQ_REMOVE(&old_bucket->list, p, p_memstat_list);
2234 	old_bucket->count--;
2235 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
2236 		old_bucket->relaunch_high_count--;
2237 	}
2238 
2239 	new_bucket = &memstat_bucket[priority];
2240 	if (head_insert) {
2241 		TAILQ_INSERT_HEAD(&new_bucket->list, p, p_memstat_list);
2242 	} else {
2243 		TAILQ_INSERT_TAIL(&new_bucket->list, p, p_memstat_list);
2244 	}
2245 	new_bucket->count++;
2246 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
2247 		new_bucket->relaunch_high_count++;
2248 	}
2249 
2250 	if (memorystatus_highwater_enabled) {
2251 		boolean_t is_fatal;
2252 		boolean_t use_active;
2253 
2254 		/*
2255 		 * If cached limit data is updated, then the limits
2256 		 * will be enforced by writing to the ledgers.
2257 		 */
2258 		boolean_t ledger_update_needed = TRUE;
2259 
2260 		/*
2261 		 * Here, we must update the cached memory limit if the task
2262 		 * is transitioning between:
2263 		 *      active <--> inactive
2264 		 *	FG     <-->       BG
2265 		 * but:
2266 		 *	dirty  <-->    clean   is ignored
2267 		 *
2268 		 * We bypass non-idle processes that have opted into dirty tracking because
2269 		 * a move between buckets does not imply a transition between the
2270 		 * dirty <--> clean state.
2271 		 */
2272 
2273 		if (p->p_memstat_dirty & P_DIRTY_TRACK) {
2274 			if (skip_demotion_check == TRUE && priority == JETSAM_PRIORITY_IDLE) {
2275 				CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2276 				use_active = FALSE;
2277 			} else {
2278 				ledger_update_needed = FALSE;
2279 			}
2280 		} else if ((priority >= JETSAM_PRIORITY_FOREGROUND) && (p->p_memstat_effectivepriority < JETSAM_PRIORITY_FOREGROUND)) {
2281 			/*
2282 			 *      inactive --> active
2283 			 *	BG       -->     FG
2284 			 *      assign active state
2285 			 */
2286 			CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
2287 			use_active = TRUE;
2288 		} else if ((priority < JETSAM_PRIORITY_FOREGROUND) && (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND)) {
2289 			/*
2290 			 *      active --> inactive
2291 			 *	FG     -->       BG
2292 			 *      assign inactive state
2293 			 */
2294 			CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2295 			use_active = FALSE;
2296 		} else {
2297 			/*
2298 			 * The transition between jetsam priority buckets apparently did
2299 			 * not affect active/inactive state.
2300 			 * This is not unusual... especially during startup when
2301 			 * processes are getting established in their respective bands.
2302 			 */
2303 			ledger_update_needed = FALSE;
2304 		}
2305 
2306 		/*
2307 		 * Enforce the new limits by writing to the ledger
2308 		 */
2309 		if (ledger_update_needed) {
2310 			task_set_phys_footprint_limit_internal(proc_task(p), (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1, NULL, use_active, is_fatal);
2311 
2312 			memorystatus_log_info("memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2313 			    proc_getpid(p), (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
2314 			    (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, priority, p->p_memstat_dirty,
2315 			    (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
2316 		}
2317 	}
2318 
2319 	/*
2320 	 * Record idle start or idle delta.
2321 	 */
2322 	if (p->p_memstat_effectivepriority == priority) {
2323 		/*
2324 		 * This process is not transitioning between
2325 		 * jetsam priority buckets.  Do nothing.
2326 		 */
2327 	} else if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
2328 		uint64_t now;
2329 		/*
2330 		 * Transitioning out of the idle priority bucket.
2331 		 * Record idle delta.
2332 		 */
2333 		assert(p->p_memstat_idle_start != 0);
2334 		now = mach_absolute_time();
2335 		if (now > p->p_memstat_idle_start) {
2336 			p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
2337 		}
2338 
2339 		/*
2340 		 * About to become active and so memory footprint could change.
2341 		 * So mark it eligible for freeze-considerations next time around.
2342 		 */
2343 		if (p->p_memstat_state & P_MEMSTAT_FREEZE_IGNORE) {
2344 			p->p_memstat_state &= ~P_MEMSTAT_FREEZE_IGNORE;
2345 		}
2346 	} else if (priority == JETSAM_PRIORITY_IDLE) {
2347 		/*
2348 		 * Transitioning into the idle priority bucket.
2349 		 * Record idle start.
2350 		 */
2351 		p->p_memstat_idle_start = mach_absolute_time();
2352 	}
2353 
2354 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_CHANGE_PRIORITY), proc_getpid(p), priority, p->p_memstat_effectivepriority);
2355 
2356 	p->p_memstat_effectivepriority = priority;
2357 
2358 #if CONFIG_SECLUDED_MEMORY
2359 	if (secluded_for_apps &&
2360 	    task_could_use_secluded_mem(proc_task(p))) {
2361 		task_set_can_use_secluded_mem(
2362 			proc_task(p),
2363 			(priority >= JETSAM_PRIORITY_FOREGROUND));
2364 	}
2365 #endif /* CONFIG_SECLUDED_MEMORY */
2366 
2367 	memorystatus_check_levels_locked();
2368 }
2369 
2370 int
memorystatus_relaunch_flags_update(proc_t p,int relaunch_flags)2371 memorystatus_relaunch_flags_update(proc_t p, int relaunch_flags)
2372 {
2373 	p->p_memstat_relaunch_flags = relaunch_flags;
2374 	KDBG(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_RELAUNCH_FLAGS), proc_getpid(p), relaunch_flags);
2375 	return 0;
2376 }
2377 
2378 #if DEVELOPMENT || DEBUG
2379 static int sysctl_memorystatus_relaunch_flags SYSCTL_HANDLER_ARGS {
2380 #pragma unused(oidp, arg1, arg2)
2381 	proc_t p;
2382 	int relaunch_flags = 0;
2383 
2384 	p = current_proc();
2385 	relaunch_flags = p->p_memstat_relaunch_flags;
2386 	switch (relaunch_flags) {
2387 	case P_MEMSTAT_RELAUNCH_LOW:
2388 		relaunch_flags = POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_LOW;
2389 		break;
2390 	case P_MEMSTAT_RELAUNCH_MED:
2391 		relaunch_flags = POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MED;
2392 		break;
2393 	case P_MEMSTAT_RELAUNCH_HIGH:
2394 		relaunch_flags = POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_HIGH;
2395 		break;
2396 	}
2397 
2398 	return SYSCTL_OUT(req, &relaunch_flags, sizeof(relaunch_flags));
2399 }
2400 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_relaunch_flags, CTLTYPE_INT | CTLFLAG_RD |
2401     CTLFLAG_LOCKED | CTLFLAG_MASKED, 0, 0, sysctl_memorystatus_relaunch_flags, "I", "get relaunch flags for current process");
2402 #endif /* DEVELOPMENT || DEBUG */
2403 
2404 /*
2405  * Everything between the idle band and the application agining band
2406  * are reserved for internal use. We allow some entitled user space programs
2407  * to use this range for experimentation.
2408  */
2409 static bool
current_task_can_use_entitled_range()2410 current_task_can_use_entitled_range()
2411 {
2412 	static const char kInternalJetsamRangeEntitlement[] = "com.apple.private.internal-jetsam-range";
2413 	task_t task = current_task();
2414 	if (task == kernel_task) {
2415 		return true;
2416 	}
2417 	return IOTaskHasEntitlement(task, kInternalJetsamRangeEntitlement);
2418 }
2419 
2420 /*
2421  *
2422  * Description: Update the jetsam priority and memory limit attributes for a given process.
2423  *
2424  * Parameters:
2425  *	p	init this process's jetsam information.
2426  *	priority          The jetsam priority band
2427  *	user_data	  user specific data, unused by the kernel
2428  *	is_assertion	  When true, a priority update is driven by an assertion.
2429  *	effective	  guards against race if process's update already occurred
2430  *	update_memlimit   When true we know this is the init step via the posix_spawn path.
2431  *
2432  *	memlimit_active	  Value in megabytes; The monitored footprint level while the
2433  *			  process is active.  Exceeding it may result in termination
2434  *			  based on it's associated fatal flag.
2435  *
2436  *	memlimit_active_is_fatal  When a process is active and exceeds its memory footprint,
2437  *				  this describes whether or not it should be immediately fatal.
2438  *
2439  *	memlimit_inactive Value in megabytes; The monitored footprint level while the
2440  *			  process is inactive.  Exceeding it may result in termination
2441  *			  based on it's associated fatal flag.
2442  *
2443  *	memlimit_inactive_is_fatal  When a process is inactive and exceeds its memory footprint,
2444  *				    this describes whether or not it should be immediatly fatal.
2445  *
2446  * Returns:     0	Success
2447  *		non-0	Failure
2448  */
2449 
2450 int
memorystatus_update(proc_t p,int priority,uint64_t user_data,boolean_t is_assertion,boolean_t effective,boolean_t update_memlimit,int32_t memlimit_active,boolean_t memlimit_active_is_fatal,int32_t memlimit_inactive,boolean_t memlimit_inactive_is_fatal)2451 memorystatus_update(proc_t p, int priority, uint64_t user_data, boolean_t is_assertion, boolean_t effective, boolean_t update_memlimit,
2452     int32_t memlimit_active, boolean_t memlimit_active_is_fatal,
2453     int32_t memlimit_inactive, boolean_t memlimit_inactive_is_fatal)
2454 {
2455 	int ret;
2456 	boolean_t head_insert = false;
2457 
2458 	memorystatus_log_info("memorystatus_update: changing (%s) pid %d: priority %d, user_data 0x%llx\n",
2459 	    (*p->p_name ? p->p_name : "unknown"), proc_getpid(p), priority, user_data);
2460 
2461 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_UPDATE) | DBG_FUNC_START, proc_getpid(p), priority, user_data, effective);
2462 
2463 	if (priority == -1) {
2464 		/* Use as shorthand for default priority */
2465 		priority = JETSAM_PRIORITY_DEFAULT;
2466 	} else if (priority > JETSAM_PRIORITY_IDLE && priority <= applications_aging_band) {
2467 		/*
2468 		 * Everything between idle and the aging bands are reserved for internal use.
2469 		 * if requested, adjust to JETSAM_PRIORITY_IDLE.
2470 		 * Entitled processes (just munch) can use a subset of this range for testing.
2471 		 */
2472 		if (priority > JETSAM_PRIORITY_ENTITLED_MAX ||
2473 		    !current_task_can_use_entitled_range()) {
2474 			priority = JETSAM_PRIORITY_IDLE;
2475 		}
2476 	} else if (priority == JETSAM_PRIORITY_IDLE_HEAD) {
2477 		/* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2478 		priority = JETSAM_PRIORITY_IDLE;
2479 		head_insert = TRUE;
2480 	} else if ((priority < 0) || (priority >= MEMSTAT_BUCKET_COUNT)) {
2481 		/* Sanity check */
2482 		ret = EINVAL;
2483 		goto out;
2484 	}
2485 
2486 	proc_list_lock();
2487 
2488 	assert(!(p->p_memstat_state & P_MEMSTAT_INTERNAL));
2489 
2490 	if (effective && (p->p_memstat_state & P_MEMSTAT_PRIORITYUPDATED)) {
2491 		ret = EALREADY;
2492 		proc_list_unlock();
2493 		memorystatus_log_debug("memorystatus_update: effective change specified for pid %d, but change already occurred.\n",
2494 		    proc_getpid(p));
2495 		goto out;
2496 	}
2497 
2498 	if ((p->p_memstat_state & (P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP)) || proc_list_exited(p)) {
2499 		/*
2500 		 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2501 		 */
2502 		ret = EBUSY;
2503 		proc_list_unlock();
2504 		goto out;
2505 	}
2506 
2507 	p->p_memstat_state |= P_MEMSTAT_PRIORITYUPDATED;
2508 	p->p_memstat_userdata = user_data;
2509 
2510 	if (is_assertion) {
2511 		if (priority == JETSAM_PRIORITY_IDLE) {
2512 			/*
2513 			 * Assertions relinquish control when the process is heading to IDLE.
2514 			 */
2515 			if (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION) {
2516 				/*
2517 				 * Mark the process as no longer being managed by assertions.
2518 				 */
2519 				p->p_memstat_state &= ~P_MEMSTAT_PRIORITY_ASSERTION;
2520 			} else {
2521 				/*
2522 				 * Ignore an idle priority transition if the process is not
2523 				 * already managed by assertions.  We won't treat this as
2524 				 * an error, but we will log the unexpected behavior and bail.
2525 				 */
2526 				memorystatus_log_error(
2527 					"memorystatus: Ignore assertion driven idle priority. Process not previously controlled %s:%d\n",
2528 					(*p->p_name ? p->p_name : "unknown"), proc_getpid(p));
2529 
2530 				ret = 0;
2531 				proc_list_unlock();
2532 				goto out;
2533 			}
2534 		} else {
2535 			/*
2536 			 * Process is now being managed by assertions,
2537 			 */
2538 			p->p_memstat_state |= P_MEMSTAT_PRIORITY_ASSERTION;
2539 		}
2540 
2541 		/* Always update the assertion priority in this path */
2542 
2543 		p->p_memstat_assertionpriority = priority;
2544 
2545 		int memstat_dirty_flags = memorystatus_dirty_get(p, TRUE);  /* proc_list_lock is held */
2546 
2547 		if (memstat_dirty_flags != 0) {
2548 			/*
2549 			 * Calculate maximum priority only when dirty tracking processes are involved.
2550 			 */
2551 			int maxpriority;
2552 			if (memstat_dirty_flags & PROC_DIRTY_IS_DIRTY) {
2553 				maxpriority = MAX(p->p_memstat_assertionpriority, p->p_memstat_requestedpriority);
2554 			} else {
2555 				/* clean */
2556 
2557 				if (memstat_dirty_flags & PROC_DIRTY_ALLOWS_IDLE_EXIT) {
2558 					/*
2559 					 * The aging policy must be evaluated and applied here because runnningboardd
2560 					 * has relinquished its hold on the jetsam priority by attempting to move a
2561 					 * clean process to the idle band.
2562 					 */
2563 
2564 					int newpriority = JETSAM_PRIORITY_IDLE;
2565 					if ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED | P_DIRTY_IS_DIRTY)) == P_DIRTY_IDLE_EXIT_ENABLED) {
2566 						newpriority = (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) ? system_procs_aging_band : JETSAM_PRIORITY_IDLE;
2567 					}
2568 
2569 					maxpriority = MAX(p->p_memstat_assertionpriority, newpriority );
2570 
2571 					if (newpriority == system_procs_aging_band) {
2572 						memorystatus_schedule_idle_demotion_locked(p, FALSE);
2573 					}
2574 				} else {
2575 					/*
2576 					 * Preserves requestedpriority when the process does not support pressured exit.
2577 					 */
2578 					maxpriority = MAX(p->p_memstat_assertionpriority, p->p_memstat_requestedpriority);
2579 				}
2580 			}
2581 			priority = maxpriority;
2582 		}
2583 	} else {
2584 		p->p_memstat_requestedpriority = priority;
2585 	}
2586 
2587 	if (update_memlimit) {
2588 		boolean_t is_fatal;
2589 		boolean_t use_active;
2590 
2591 		/*
2592 		 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2593 		 * Forked processes do not come through this path, so no ledger limits exist.
2594 		 * (That's why forked processes can consume unlimited memory.)
2595 		 */
2596 
2597 		memorystatus_log_info(
2598 			"memorystatus_update: update memlimit (%s) pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2599 			(*p->p_name ? p->p_name : "unknown"), proc_getpid(p), priority, p->p_memstat_dirty,
2600 			memlimit_active, (memlimit_active_is_fatal ? "F " : "NF"),
2601 			memlimit_inactive, (memlimit_inactive_is_fatal ? "F " : "NF"));
2602 
2603 		if (memlimit_active <= 0) {
2604 			/*
2605 			 * This process will have a system_wide task limit when active.
2606 			 * System_wide task limit is always fatal.
2607 			 * It's quite common to see non-fatal flag passed in here.
2608 			 * It's not an error, we just ignore it.
2609 			 */
2610 
2611 			/*
2612 			 * For backward compatibility with some unexplained launchd behavior,
2613 			 * we allow a zero sized limit.  But we still enforce system_wide limit
2614 			 * when written to the ledgers.
2615 			 */
2616 
2617 			if (memlimit_active < 0) {
2618 				memlimit_active = -1;  /* enforces system_wide task limit */
2619 			}
2620 			memlimit_active_is_fatal = TRUE;
2621 		}
2622 
2623 		if (memlimit_inactive <= 0) {
2624 			/*
2625 			 * This process will have a system_wide task limit when inactive.
2626 			 * System_wide task limit is always fatal.
2627 			 */
2628 
2629 			memlimit_inactive = -1;
2630 			memlimit_inactive_is_fatal = TRUE;
2631 		}
2632 
2633 		/*
2634 		 * Initialize the active limit variants for this process.
2635 		 */
2636 		SET_ACTIVE_LIMITS_LOCKED(p, memlimit_active, memlimit_active_is_fatal);
2637 
2638 		/*
2639 		 * Initialize the inactive limit variants for this process.
2640 		 */
2641 		SET_INACTIVE_LIMITS_LOCKED(p, memlimit_inactive, memlimit_inactive_is_fatal);
2642 
2643 		/*
2644 		 * Initialize the cached limits for target process.
2645 		 * When the target process is dirty tracked, it's typically
2646 		 * in a clean state.  Non dirty tracked processes are
2647 		 * typically active (Foreground or above).
2648 		 * But just in case, we don't make assumptions...
2649 		 */
2650 
2651 		if (proc_jetsam_state_is_active_locked(p) == TRUE) {
2652 			CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
2653 			use_active = TRUE;
2654 		} else {
2655 			CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2656 			use_active = FALSE;
2657 		}
2658 
2659 		/*
2660 		 * Enforce the cached limit by writing to the ledger.
2661 		 */
2662 		if (memorystatus_highwater_enabled) {
2663 			/* apply now */
2664 			task_set_phys_footprint_limit_internal(proc_task(p),
2665 			    ((p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1), NULL, use_active, is_fatal);
2666 		}
2667 	}
2668 
2669 	/*
2670 	 * We can't add to the aging bands buckets here.
2671 	 * But, we could be removing it from those buckets.
2672 	 * Check and take appropriate steps if so.
2673 	 */
2674 
2675 	if (isProcessInAgingBands(p)) {
2676 		if (isApp(p) && (priority > applications_aging_band)) {
2677 			/*
2678 			 * Runningboardd is pulling up an application that is in the aging band.
2679 			 * We reset the app's state here so that it'll get a fresh stay in the
2680 			 * aging band on the way back.
2681 			 *
2682 			 * We always handled the app 'aging' in the memorystatus_update_priority_locked()
2683 			 * function. Daemons used to be handled via the dirty 'set/clear/track' path.
2684 			 * But with extensions (daemon-app hybrid), runningboardd is now going through
2685 			 * this routine for daemons too and things have gotten a bit tangled. This should
2686 			 * be simplified/untangled at some point and might require some assistance from
2687 			 * runningboardd.
2688 			 */
2689 			memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2690 		} else {
2691 			memorystatus_invalidate_idle_demotion_locked(p, FALSE);
2692 		}
2693 		memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
2694 	}
2695 
2696 	memorystatus_update_priority_locked(p, priority, head_insert, FALSE);
2697 
2698 	proc_list_unlock();
2699 	ret = 0;
2700 
2701 out:
2702 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_UPDATE) | DBG_FUNC_END, ret);
2703 
2704 	return ret;
2705 }
2706 
2707 int
memorystatus_remove(proc_t p)2708 memorystatus_remove(proc_t p)
2709 {
2710 	int ret;
2711 	memstat_bucket_t *bucket;
2712 	boolean_t       reschedule = FALSE;
2713 
2714 	memorystatus_log_debug("memorystatus_list_remove: removing pid %d\n", proc_getpid(p));
2715 
2716 	/* Processes marked internal do not have priority tracked */
2717 	if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
2718 		return 0;
2719 	}
2720 
2721 	/*
2722 	 * Check if this proc is locked (because we're performing a freeze).
2723 	 * If so, we fail and instruct the caller to try again later.
2724 	 */
2725 	if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
2726 		return EAGAIN;
2727 	}
2728 
2729 	assert(!(p->p_memstat_state & P_MEMSTAT_INTERNAL));
2730 
2731 	bucket = &memstat_bucket[p->p_memstat_effectivepriority];
2732 
2733 	if (isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) {
2734 		assert(bucket->count == memorystatus_scheduled_idle_demotions_sysprocs);
2735 		reschedule = TRUE;
2736 	} else if (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)) {
2737 		assert(bucket->count == memorystatus_scheduled_idle_demotions_apps);
2738 		reschedule = TRUE;
2739 	}
2740 
2741 	/*
2742 	 * Record idle delta
2743 	 */
2744 
2745 	if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
2746 		uint64_t now = mach_absolute_time();
2747 		if (now > p->p_memstat_idle_start) {
2748 			p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
2749 		}
2750 	}
2751 
2752 	TAILQ_REMOVE(&bucket->list, p, p_memstat_list);
2753 	bucket->count--;
2754 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
2755 		bucket->relaunch_high_count--;
2756 	}
2757 
2758 	memorystatus_list_count--;
2759 
2760 	/* If awaiting demotion to the idle band, clean up */
2761 	if (reschedule) {
2762 		memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2763 		memorystatus_reschedule_idle_demotion_locked();
2764 	}
2765 
2766 	memorystatus_check_levels_locked();
2767 
2768 #if CONFIG_FREEZE
2769 	if (p->p_memstat_state & (P_MEMSTAT_FROZEN)) {
2770 		if (p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) {
2771 			p->p_memstat_state &= ~P_MEMSTAT_REFREEZE_ELIGIBLE;
2772 			memorystatus_refreeze_eligible_count--;
2773 		}
2774 
2775 		memorystatus_frozen_count--;
2776 		if (p->p_memstat_state & P_MEMSTAT_FROZEN_XPC_SERVICE) {
2777 			memorystatus_frozen_count_xpc_service--;
2778 		}
2779 		if (strcmp(p->p_name, "com.apple.WebKit.WebContent") == 0) {
2780 			memorystatus_frozen_count_webcontent--;
2781 		}
2782 		memorystatus_frozen_shared_mb -= p->p_memstat_freeze_sharedanon_pages;
2783 		p->p_memstat_freeze_sharedanon_pages = 0;
2784 	}
2785 
2786 	if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
2787 		memorystatus_suspended_count--;
2788 	}
2789 #endif
2790 
2791 #if DEVELOPMENT || DEBUG
2792 	if (proc_getpid(p) == memorystatus_testing_pid) {
2793 		memorystatus_testing_pid = 0;
2794 	}
2795 #endif /* DEVELOPMENT || DEBUG */
2796 
2797 	if (p) {
2798 		ret = 0;
2799 	} else {
2800 		ret = ESRCH;
2801 	}
2802 
2803 	return ret;
2804 }
2805 
2806 /*
2807  * Validate dirty tracking flags with process state.
2808  *
2809  * Return:
2810  *	0     on success
2811  *      non-0 on failure
2812  *
2813  * The proc_list_lock is held by the caller.
2814  */
2815 
2816 static int
memorystatus_validate_track_flags(struct proc * target_p,uint32_t pcontrol)2817 memorystatus_validate_track_flags(struct proc *target_p, uint32_t pcontrol)
2818 {
2819 	/* See that the process isn't marked for termination */
2820 	if (target_p->p_memstat_dirty & P_DIRTY_TERMINATED) {
2821 		return EBUSY;
2822 	}
2823 
2824 	/* Idle exit requires that process be tracked */
2825 	if ((pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) &&
2826 	    !(pcontrol & PROC_DIRTY_TRACK)) {
2827 		return EINVAL;
2828 	}
2829 
2830 	/* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2831 	if ((pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) &&
2832 	    !(pcontrol & PROC_DIRTY_TRACK)) {
2833 		return EINVAL;
2834 	}
2835 
2836 	/* Only one type of DEFER behavior is allowed.*/
2837 	if ((pcontrol & PROC_DIRTY_DEFER) &&
2838 	    (pcontrol & PROC_DIRTY_DEFER_ALWAYS)) {
2839 		return EINVAL;
2840 	}
2841 
2842 	/* Deferral is only relevant if idle exit is specified */
2843 	if (((pcontrol & PROC_DIRTY_DEFER) ||
2844 	    (pcontrol & PROC_DIRTY_DEFER_ALWAYS)) &&
2845 	    !(pcontrol & PROC_DIRTY_ALLOWS_IDLE_EXIT)) {
2846 		return EINVAL;
2847 	}
2848 
2849 	return 0;
2850 }
2851 
2852 static void
memorystatus_update_idle_priority_locked(proc_t p)2853 memorystatus_update_idle_priority_locked(proc_t p)
2854 {
2855 	int32_t priority;
2856 
2857 	memorystatus_log_debug("memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n",
2858 	    proc_getpid(p), p->p_memstat_dirty);
2859 
2860 	assert(isSysProc(p));
2861 
2862 	if ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED | P_DIRTY_IS_DIRTY)) == P_DIRTY_IDLE_EXIT_ENABLED) {
2863 		priority = (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) ? system_procs_aging_band : JETSAM_PRIORITY_IDLE;
2864 	} else {
2865 		priority = p->p_memstat_requestedpriority;
2866 	}
2867 
2868 	if (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION) {
2869 		/*
2870 		 * This process has a jetsam priority managed by an assertion.
2871 		 * Policy is to choose the max priority.
2872 		 */
2873 		if (p->p_memstat_assertionpriority > priority) {
2874 			memorystatus_log_debug("memorystatus: assertion priority %d overrides priority %d for %s:%d\n",
2875 			    p->p_memstat_assertionpriority, priority,
2876 			    (*p->p_name ? p->p_name : "unknown"), proc_getpid(p));
2877 			priority = p->p_memstat_assertionpriority;
2878 		}
2879 	}
2880 
2881 	if (priority != p->p_memstat_effectivepriority) {
2882 		memorystatus_update_priority_locked(p, priority, false, false);
2883 	}
2884 }
2885 
2886 /*
2887  * Processes can opt to have their state tracked by the kernel, indicating  when they are busy (dirty) or idle
2888  * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2889  * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2890  * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2891  *
2892  * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2893  * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2894  * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2895  * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2896  * band. The deferral can be cleared early by clearing the appropriate flag.
2897  *
2898  * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2899  * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2900  * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2901  */
2902 
2903 int
memorystatus_dirty_track(proc_t p,uint32_t pcontrol)2904 memorystatus_dirty_track(proc_t p, uint32_t pcontrol)
2905 {
2906 	unsigned int old_dirty;
2907 	boolean_t reschedule = FALSE;
2908 	boolean_t already_deferred = FALSE;
2909 	boolean_t defer_now = FALSE;
2910 	int ret = 0;
2911 
2912 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_DIRTY_TRACK),
2913 	    proc_getpid(p), p->p_memstat_dirty, pcontrol);
2914 
2915 	proc_list_lock();
2916 
2917 	if (proc_list_exited(p)) {
2918 		/*
2919 		 * Process is on its way out.
2920 		 */
2921 		ret = EBUSY;
2922 		goto exit;
2923 	}
2924 
2925 	if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
2926 		ret = EPERM;
2927 		goto exit;
2928 	}
2929 
2930 	if ((ret = memorystatus_validate_track_flags(p, pcontrol)) != 0) {
2931 		/* error  */
2932 		goto exit;
2933 	}
2934 
2935 	old_dirty = p->p_memstat_dirty;
2936 
2937 	/* These bits are cumulative, as per <rdar://problem/11159924> */
2938 	if (pcontrol & PROC_DIRTY_TRACK) {
2939 		/*Request to turn ON Dirty tracking...*/
2940 		if (p->p_memstat_state & P_MEMSTAT_MANAGED) {
2941 			/* on a process managed by RunningBoard or its equivalent...*/
2942 			if (!(p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT)) {
2943 				/* but this might be an app because there's no fatal limits
2944 				 * NB: This _big_ assumption is not universal. What we really
2945 				 * need is a way to say this is an _APP_ and we can't have dirty
2946 				 * tracking turned ON for it. Lacking that functionality we clump
2947 				 * together some checks and try to do the best detection we can.
2948 				 * Reason we can't allow addition of these flags is because, per the
2949 				 * kernel checks, they change the role of a process from app to daemon. And the
2950 				 * AGING_IN_PROGRESS bits might still be set i.e. it needs to be demoted
2951 				 * correctly from the right aging band (app or sysproc). We can't simply try
2952 				 * to invalidate the demotion here because, owing to assertion priorities, we
2953 				 * might not be in the aging bands.
2954 				 */
2955 #if DEVELOPMENT || DEBUG
2956 				memorystatus_log_info(
2957 					"memorystatus: Denying dirty-tracking opt-in for app %s (pid %d)\n",
2958 					(*p->p_name ? p->p_name : "unknown"), proc_getpid(p));
2959 #endif /*DEVELOPMENT || DEBUG*/
2960 				/* fail silently to avoid an XPC assertion... */
2961 				ret = 0;
2962 				goto exit;
2963 			}
2964 		}
2965 
2966 		p->p_memstat_dirty |= P_DIRTY_TRACK;
2967 	}
2968 
2969 	if (pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) {
2970 		p->p_memstat_dirty |= P_DIRTY_ALLOW_IDLE_EXIT;
2971 	}
2972 
2973 	if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
2974 		p->p_memstat_dirty |= P_DIRTY_LAUNCH_IN_PROGRESS;
2975 	}
2976 
2977 	if (old_dirty & P_DIRTY_AGING_IN_PROGRESS) {
2978 		already_deferred = TRUE;
2979 	}
2980 
2981 
2982 	/* This can be set and cleared exactly once. */
2983 	if (pcontrol & (PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) {
2984 		if ((pcontrol & (PROC_DIRTY_DEFER)) &&
2985 		    !(old_dirty & P_DIRTY_DEFER)) {
2986 			p->p_memstat_dirty |= P_DIRTY_DEFER;
2987 		}
2988 
2989 		if ((pcontrol & (PROC_DIRTY_DEFER_ALWAYS)) &&
2990 		    !(old_dirty & P_DIRTY_DEFER_ALWAYS)) {
2991 			p->p_memstat_dirty |= P_DIRTY_DEFER_ALWAYS;
2992 		}
2993 
2994 		defer_now = TRUE;
2995 	}
2996 
2997 	memorystatus_log_info(
2998 		"memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2999 		((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) ? "Y" : "N",
3000 		defer_now ? "Y" : "N", p->p_memstat_dirty & P_DIRTY ? "Y" : "N", proc_getpid(p));
3001 
3002 	/* Kick off or invalidate the idle exit deferment if there's a state transition. */
3003 	if (!(p->p_memstat_dirty & P_DIRTY_IS_DIRTY)) {
3004 		if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
3005 			if (defer_now && !already_deferred) {
3006 				/*
3007 				 * Request to defer a clean process that's idle-exit enabled
3008 				 * and not already in the jetsam deferred band. Most likely a
3009 				 * new launch.
3010 				 */
3011 				memorystatus_schedule_idle_demotion_locked(p, TRUE);
3012 				reschedule = TRUE;
3013 			} else if (!defer_now) {
3014 				/*
3015 				 * The process isn't asking for the 'aging' facility.
3016 				 * Could be that it is:
3017 				 */
3018 
3019 				if (already_deferred) {
3020 					/*
3021 					 * already in the aging bands. Traditionally,
3022 					 * some processes have tried to use this to
3023 					 * opt out of the 'aging' facility.
3024 					 */
3025 
3026 					memorystatus_invalidate_idle_demotion_locked(p, TRUE);
3027 				} else {
3028 					/*
3029 					 * agnostic to the 'aging' facility. In that case,
3030 					 * we'll go ahead and opt it in because this is likely
3031 					 * a new launch (clean process, dirty tracking enabled)
3032 					 */
3033 
3034 					memorystatus_schedule_idle_demotion_locked(p, TRUE);
3035 				}
3036 
3037 				reschedule = TRUE;
3038 			}
3039 		}
3040 	} else {
3041 		/*
3042 		 * We are trying to operate on a dirty process. Dirty processes have to
3043 		 * be removed from the deferred band & their state has to be reset.
3044 		 *
3045 		 * This could be a legal request like:
3046 		 * - this process had opted into the 'aging' band
3047 		 * - but it's now dirty and requests to opt out.
3048 		 * In this case, we remove the process from the band and reset its
3049 		 * state too. It'll opt back in properly when needed.
3050 		 *
3051 		 * OR, this request could be a user-space bug. E.g.:
3052 		 * - this process had opted into the 'aging' band when clean
3053 		 * - and, then issues another request to again put it into the band except
3054 		 *   this time the process is dirty.
3055 		 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
3056 		 * the deferred band with its state intact. So our request below is no-op.
3057 		 * But we do it here anyways for coverage.
3058 		 *
3059 		 * memorystatus_update_idle_priority_locked()
3060 		 * single-mindedly treats a dirty process as "cannot be in the aging band".
3061 		 */
3062 
3063 		memorystatus_invalidate_idle_demotion_locked(p, TRUE);
3064 		reschedule = TRUE;
3065 	}
3066 
3067 	memorystatus_update_idle_priority_locked(p);
3068 
3069 	if (reschedule) {
3070 		memorystatus_reschedule_idle_demotion_locked();
3071 	}
3072 
3073 	ret = 0;
3074 
3075 exit:
3076 	proc_list_unlock();
3077 
3078 	return ret;
3079 }
3080 
3081 int
memorystatus_dirty_set(proc_t p,boolean_t self,uint32_t pcontrol)3082 memorystatus_dirty_set(proc_t p, boolean_t self, uint32_t pcontrol)
3083 {
3084 	int ret;
3085 	boolean_t kill = false;
3086 	boolean_t reschedule = FALSE;
3087 	boolean_t was_dirty = FALSE;
3088 	boolean_t now_dirty = FALSE;
3089 
3090 	memorystatus_log_debug("memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self, proc_getpid(p), pcontrol, p->p_memstat_dirty);
3091 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_DIRTY_SET), proc_getpid(p), self, pcontrol);
3092 
3093 	proc_list_lock();
3094 
3095 	if (proc_list_exited(p)) {
3096 		/*
3097 		 * Process is on its way out.
3098 		 */
3099 		ret = EBUSY;
3100 		goto exit;
3101 	}
3102 
3103 	if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
3104 		ret = EPERM;
3105 		goto exit;
3106 	}
3107 
3108 	if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3109 		was_dirty = TRUE;
3110 	}
3111 
3112 	if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
3113 		/* Dirty tracking not enabled */
3114 		ret = EINVAL;
3115 	} else if (pcontrol && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
3116 		/*
3117 		 * Process is set to be terminated and we're attempting to mark it dirty.
3118 		 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
3119 		 */
3120 		ret = EBUSY;
3121 	} else {
3122 		int flag = (self == TRUE) ? P_DIRTY : P_DIRTY_SHUTDOWN;
3123 		if (pcontrol && !(p->p_memstat_dirty & flag)) {
3124 			/* Mark the process as having been dirtied at some point */
3125 			p->p_memstat_dirty |= (flag | P_DIRTY_MARKED);
3126 			memorystatus_dirty_count++;
3127 			ret = 0;
3128 		} else if ((pcontrol == 0) && (p->p_memstat_dirty & flag)) {
3129 			if ((flag == P_DIRTY_SHUTDOWN) && (!(p->p_memstat_dirty & P_DIRTY))) {
3130 				/* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
3131 				p->p_memstat_dirty |= P_DIRTY_TERMINATED;
3132 				kill = true;
3133 			} else if ((flag == P_DIRTY) && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
3134 				/* Kill previously terminated processes if set clean */
3135 				kill = true;
3136 			}
3137 			p->p_memstat_dirty &= ~flag;
3138 			memorystatus_dirty_count--;
3139 			ret = 0;
3140 		} else {
3141 			/* Already set */
3142 			ret = EALREADY;
3143 		}
3144 	}
3145 
3146 	if (ret != 0) {
3147 		goto exit;
3148 	}
3149 
3150 	if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3151 		now_dirty = TRUE;
3152 	}
3153 
3154 	if ((was_dirty == TRUE && now_dirty == FALSE) ||
3155 	    (was_dirty == FALSE && now_dirty == TRUE)) {
3156 		/* Manage idle exit deferral, if applied */
3157 		if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
3158 			/*
3159 			 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
3160 			 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
3161 			 * P_DIRTY_DEFER: one-time protection window given at launch
3162 			 * P_DIRTY_DEFER_ALWAYS: protection window given for every dirty->clean transition. Like non-legacy mode.
3163 			 *
3164 			 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
3165 			 * in that band on it's way to IDLE.
3166 			 */
3167 
3168 			if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3169 				/*
3170 				 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
3171 				 *
3172 				 * The process will move from its aging band to its higher requested
3173 				 * jetsam band.
3174 				 */
3175 				memorystatus_invalidate_idle_demotion_locked(p, TRUE);
3176 				reschedule = TRUE;
3177 			} else {
3178 				/*
3179 				 * Process is back from "dirty" to "clean".
3180 				 */
3181 
3182 				memorystatus_schedule_idle_demotion_locked(p, TRUE);
3183 				reschedule = TRUE;
3184 			}
3185 		}
3186 
3187 		memorystatus_update_idle_priority_locked(p);
3188 
3189 		if (memorystatus_highwater_enabled) {
3190 			boolean_t ledger_update_needed = TRUE;
3191 			boolean_t use_active;
3192 			boolean_t is_fatal;
3193 			/*
3194 			 * We are in this path because this process transitioned between
3195 			 * dirty <--> clean state.  Update the cached memory limits.
3196 			 */
3197 
3198 			if (proc_jetsam_state_is_active_locked(p) == TRUE) {
3199 				/*
3200 				 * process is pinned in elevated band
3201 				 * or
3202 				 * process is dirty
3203 				 */
3204 				CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
3205 				use_active = TRUE;
3206 				ledger_update_needed = TRUE;
3207 			} else {
3208 				/*
3209 				 * process is clean...but if it has opted into pressured-exit
3210 				 * we don't apply the INACTIVE limit till the process has aged
3211 				 * out and is entering the IDLE band.
3212 				 * See memorystatus_update_priority_locked() for that.
3213 				 */
3214 
3215 				if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
3216 					ledger_update_needed = FALSE;
3217 				} else {
3218 					CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
3219 					use_active = FALSE;
3220 					ledger_update_needed = TRUE;
3221 				}
3222 			}
3223 
3224 			/*
3225 			 * Enforce the new limits by writing to the ledger.
3226 			 *
3227 			 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
3228 			 * (where the task lock is taken) is bad.  So, we temporarily drop the proc_list_lock.
3229 			 * We aren't traversing the jetsam bucket list here, so we should be safe.
3230 			 * See rdar://21394491.
3231 			 */
3232 
3233 			if (ledger_update_needed && proc_ref(p, true) == p) {
3234 				int ledger_limit;
3235 				if (p->p_memstat_memlimit > 0) {
3236 					ledger_limit = p->p_memstat_memlimit;
3237 				} else {
3238 					ledger_limit = -1;
3239 				}
3240 				proc_list_unlock();
3241 				task_set_phys_footprint_limit_internal(proc_task(p), ledger_limit, NULL, use_active, is_fatal);
3242 				proc_list_lock();
3243 				proc_rele(p);
3244 
3245 				memorystatus_log_debug(
3246 					"memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
3247 					proc_getpid(p), (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
3248 					(p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, p->p_memstat_dirty,
3249 					(p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
3250 			}
3251 		}
3252 
3253 		/* If the deferral state changed, reschedule the demotion timer */
3254 		if (reschedule) {
3255 			memorystatus_reschedule_idle_demotion_locked();
3256 		}
3257 
3258 		/* Settle dirty time in ledger, and update transition timestamp */
3259 		task_t t = proc_task(p);
3260 		if (was_dirty) {
3261 			task_ledger_settle_dirty_time(t);
3262 			task_set_dirty_start(t, 0);
3263 		} else {
3264 			task_set_dirty_start(t, mach_absolute_time());
3265 		}
3266 	}
3267 
3268 	if (kill) {
3269 		if (proc_ref(p, true) == p) {
3270 			proc_list_unlock();
3271 			psignal(p, SIGKILL);
3272 			proc_list_lock();
3273 			proc_rele(p);
3274 		}
3275 	}
3276 
3277 exit:
3278 	proc_list_unlock();
3279 
3280 	return ret;
3281 }
3282 
3283 int
memorystatus_dirty_clear(proc_t p,uint32_t pcontrol)3284 memorystatus_dirty_clear(proc_t p, uint32_t pcontrol)
3285 {
3286 	int ret = 0;
3287 
3288 	memorystatus_log_debug("memorystatus_dirty_clear(): %d 0x%x 0x%x\n", proc_getpid(p), pcontrol, p->p_memstat_dirty);
3289 
3290 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_DIRTY_CLEAR), proc_getpid(p), pcontrol);
3291 
3292 	proc_list_lock();
3293 
3294 	if (proc_list_exited(p)) {
3295 		/*
3296 		 * Process is on its way out.
3297 		 */
3298 		ret = EBUSY;
3299 		goto exit;
3300 	}
3301 
3302 	if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
3303 		ret = EPERM;
3304 		goto exit;
3305 	}
3306 
3307 	if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
3308 		/* Dirty tracking not enabled */
3309 		ret = EINVAL;
3310 		goto exit;
3311 	}
3312 
3313 	if (!pcontrol || (pcontrol & (PROC_DIRTY_LAUNCH_IN_PROGRESS | PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) == 0) {
3314 		ret = EINVAL;
3315 		goto exit;
3316 	}
3317 
3318 	if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
3319 		p->p_memstat_dirty &= ~P_DIRTY_LAUNCH_IN_PROGRESS;
3320 	}
3321 
3322 	/* This can be set and cleared exactly once. */
3323 	if (pcontrol & (PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) {
3324 		if (p->p_memstat_dirty & P_DIRTY_DEFER) {
3325 			p->p_memstat_dirty &= ~(P_DIRTY_DEFER);
3326 		}
3327 
3328 		if (p->p_memstat_dirty & P_DIRTY_DEFER_ALWAYS) {
3329 			p->p_memstat_dirty &= ~(P_DIRTY_DEFER_ALWAYS);
3330 		}
3331 
3332 		memorystatus_invalidate_idle_demotion_locked(p, TRUE);
3333 		memorystatus_update_idle_priority_locked(p);
3334 		memorystatus_reschedule_idle_demotion_locked();
3335 	}
3336 
3337 	ret = 0;
3338 exit:
3339 	proc_list_unlock();
3340 
3341 	return ret;
3342 }
3343 
3344 int
memorystatus_dirty_get(proc_t p,boolean_t locked)3345 memorystatus_dirty_get(proc_t p, boolean_t locked)
3346 {
3347 	int ret = 0;
3348 
3349 	if (!locked) {
3350 		proc_list_lock();
3351 	}
3352 
3353 	if (p->p_memstat_dirty & P_DIRTY_TRACK) {
3354 		ret |= PROC_DIRTY_TRACKED;
3355 		if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
3356 			ret |= PROC_DIRTY_ALLOWS_IDLE_EXIT;
3357 		}
3358 		if (p->p_memstat_dirty & P_DIRTY) {
3359 			ret |= PROC_DIRTY_IS_DIRTY;
3360 		}
3361 		if (p->p_memstat_dirty & P_DIRTY_LAUNCH_IN_PROGRESS) {
3362 			ret |= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS;
3363 		}
3364 	}
3365 
3366 	if (!locked) {
3367 		proc_list_unlock();
3368 	}
3369 
3370 	return ret;
3371 }
3372 
3373 int
memorystatus_on_terminate(proc_t p)3374 memorystatus_on_terminate(proc_t p)
3375 {
3376 	int sig;
3377 
3378 	proc_list_lock();
3379 
3380 	p->p_memstat_dirty |= P_DIRTY_TERMINATED;
3381 
3382 	if (((p->p_memstat_dirty & (P_DIRTY_TRACK | P_DIRTY_IS_DIRTY)) == P_DIRTY_TRACK) ||
3383 	    (p->p_memstat_state & P_MEMSTAT_SUSPENDED)) {
3384 		/*
3385 		 * Mark as terminated and issue SIGKILL if:-
3386 		 * - process is clean, or,
3387 		 * - if process is dirty but suspended. This case is likely
3388 		 * an extension because apps don't opt into dirty-tracking
3389 		 * and daemons aren't suspended.
3390 		 */
3391 #if DEVELOPMENT || DEBUG
3392 		if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
3393 			memorystatus_log_info(
3394 				"memorystatus: sending suspended process %s (pid %d) SIGKILL\n",
3395 				(*p->p_name ? p->p_name : "unknown"), proc_getpid(p));
3396 		}
3397 #endif /* DEVELOPMENT || DEBUG */
3398 		sig = SIGKILL;
3399 	} else {
3400 		/* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3401 		sig = SIGTERM;
3402 	}
3403 
3404 	proc_list_unlock();
3405 
3406 	return sig;
3407 }
3408 
3409 void
memorystatus_on_suspend(proc_t p)3410 memorystatus_on_suspend(proc_t p)
3411 {
3412 #if CONFIG_FREEZE
3413 	uint32_t pages;
3414 	memorystatus_get_task_page_counts(proc_task(p), &pages, NULL, NULL);
3415 #endif
3416 	proc_list_lock();
3417 #if CONFIG_FREEZE
3418 	memorystatus_suspended_count++;
3419 #endif
3420 	p->p_memstat_state |= P_MEMSTAT_SUSPENDED;
3421 
3422 	/* Check if proc is marked for termination */
3423 	bool kill_process = !!(p->p_memstat_dirty & P_DIRTY_TERMINATED);
3424 	proc_list_unlock();
3425 
3426 	if (kill_process) {
3427 		psignal(p, SIGKILL);
3428 	}
3429 
3430 #if CONFIG_DEFERRED_RECLAIM
3431 	vm_deferred_reclamation_reclaim_from_task_async(proc_task(p));
3432 #endif /* CONFIG_DEFERRED_RECLAIM */
3433 }
3434 
3435 extern uint64_t memorystatus_thaw_count_since_boot;
3436 
3437 void
memorystatus_on_resume(proc_t p)3438 memorystatus_on_resume(proc_t p)
3439 {
3440 #if CONFIG_FREEZE
3441 	boolean_t frozen;
3442 	pid_t pid;
3443 #endif
3444 
3445 	proc_list_lock();
3446 
3447 #if CONFIG_FREEZE
3448 	frozen = (p->p_memstat_state & P_MEMSTAT_FROZEN);
3449 	if (frozen) {
3450 		/*
3451 		 * Now that we don't _thaw_ a process completely,
3452 		 * resuming it (and having some on-demand swapins)
3453 		 * shouldn't preclude it from being counted as frozen.
3454 		 *
3455 		 * memorystatus_frozen_count--;
3456 		 *
3457 		 * We preserve the P_MEMSTAT_FROZEN state since the process
3458 		 * could have state on disk AND so will deserve some protection
3459 		 * in the jetsam bands.
3460 		 */
3461 		if ((p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) == 0) {
3462 			p->p_memstat_state |= P_MEMSTAT_REFREEZE_ELIGIBLE;
3463 			memorystatus_refreeze_eligible_count++;
3464 		}
3465 		if (p->p_memstat_thaw_count == 0 || p->p_memstat_last_thaw_interval < memorystatus_freeze_current_interval) {
3466 			os_atomic_inc(&(memorystatus_freezer_stats.mfs_processes_thawed), relaxed);
3467 			if (strcmp(p->p_name, "com.apple.WebKit.WebContent") == 0) {
3468 				os_atomic_inc(&(memorystatus_freezer_stats.mfs_processes_thawed_webcontent), relaxed);
3469 			}
3470 		}
3471 		p->p_memstat_last_thaw_interval = memorystatus_freeze_current_interval;
3472 		p->p_memstat_thaw_count++;
3473 
3474 		memorystatus_thaw_count++;
3475 		memorystatus_thaw_count_since_boot++;
3476 	}
3477 
3478 	if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
3479 		memorystatus_suspended_count--;
3480 	}
3481 
3482 	pid = proc_getpid(p);
3483 #endif
3484 
3485 	/*
3486 	 * P_MEMSTAT_FROZEN will remain unchanged. This used to be:
3487 	 * p->p_memstat_state &= ~(P_MEMSTAT_SUSPENDED | P_MEMSTAT_FROZEN);
3488 	 */
3489 	p->p_memstat_state &= ~P_MEMSTAT_SUSPENDED;
3490 
3491 	proc_list_unlock();
3492 
3493 #if CONFIG_FREEZE
3494 	if (frozen) {
3495 		memorystatus_freeze_entry_t data = { pid, FALSE, 0 };
3496 		memorystatus_send_note(kMemorystatusFreezeNote, &data, sizeof(data));
3497 	}
3498 #endif
3499 }
3500 
3501 void
memorystatus_on_inactivity(proc_t p)3502 memorystatus_on_inactivity(proc_t p)
3503 {
3504 #pragma unused(p)
3505 #if CONFIG_FREEZE
3506 	/* Wake the freeze thread */
3507 	thread_wakeup((event_t)&memorystatus_freeze_wakeup);
3508 #endif
3509 }
3510 
3511 /*
3512  * The proc_list_lock is held by the caller.
3513  */
3514 static uint32_t
memorystatus_build_state(proc_t p)3515 memorystatus_build_state(proc_t p)
3516 {
3517 	uint32_t snapshot_state = 0;
3518 
3519 	/* General */
3520 	if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
3521 		snapshot_state |= kMemorystatusSuspended;
3522 	}
3523 	if (p->p_memstat_state & P_MEMSTAT_FROZEN) {
3524 		snapshot_state |= kMemorystatusFrozen;
3525 	}
3526 	if (p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) {
3527 		snapshot_state |= kMemorystatusWasThawed;
3528 	}
3529 	if (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION) {
3530 		snapshot_state |= kMemorystatusAssertion;
3531 	}
3532 
3533 	/* Tracking */
3534 	if (p->p_memstat_dirty & P_DIRTY_TRACK) {
3535 		snapshot_state |= kMemorystatusTracked;
3536 	}
3537 	if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
3538 		snapshot_state |= kMemorystatusSupportsIdleExit;
3539 	}
3540 	if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3541 		snapshot_state |= kMemorystatusDirty;
3542 	}
3543 
3544 	return snapshot_state;
3545 }
3546 
3547 static boolean_t
kill_idle_exit_proc(void)3548 kill_idle_exit_proc(void)
3549 {
3550 	proc_t p, victim_p = PROC_NULL;
3551 	uint64_t current_time, footprint_of_killed_proc;
3552 	boolean_t killed = FALSE;
3553 	unsigned int i = 0;
3554 	os_reason_t jetsam_reason = OS_REASON_NULL;
3555 
3556 	/* Pick next idle exit victim. */
3557 	current_time = mach_absolute_time();
3558 
3559 	jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_IDLE_EXIT);
3560 	if (jetsam_reason == OS_REASON_NULL) {
3561 		memorystatus_log_error("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3562 	}
3563 
3564 	proc_list_lock();
3565 
3566 	p = memorystatus_get_first_proc_locked(&i, FALSE);
3567 	while (p) {
3568 		/* No need to look beyond the idle band */
3569 		if (p->p_memstat_effectivepriority != JETSAM_PRIORITY_IDLE) {
3570 			break;
3571 		}
3572 
3573 		if ((p->p_memstat_dirty & (P_DIRTY_ALLOW_IDLE_EXIT | P_DIRTY_IS_DIRTY | P_DIRTY_TERMINATED)) == (P_DIRTY_ALLOW_IDLE_EXIT)) {
3574 			if (current_time >= p->p_memstat_idledeadline) {
3575 				p->p_memstat_dirty |= P_DIRTY_TERMINATED;
3576 				victim_p = proc_ref(p, true);
3577 				break;
3578 			}
3579 		}
3580 
3581 		p = memorystatus_get_next_proc_locked(&i, p, FALSE);
3582 	}
3583 
3584 	proc_list_unlock();
3585 
3586 	if (victim_p) {
3587 		memorystatus_log(
3588 			"memorystatus: killing_idle_process pid %d [%s] jetsam_reason->osr_code: %llu\n",
3589 			proc_getpid(victim_p), (*victim_p->p_name ? victim_p->p_name : "unknown"), jetsam_reason->osr_code);
3590 		killed = memorystatus_do_kill(victim_p, kMemorystatusKilledIdleExit, jetsam_reason, &footprint_of_killed_proc);
3591 		proc_rele(victim_p);
3592 	} else {
3593 		os_reason_free(jetsam_reason);
3594 	}
3595 
3596 	return killed;
3597 }
3598 
3599 void
memorystatus_thread_wake()3600 memorystatus_thread_wake()
3601 {
3602 	int thr_id = 0;
3603 	int active_thr = atomic_load(&active_jetsam_threads);
3604 
3605 	/* Wakeup all the jetsam threads */
3606 	for (thr_id = 0; thr_id < active_thr; thr_id++) {
3607 		jetsam_thread_state_t *jetsam_thread = &jetsam_threads[thr_id];
3608 		sched_cond_signal(&(jetsam_thread->jt_wakeup_cond), jetsam_thread->thread);
3609 	}
3610 }
3611 
3612 #if CONFIG_JETSAM
3613 
3614 static void
memorystatus_thread_pool_max()3615 memorystatus_thread_pool_max()
3616 {
3617 	/* Increase the jetsam thread pool to max_jetsam_threads */
3618 	int max_threads = max_jetsam_threads;
3619 	memorystatus_log_info("Expanding memorystatus pool to %d!\n", max_threads);
3620 	atomic_store(&active_jetsam_threads, max_threads);
3621 }
3622 
3623 static void
memorystatus_thread_pool_default()3624 memorystatus_thread_pool_default()
3625 {
3626 	/* Restore the jetsam thread pool to a single thread */
3627 	memorystatus_log_info("Reverting memorystatus pool back to 1\n");
3628 	atomic_store(&active_jetsam_threads, 1);
3629 }
3630 
3631 #endif /* CONFIG_JETSAM */
3632 
3633 extern void vm_pressure_response(void);
3634 
3635 bool
memorystatus_avail_pages_below_pressure(void)3636 memorystatus_avail_pages_below_pressure(void)
3637 {
3638 #if CONFIG_JETSAM
3639 	return memorystatus_available_pages <= memorystatus_available_pages_pressure;
3640 #else /* CONFIG_JETSAM */
3641 	return false;
3642 #endif /* CONFIG_JETSAM */
3643 }
3644 
3645 bool
memorystatus_avail_pages_below_critical(void)3646 memorystatus_avail_pages_below_critical(void)
3647 {
3648 #if CONFIG_JETSAM
3649 	return memorystatus_available_pages <= memorystatus_available_pages_critical;
3650 #else /* CONFIG_JETSAM */
3651 	return false;
3652 #endif /* CONFIG_JETSAM */
3653 }
3654 
3655 #if CONFIG_JETSAM
3656 static uint64_t
memorystatus_swap_trigger_pages(void)3657 memorystatus_swap_trigger_pages(void)
3658 {
3659 	/*
3660 	 * The swapout trigger varies based on the current memorystatus_level.
3661 	 * When available memory is somewhat high (at memorystatus_available_pages_pressure)
3662 	 * we keep more swappable compressor segments in memory.
3663 	 * However, as available memory drops to our idle and eventually critical kill
3664 	 * thresholds we start swapping more aggressively.
3665 	 */
3666 	static uint32_t available_pages_factor[] = {0, 1, 1, 1, 2, 2, 3, 5, 7, 8, 10, 13, 15, 17, 20};
3667 	size_t index = MIN(memorystatus_level, sizeof(available_pages_factor) / sizeof(uint32_t) - 1);
3668 	return available_pages_factor[index] * memorystatus_available_pages / 10;
3669 }
3670 
3671 static int
3672 sysctl_memorystatus_swap_trigger_pages SYSCTL_HANDLER_ARGS
3673 {
3674 #pragma unused(arg1, arg2)
3675 	uint64_t trigger_pages = memorystatus_swap_trigger_pages();
3676 	return SYSCTL_OUT(req, &trigger_pages, sizeof(trigger_pages));
3677 }
3678 
3679 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_swap_trigger_pages, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED,
3680     0, 0, &sysctl_memorystatus_swap_trigger_pages, "I", "");
3681 
3682 /*
3683  * Check if the number of full swappable csegments is over the trigger
3684  * threshold to start swapping.
3685  * The adjustment_factor is applied to the trigger to raise or lower
3686  * it. For example an adjustement factor of 110 will raise the threshold by 10%.
3687  */
3688 bool
memorystatus_swap_over_trigger(uint64_t adjustment_factor)3689 memorystatus_swap_over_trigger(uint64_t adjustment_factor)
3690 {
3691 	if (!memorystatus_swap_all_apps) {
3692 		return false;
3693 	}
3694 	uint64_t trigger_pages = memorystatus_swap_trigger_pages();
3695 	trigger_pages = trigger_pages * adjustment_factor / 100;
3696 	return atop_64(c_late_swapout_count * c_seg_allocsize) > trigger_pages;
3697 }
3698 
3699 /*
3700  * Check if the number of segments on the early swapin queue
3701  * is over the trigger to start compacting it.
3702  */
3703 bool
memorystatus_swapin_over_trigger(void)3704 memorystatus_swapin_over_trigger(void)
3705 {
3706 	return atop_64(c_late_swappedin_count * c_seg_allocsize) > memorystatus_swapin_trigger_pages;
3707 }
3708 #endif /* CONFIG_JETSAM */
3709 
3710 #if DEVELOPMENT || DEBUG
3711 SYSCTL_UINT(_vm, OID_AUTO, c_late_swapout_count, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, &c_late_swapout_count, 0, "");
3712 SYSCTL_UINT(_vm, OID_AUTO, c_seg_allocsize, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, &c_seg_allocsize, 0, "");
3713 #if CONFIG_FREEZE
3714 extern int32_t c_segment_pages_compressed_incore_late_swapout;
3715 SYSCTL_INT(_vm, OID_AUTO, c_segment_pages_compressed_incore_late_swapout, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, &c_segment_pages_compressed_incore_late_swapout, 0, "");
3716 #endif /* CONFIG_FREEZE */
3717 #endif /* DEVELOPMENT || DEBUG */
3718 
3719 static boolean_t
memorystatus_should_post_snapshot(int32_t priority,uint32_t cause)3720 memorystatus_should_post_snapshot(int32_t priority, uint32_t cause)
3721 {
3722 	boolean_t is_idle_priority;
3723 
3724 	is_idle_priority = (priority == JETSAM_PRIORITY_IDLE || priority == JETSAM_PRIORITY_IDLE_DEFERRED);
3725 #if CONFIG_JETSAM
3726 #pragma unused(cause)
3727 	/*
3728 	 * Don't generate logs for steady-state idle-exit kills,
3729 	 * unless it is overridden for debug or by the device
3730 	 * tree.
3731 	 */
3732 
3733 	return !is_idle_priority || memorystatus_idle_snapshot;
3734 
3735 #else /* CONFIG_JETSAM */
3736 	/*
3737 	 * Don't generate logs for steady-state idle-exit kills,
3738 	 * unless
3739 	 * - it is overridden for debug or by the device
3740 	 * tree.
3741 	 * OR
3742 	 * - the kill causes are important i.e. not kMemorystatusKilledIdleExit
3743 	 */
3744 
3745 	boolean_t snapshot_eligible_kill_cause = (is_reason_thrashing(cause) || is_reason_zone_map_exhaustion(cause));
3746 	return !is_idle_priority || memorystatus_idle_snapshot || snapshot_eligible_kill_cause;
3747 #endif /* CONFIG_JETSAM */
3748 }
3749 
3750 
3751 static boolean_t
memorystatus_act_on_hiwat_processes(uint32_t * errors,uint32_t * hwm_kill,bool * post_snapshot,uint64_t * memory_reclaimed)3752 memorystatus_act_on_hiwat_processes(uint32_t *errors, uint32_t *hwm_kill, bool *post_snapshot, uint64_t *memory_reclaimed)
3753 {
3754 	boolean_t purged = FALSE, killed = FALSE;
3755 
3756 	*memory_reclaimed = 0;
3757 	killed = memorystatus_kill_hiwat_proc(errors, &purged, memory_reclaimed);
3758 
3759 	if (killed) {
3760 		*hwm_kill = *hwm_kill + 1;
3761 		*post_snapshot = TRUE;
3762 		return TRUE;
3763 	} else {
3764 		if (purged == FALSE) {
3765 			/* couldn't purge and couldn't kill */
3766 			memorystatus_hwm_candidates = FALSE;
3767 		}
3768 	}
3769 
3770 	return killed;
3771 }
3772 
3773 static bool
memorystatus_dump_caches(bool purge_corpses)3774 memorystatus_dump_caches(bool purge_corpses)
3775 {
3776 	pmap_release_pages_fast();
3777 	if (purge_corpses && total_corpses_count() > 0) {
3778 		os_atomic_inc(&block_corpses, relaxed);
3779 		assert(block_corpses > 0);
3780 		task_purge_all_corpses();
3781 		return true;
3782 	}
3783 	return false;
3784 }
3785 
3786 /*
3787  * Called before jetsamming in the foreground band in the hope that we'll
3788  * avoid a jetsam.
3789  */
3790 static void
memorystatus_approaching_fg_band(bool * corpse_list_purged)3791 memorystatus_approaching_fg_band(bool *corpse_list_purged)
3792 {
3793 	bool corpses_purged = false;
3794 	assert(corpse_list_purged != NULL);
3795 	if (memorystatus_should_issue_fg_band_notify) {
3796 		memorystatus_issue_fg_band_notify();
3797 	}
3798 	corpses_purged = memorystatus_dump_caches(!(*corpse_list_purged));
3799 	*corpse_list_purged |= corpses_purged;
3800 #if CONFIG_DEFERRED_RECLAIM
3801 	vm_deferred_reclamation_reclaim_all_memory();
3802 #endif /* CONFIG_DEFERRED_RECLAIM */
3803 }
3804 
3805 int       jld_eval_aggressive_count = 0;
3806 int32_t   jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
3807 uint64_t  jld_timestamp_msecs = 0;
3808 int       jld_idle_kill_candidates = 0;
3809 
3810 static boolean_t
memorystatus_act_aggressive(uint32_t cause,os_reason_t jetsam_reason,int * jld_idle_kills,bool * corpse_list_purged,bool * post_snapshot,uint64_t * memory_reclaimed)3811 memorystatus_act_aggressive(uint32_t cause, os_reason_t jetsam_reason, int *jld_idle_kills, bool *corpse_list_purged, bool *post_snapshot, uint64_t *memory_reclaimed)
3812 {
3813 	boolean_t killed;
3814 	uint32_t errors = 0;
3815 	uint64_t footprint_of_killed_proc = 0;
3816 	int elevated_bucket_count = 0, maximum_kills = 0, band = 0;
3817 	*memory_reclaimed = 0;
3818 
3819 	jld_eval_aggressive_count++;
3820 
3821 	if (jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) {
3822 		memorystatus_approaching_fg_band(corpse_list_purged);
3823 	} else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
3824 		/*
3825 		 * Bump up the jetsam priority limit (eg: the bucket index)
3826 		 * Enforce bucket index sanity.
3827 		 */
3828 		if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
3829 		    (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
3830 			/*
3831 			 * Do nothing.  Stick with the default level.
3832 			 */
3833 		} else {
3834 			jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
3835 		}
3836 	}
3837 
3838 	proc_list_lock();
3839 	elevated_bucket_count = memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE].count;
3840 	proc_list_unlock();
3841 
3842 	/* Visit elevated processes first */
3843 	while (elevated_bucket_count) {
3844 		elevated_bucket_count--;
3845 
3846 		/*
3847 		 * memorystatus_kill_elevated_process() drops a reference,
3848 		 * so take another one so we can continue to use this exit reason
3849 		 * even after it returns.
3850 		 */
3851 
3852 		os_reason_ref(jetsam_reason);
3853 		killed = memorystatus_kill_elevated_process(
3854 			cause,
3855 			jetsam_reason,
3856 			JETSAM_PRIORITY_ELEVATED_INACTIVE,
3857 			jld_eval_aggressive_count,
3858 			&errors, &footprint_of_killed_proc);
3859 		if (killed) {
3860 			*post_snapshot = true;
3861 			*memory_reclaimed += footprint_of_killed_proc;
3862 			if (memorystatus_avail_pages_below_pressure()) {
3863 				/*
3864 				 * Still under pressure.
3865 				 * Find another pinned processes.
3866 				 */
3867 				continue;
3868 			} else {
3869 				return TRUE;
3870 			}
3871 		} else {
3872 			/*
3873 			 * No pinned processes left to kill.
3874 			 * Abandon elevated band.
3875 			 */
3876 			break;
3877 		}
3878 	}
3879 
3880 	proc_list_lock();
3881 	for (band = 0; band < jld_priority_band_max; band++) {
3882 		maximum_kills += memstat_bucket[band].count;
3883 	}
3884 	proc_list_unlock();
3885 	maximum_kills *= memorystatus_jld_max_kill_loops;
3886 	/*
3887 	 * memorystatus_kill_processes_aggressive() allocates its own
3888 	 * jetsam_reason so the kMemorystatusKilledProcThrashing cause
3889 	 * is consistent throughout the aggressive march.
3890 	 */
3891 	killed = memorystatus_kill_processes_aggressive(
3892 		kMemorystatusKilledProcThrashing,
3893 		jld_eval_aggressive_count,
3894 		jld_priority_band_max,
3895 		maximum_kills,
3896 		&errors, &footprint_of_killed_proc);
3897 
3898 	if (killed) {
3899 		/* Always generate logs after aggressive kill */
3900 		*post_snapshot = true;
3901 		*memory_reclaimed += footprint_of_killed_proc;
3902 		*jld_idle_kills = 0;
3903 		return TRUE;
3904 	}
3905 
3906 	return FALSE;
3907 }
3908 
3909 /*
3910  * Sets up a new jetsam thread.
3911  */
3912 static void
memorystatus_thread_init(jetsam_thread_state_t * jetsam_thread)3913 memorystatus_thread_init(jetsam_thread_state_t *jetsam_thread)
3914 {
3915 	char name[32];
3916 	thread_wire(host_priv_self(), current_thread(), TRUE);
3917 	snprintf(name, 32, "VM_memorystatus_%d", jetsam_thread->index + 1);
3918 
3919 	/* Limit all but one thread to the lower jetsam bands, as that's where most of the victims are. */
3920 	if (jetsam_thread->index == 0) {
3921 		if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
3922 			thread_vm_bind_group_add();
3923 		}
3924 		jetsam_thread->limit_to_low_bands = FALSE;
3925 	} else {
3926 		jetsam_thread->limit_to_low_bands = TRUE;
3927 	}
3928 #if CONFIG_THREAD_GROUPS
3929 	thread_group_vm_add();
3930 #endif
3931 	thread_set_thread_name(current_thread(), name);
3932 	sched_cond_init(&(jetsam_thread->jt_wakeup_cond));
3933 	jetsam_thread->inited = TRUE;
3934 }
3935 
3936 /*
3937  * Create a new jetsam reason from the given kill cause.
3938  */
3939 static os_reason_t
create_jetsam_reason(memorystatus_kill_cause_t cause)3940 create_jetsam_reason(memorystatus_kill_cause_t cause)
3941 {
3942 	os_reason_t jetsam_reason = OS_REASON_NULL;
3943 
3944 	jetsam_reason_t reason_code = (jetsam_reason_t)cause;
3945 	assert3u(reason_code, <=, JETSAM_REASON_MEMORYSTATUS_MAX);
3946 
3947 	jetsam_reason = os_reason_create(OS_REASON_JETSAM, reason_code);
3948 	if (jetsam_reason == OS_REASON_NULL) {
3949 		memorystatus_log_error("memorystatus: failed to allocate jetsam reason for cause %u\n", cause);
3950 	}
3951 	return jetsam_reason;
3952 }
3953 
3954 /*
3955  * Do one kill as we're marching up the priority bands.
3956  * This is a wrapper around memorystatus_kill_top_process that also
3957  * sets post_snapshot, tracks jld_idle_kills, and notifies if we're appraoching the fg band.
3958  */
3959 static bool
memorystatus_do_priority_kill(jetsam_thread_state_t * thread,uint32_t kill_cause,int32_t max_priority,bool only_swappable)3960 memorystatus_do_priority_kill(jetsam_thread_state_t *thread,
3961     uint32_t kill_cause, int32_t max_priority, bool only_swappable)
3962 {
3963 	os_reason_t jetsam_reason = OS_REASON_NULL;
3964 	bool killed = false;
3965 	int priority;
3966 
3967 	jetsam_reason = create_jetsam_reason(kill_cause);
3968 	/*
3969 	 * memorystatus_kill_top_process() drops a reference,
3970 	 * so take another one so we can continue to use this exit reason
3971 	 * even after it returns
3972 	 */
3973 	os_reason_ref(jetsam_reason);
3974 
3975 	/* LRU */
3976 	killed = memorystatus_kill_top_process(true, thread->sort_flag, kill_cause, jetsam_reason, max_priority,
3977 	    only_swappable, &priority, &thread->errors, &thread->memory_reclaimed);
3978 	thread->sort_flag = false;
3979 
3980 	if (killed) {
3981 		if (memorystatus_should_post_snapshot(priority, kill_cause) == TRUE) {
3982 			thread->post_snapshot = true;
3983 		}
3984 
3985 		/* Jetsam Loop Detection */
3986 		if (memorystatus_jld_enabled == TRUE) {
3987 			if (priority <= applications_aging_band) {
3988 				thread->jld_idle_kills++;
3989 			} else {
3990 				/*
3991 				 * We've reached into bands beyond idle deferred.
3992 				 * We make no attempt to monitor them
3993 				 */
3994 			}
3995 		}
3996 
3997 		/*
3998 		 * If we have jetsammed a process in or above JETSAM_PRIORITY_FREEZER
3999 		 * then we attempt to relieve pressure by purging corpse memory and notifying
4000 		 * anybody wanting to know this.
4001 		 */
4002 		if (priority >= JETSAM_PRIORITY_FREEZER) {
4003 			memorystatus_approaching_fg_band(&thread->corpse_list_purged);
4004 		}
4005 	}
4006 	os_reason_free(jetsam_reason);
4007 
4008 	return killed;
4009 }
4010 
4011 static bool
memorystatus_do_action(jetsam_thread_state_t * thread,memorystatus_action_t action,uint32_t kill_cause)4012 memorystatus_do_action(jetsam_thread_state_t *thread, memorystatus_action_t action, uint32_t kill_cause)
4013 {
4014 	bool killed = false;
4015 	os_reason_t jetsam_reason = OS_REASON_NULL;
4016 
4017 	switch (action) {
4018 	case MEMORYSTATUS_KILL_HIWATER:
4019 		killed = memorystatus_act_on_hiwat_processes(&thread->errors, &thread->hwm_kills,
4020 		    &thread->post_snapshot, &thread->memory_reclaimed);
4021 		break;
4022 	case MEMORYSTATUS_KILL_AGGRESSIVE:
4023 		jetsam_reason = create_jetsam_reason(kill_cause);
4024 		killed = memorystatus_act_aggressive(kill_cause, jetsam_reason,
4025 		    &thread->jld_idle_kills, &thread->corpse_list_purged, &thread->post_snapshot,
4026 		    &thread->memory_reclaimed);
4027 		os_reason_free(jetsam_reason);
4028 		break;
4029 	case MEMORYSTATUS_KILL_TOP_PROCESS:
4030 		killed = memorystatus_do_priority_kill(thread, kill_cause, max_kill_priority, false);
4031 		break;
4032 	case MEMORYSTATUS_WAKE_SWAPPER:
4033 		memorystatus_log_info(
4034 			"memorystatus_do_action: Waking up swap thread. memorystatus_available_pages: %llu\n",
4035 			(uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
4036 		os_atomic_store(&vm_swapout_wake_pending, true, relaxed);
4037 		thread_wakeup((event_t)&vm_swapout_thread);
4038 		break;
4039 	case MEMORYSTATUS_PROCESS_SWAPIN_QUEUE:
4040 		memorystatus_log_info(
4041 			"memorystatus_do_action: Processing swapin queue of length: %u memorystatus_available_pages: %llu\n",
4042 			c_late_swappedin_count, (uint64_t) MEMORYSTATUS_LOG_AVAILABLE_PAGES);
4043 		vm_compressor_process_special_swapped_in_segments();
4044 		break;
4045 	case MEMORYSTATUS_KILL_SUSPENDED_SWAPPABLE:
4046 		killed = memorystatus_do_priority_kill(thread, kill_cause, JETSAM_PRIORITY_BACKGROUND - 1, true);
4047 		break;
4048 	case MEMORYSTATUS_KILL_SWAPPABLE:
4049 		killed = memorystatus_do_priority_kill(thread, kill_cause, max_kill_priority, true);
4050 		break;
4051 	case MEMORYSTATUS_KILL_NONE:
4052 		panic("memorystatus_do_action: Impossible! memorystatus_do_action called with action = NONE\n");
4053 	}
4054 	return killed;
4055 }
4056 
4057 static void
memorystatus_post_snapshot()4058 memorystatus_post_snapshot()
4059 {
4060 	proc_list_lock();
4061 	size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
4062 	    sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count);
4063 	uint64_t timestamp_now = mach_absolute_time();
4064 	memorystatus_jetsam_snapshot->notification_time = timestamp_now;
4065 	memorystatus_jetsam_snapshot->js_gencount++;
4066 	if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
4067 	    timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
4068 		proc_list_unlock();
4069 		int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
4070 		if (!ret) {
4071 			proc_list_lock();
4072 			memorystatus_jetsam_snapshot_last_timestamp = timestamp_now; proc_list_unlock();
4073 		}
4074 	} else {
4075 		proc_list_unlock();
4076 	}
4077 }
4078 
4079 
4080 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
4081 extern void vm_thrashing_jetsam_done(void);
4082 
4083 /*
4084  * Main entrypoint for the memorystatus thread.
4085  * This thread is woken up when we're low on one of the following resources:
4086  * - available pages (free + filebacked)
4087  * - zone memory
4088  * - compressor space
4089  *
4090  * Or when thrashing is detected in the compressor or file cache.
4091  */
4092 static void
memorystatus_thread_internal(jetsam_thread_state_t * jetsam_thread)4093 memorystatus_thread_internal(jetsam_thread_state_t *jetsam_thread)
4094 {
4095 	uint64_t total_memory_reclaimed = 0;
4096 	bool highwater_remaining = true;
4097 	bool swappable_apps_remaining = false;
4098 	bool suspended_swappable_apps_remaining = false;
4099 
4100 #if CONFIG_JETSAM
4101 	swappable_apps_remaining = memorystatus_swap_all_apps;
4102 	suspended_swappable_apps_remaining = memorystatus_swap_all_apps;
4103 #endif /* CONFIG_JETSAM */
4104 
4105 	assert(jetsam_thread != NULL);
4106 	jetsam_thread->jld_idle_kills = 0;
4107 	jetsam_thread->errors = 0;
4108 	jetsam_thread->hwm_kills = 0;
4109 	jetsam_thread->sort_flag = true;
4110 	jetsam_thread->corpse_list_purged = false;
4111 	jetsam_thread->post_snapshot = FALSE;
4112 	jetsam_thread->memory_reclaimed = 0;
4113 
4114 	if (jetsam_thread->inited == FALSE) {
4115 		/*
4116 		 * It's the first time the thread has run, so just mark the thread as privileged and block.
4117 		 */
4118 		memorystatus_thread_init(jetsam_thread);
4119 		sched_cond_wait(&(jetsam_thread->jt_wakeup_cond), THREAD_UNINT, memorystatus_thread);
4120 	}
4121 
4122 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_SCAN) | DBG_FUNC_START,
4123 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, memorystatus_jld_enabled, memorystatus_jld_eval_period_msecs, memorystatus_jld_eval_aggressive_count);
4124 
4125 	extern uint32_t c_segment_count;
4126 	extern mach_timespec_t major_compact_ts;
4127 	clock_sec_t now;
4128 	clock_nsec_t nsec;
4129 	clock_get_system_nanotime(&now, &nsec);
4130 	mach_timespec_t major_compact_diff = {.tv_sec = (int)now, .tv_nsec = nsec};
4131 	SUB_MACH_TIMESPEC(&major_compact_diff, &major_compact_ts);
4132 	memorystatus_log_info(
4133 		"memorystatus: c_segment_count=%u major compaction occurred %u seconds ago\n",
4134 		c_segment_count, major_compact_diff.tv_sec);
4135 
4136 	/*
4137 	 * Jetsam aware version.
4138 	 *
4139 	 * The VM pressure notification thread is working its way through clients in parallel.
4140 	 *
4141 	 * So, while the pressure notification thread is targeting processes in order of
4142 	 * increasing jetsam priority, we can hopefully reduce / stop its work by killing
4143 	 * any processes that have exceeded their highwater mark.
4144 	 *
4145 	 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
4146 	 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
4147 	 */
4148 	while (true) {
4149 		bool killed;
4150 		jetsam_thread->memory_reclaimed = 0;
4151 		uint32_t cause = 0;
4152 
4153 		memorystatus_action_t action = memorystatus_pick_action(jetsam_thread, &cause,
4154 		    highwater_remaining, suspended_swappable_apps_remaining, swappable_apps_remaining,
4155 		    &jetsam_thread->jld_idle_kills);
4156 		if (action == MEMORYSTATUS_KILL_NONE) {
4157 			break;
4158 		}
4159 
4160 		if (cause == kMemorystatusKilledVMCompressorThrashing || cause == kMemorystatusKilledVMCompressorSpaceShortage) {
4161 			memorystatus_log("memorystatus: killing due to \"%s\" - compression_ratio=%u\n", memorystatus_kill_cause_name[cause], vm_compression_ratio());
4162 		}
4163 
4164 		killed = memorystatus_do_action(jetsam_thread, action, cause);
4165 		total_memory_reclaimed += jetsam_thread->memory_reclaimed;
4166 
4167 		if (!killed) {
4168 			if (action == MEMORYSTATUS_KILL_HIWATER) {
4169 				highwater_remaining = false;
4170 			} else if (action == MEMORYSTATUS_KILL_SWAPPABLE) {
4171 				swappable_apps_remaining = false;
4172 				suspended_swappable_apps_remaining = false;
4173 			} else if (action == MEMORYSTATUS_KILL_SUSPENDED_SWAPPABLE) {
4174 				suspended_swappable_apps_remaining = false;
4175 			}
4176 		} else {
4177 			if (cause == kMemorystatusKilledVMCompressorThrashing || cause == kMemorystatusKilledVMCompressorSpaceShortage) {
4178 				memorystatus_log("memorystatus: post-jetsam compressor fragmentation_level=%u\n", vm_compressor_fragmentation_level());
4179 			}
4180 			/* Always re-check for highwater and swappable kills after doing a kill. */
4181 			highwater_remaining = true;
4182 			swappable_apps_remaining = true;
4183 			suspended_swappable_apps_remaining = true;
4184 		}
4185 
4186 		if ((action == MEMORYSTATUS_KILL_TOP_PROCESS || action == MEMORYSTATUS_KILL_AGGRESSIVE) && !killed && total_memory_reclaimed == 0 && memorystatus_avail_pages_below_critical()) {
4187 			/*
4188 			 * Still under pressure and unable to kill a process - purge corpse memory
4189 			 * and get everything back from the pmap.
4190 			 */
4191 			memorystatus_dump_caches(true);
4192 
4193 			if (!jetsam_thread->limit_to_low_bands && memorystatus_avail_pages_below_critical()) {
4194 				/*
4195 				 * Still under pressure and unable to kill a process - panic
4196 				 */
4197 				panic("memorystatus_jetsam_thread: no victim! available pages:%llu", (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
4198 			}
4199 		}
4200 
4201 		/*
4202 		 * If we did a kill on behalf of another subsystem (compressor or zalloc)
4203 		 * notify them.
4204 		 */
4205 		if (killed && is_reason_thrashing(cause)) {
4206 			os_atomic_store(&memorystatus_compressor_space_shortage, false, release);
4207 #if CONFIG_PHANTOM_CACHE
4208 			os_atomic_store(&memorystatus_phantom_cache_pressure, false, release);
4209 #endif /* CONFIG_PHANTOM_CACHE */
4210 #if CONFIG_JETSAM
4211 			vm_thrashing_jetsam_done();
4212 #endif /* CONFIG_JETSAM */
4213 		} else if (killed && is_reason_zone_map_exhaustion(cause)) {
4214 			os_atomic_store(&memorystatus_zone_map_is_exhausted, false, release);
4215 		} else if (killed && cause == kMemorystatusKilledVMPageoutStarvation) {
4216 			os_atomic_store(&memorystatus_pageout_starved, false, release);
4217 		}
4218 	}
4219 
4220 	if (jetsam_thread->errors) {
4221 		memorystatus_clear_errors();
4222 	}
4223 
4224 	if (jetsam_thread->post_snapshot) {
4225 		memorystatus_post_snapshot();
4226 	}
4227 
4228 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_SCAN) | DBG_FUNC_END,
4229 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, total_memory_reclaimed);
4230 
4231 	if (jetsam_thread->corpse_list_purged) {
4232 		os_atomic_dec(&block_corpses, relaxed);
4233 		assert(block_corpses >= 0);
4234 	}
4235 }
4236 
4237 OS_NORETURN
4238 static void
memorystatus_thread(void * param __unused,wait_result_t wr __unused)4239 memorystatus_thread(void *param __unused, wait_result_t wr __unused)
4240 {
4241 	jetsam_thread_state_t *jetsam_thread = jetsam_current_thread();
4242 	sched_cond_ack(&(jetsam_thread->jt_wakeup_cond));
4243 	while (1) {
4244 		memorystatus_thread_internal(jetsam_thread);
4245 		sched_cond_wait(&(jetsam_thread->jt_wakeup_cond), THREAD_UNINT, memorystatus_thread);
4246 	}
4247 }
4248 
4249 /*
4250  * This section defines when we deploy aggressive jetsam.
4251  * Aggressive jetsam kills everything up to the jld_priority_band_max band.
4252  */
4253 
4254 /*
4255  * Returns TRUE:
4256  *      when an idle-exitable proc was killed
4257  * Returns FALSE:
4258  *	when there are no more idle-exitable procs found
4259  *      when the attempt to kill an idle-exitable proc failed
4260  */
4261 boolean_t
memorystatus_idle_exit_from_VM(void)4262 memorystatus_idle_exit_from_VM(void)
4263 {
4264 	/*
4265 	 * This routine should no longer be needed since we are
4266 	 * now using jetsam bands on all platforms and so will deal
4267 	 * with IDLE processes within the memorystatus thread itself.
4268 	 *
4269 	 * But we still use it because we observed that macos systems
4270 	 * started heavy compression/swapping with a bunch of
4271 	 * idle-exitable processes alive and doing nothing. We decided
4272 	 * to rather kill those processes than start swapping earlier.
4273 	 */
4274 
4275 	return kill_idle_exit_proc();
4276 }
4277 
4278 /*
4279  * Callback invoked when allowable physical memory footprint exceeded
4280  * (dirty pages + IOKit mappings)
4281  *
4282  * This is invoked for both advisory, non-fatal per-task high watermarks,
4283  * as well as the fatal task memory limits.
4284  */
4285 void
memorystatus_on_ledger_footprint_exceeded(boolean_t warning,boolean_t memlimit_is_active,boolean_t memlimit_is_fatal)4286 memorystatus_on_ledger_footprint_exceeded(boolean_t warning, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
4287 {
4288 	os_reason_t jetsam_reason = OS_REASON_NULL;
4289 
4290 	proc_t p = current_proc();
4291 
4292 #if VM_PRESSURE_EVENTS
4293 	if (warning == TRUE) {
4294 		/*
4295 		 * This is a warning path which implies that the current process is close, but has
4296 		 * not yet exceeded its per-process memory limit.
4297 		 */
4298 		if (memorystatus_warn_process(p, memlimit_is_active, memlimit_is_fatal, FALSE /* not exceeded */) != TRUE) {
4299 			/* Print warning, since it's possible that task has not registered for pressure notifications */
4300 			memorystatus_log_error(
4301 				"memorystatus_on_ledger_footprint_exceeded: failed to warn the current task (%d exiting, or no handler registered?).\n",
4302 				proc_getpid(p));
4303 		}
4304 		return;
4305 	}
4306 #endif /* VM_PRESSURE_EVENTS */
4307 
4308 	if (memlimit_is_fatal) {
4309 		/*
4310 		 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
4311 		 * has violated either the system-wide per-task memory limit OR its own task limit.
4312 		 */
4313 		jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_PERPROCESSLIMIT);
4314 		if (jetsam_reason == NULL) {
4315 			memorystatus_log_error("task_exceeded footprint: failed to allocate jetsam reason\n");
4316 		} else if (corpse_for_fatal_memkill && proc_send_synchronous_EXC_RESOURCE(p) == FALSE) {
4317 			/* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
4318 			jetsam_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
4319 		}
4320 
4321 		if (memorystatus_kill_process_sync(proc_getpid(p), kMemorystatusKilledPerProcessLimit, jetsam_reason) != TRUE) {
4322 			memorystatus_log_error("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
4323 		}
4324 	} else {
4325 		/*
4326 		 * HWM offender exists. Done without locks or synchronization.
4327 		 * See comment near its declaration for more details.
4328 		 */
4329 		memorystatus_hwm_candidates = TRUE;
4330 
4331 #if VM_PRESSURE_EVENTS
4332 		/*
4333 		 * The current process is not in the warning path.
4334 		 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
4335 		 * Failure to send note is ignored here.
4336 		 */
4337 		(void)memorystatus_warn_process(p, memlimit_is_active, memlimit_is_fatal, TRUE /* exceeded */);
4338 
4339 #endif /* VM_PRESSURE_EVENTS */
4340 	}
4341 }
4342 
4343 inline void
memorystatus_log_exception(const int max_footprint_mb,boolean_t memlimit_is_active,boolean_t memlimit_is_fatal)4344 memorystatus_log_exception(const int max_footprint_mb, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
4345 {
4346 	proc_t p = current_proc();
4347 
4348 	/*
4349 	 * The limit violation is logged here, but only once per process per limit.
4350 	 * Soft memory limit is a non-fatal high-water-mark
4351 	 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
4352 	 */
4353 
4354 	memorystatus_log("EXC_RESOURCE -> %s[%d] exceeded mem limit: %s%s %d MB (%s)\n",
4355 	    ((p && *p->p_name) ? p->p_name : "unknown"), (p ? proc_getpid(p) : -1), (memlimit_is_active ? "Active" : "Inactive"),
4356 	    (memlimit_is_fatal  ? "Hard" : "Soft"), max_footprint_mb,
4357 	    (memlimit_is_fatal  ? "fatal" : "non-fatal"));
4358 }
4359 
4360 inline void
memorystatus_log_diag_threshold_exception(const int diag_threshold_value)4361 memorystatus_log_diag_threshold_exception(const int diag_threshold_value)
4362 {
4363 	proc_t p = current_proc();
4364 
4365 	/*
4366 	 * The limit violation is logged here, but only once per process per limit.
4367 	 * Soft memory limit is a non-fatal high-water-mark
4368 	 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
4369 	 */
4370 
4371 	memorystatus_log("EXC_RESOURCE -> %s[%d] exceeded diag threshold limit: %d MB \n",
4372 	    ((p && *p->p_name) ? p->p_name : "unknown"), (p ? proc_getpid(p) : -1), diag_threshold_value);
4373 }
4374 
4375 /*
4376  * Description:
4377  *	Evaluates process state to determine which limit
4378  *	should be applied (active vs. inactive limit).
4379  *
4380  *	Processes that have the 'elevated inactive jetsam band' attribute
4381  *	are first evaluated based on their current priority band.
4382  *	presently elevated ==> active
4383  *
4384  *	Processes that opt into dirty tracking are evaluated
4385  *	based on clean vs dirty state.
4386  *	dirty ==> active
4387  *	clean ==> inactive
4388  *
4389  *	Process that do not opt into dirty tracking are
4390  *	evalulated based on priority level.
4391  *	Foreground or above ==> active
4392  *	Below Foreground    ==> inactive
4393  *
4394  *	Return: TRUE if active
4395  *		False if inactive
4396  */
4397 
4398 static boolean_t
proc_jetsam_state_is_active_locked(proc_t p)4399 proc_jetsam_state_is_active_locked(proc_t p)
4400 {
4401 	if ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) &&
4402 	    (p->p_memstat_effectivepriority == JETSAM_PRIORITY_ELEVATED_INACTIVE)) {
4403 		/*
4404 		 * process has the 'elevated inactive jetsam band' attribute
4405 		 * and process is present in the elevated band
4406 		 * implies active state
4407 		 */
4408 		return TRUE;
4409 	} else if (p->p_memstat_dirty & P_DIRTY_TRACK) {
4410 		/*
4411 		 * process has opted into dirty tracking
4412 		 * active state is based on dirty vs. clean
4413 		 */
4414 		if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
4415 			/*
4416 			 * process is dirty
4417 			 * implies active state
4418 			 */
4419 			return TRUE;
4420 		} else {
4421 			/*
4422 			 * process is clean
4423 			 * implies inactive state
4424 			 */
4425 			return FALSE;
4426 		}
4427 	} else if (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND) {
4428 		/*
4429 		 * process is Foreground or higher
4430 		 * implies active state
4431 		 */
4432 		return TRUE;
4433 	} else {
4434 		/*
4435 		 * process found below Foreground
4436 		 * implies inactive state
4437 		 */
4438 		return FALSE;
4439 	}
4440 }
4441 
4442 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid,uint32_t cause,os_reason_t jetsam_reason)4443 memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason)
4444 {
4445 	boolean_t res;
4446 
4447 	uint32_t errors = 0;
4448 	uint64_t memory_reclaimed = 0;
4449 
4450 	if (victim_pid == -1) {
4451 		/* No pid, so kill first process */
4452 		res = memorystatus_kill_top_process(true, true, cause, jetsam_reason,
4453 		    max_kill_priority, false, NULL, &errors, &memory_reclaimed);
4454 	} else {
4455 		res = memorystatus_kill_specific_process(victim_pid, cause, jetsam_reason);
4456 	}
4457 
4458 	if (errors) {
4459 		memorystatus_clear_errors();
4460 	}
4461 
4462 	if (res == TRUE) {
4463 		/* Fire off snapshot notification */
4464 		proc_list_lock();
4465 		size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
4466 		    sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_count;
4467 		uint64_t timestamp_now = mach_absolute_time();
4468 		memorystatus_jetsam_snapshot->notification_time = timestamp_now;
4469 		if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
4470 		    timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
4471 			proc_list_unlock();
4472 			int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
4473 			if (!ret) {
4474 				proc_list_lock();
4475 				memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
4476 				proc_list_unlock();
4477 			}
4478 		} else {
4479 			proc_list_unlock();
4480 		}
4481 	}
4482 
4483 	return res;
4484 }
4485 
4486 /*
4487  * Jetsam a specific process.
4488  */
4489 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid,uint32_t cause,os_reason_t jetsam_reason)4490 memorystatus_kill_specific_process(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason)
4491 {
4492 	boolean_t killed;
4493 	proc_t p;
4494 	uint64_t killtime = 0;
4495 	uint64_t footprint_of_killed_proc;
4496 	clock_sec_t     tv_sec;
4497 	clock_usec_t    tv_usec;
4498 	uint32_t        tv_msec;
4499 
4500 	/* TODO - add a victim queue and push this into the main jetsam thread */
4501 
4502 	p = proc_find(victim_pid);
4503 	if (!p) {
4504 		os_reason_free(jetsam_reason);
4505 		return FALSE;
4506 	}
4507 
4508 	proc_list_lock();
4509 
4510 	if (p->p_memstat_state & P_MEMSTAT_TERMINATED) {
4511 		/*
4512 		 * Someone beat us to this kill.
4513 		 * Nothing to do here.
4514 		 */
4515 		proc_list_unlock();
4516 		os_reason_free(jetsam_reason);
4517 		proc_rele(p);
4518 		return FALSE;
4519 	}
4520 	p->p_memstat_state |= P_MEMSTAT_TERMINATED;
4521 
4522 	if (memorystatus_jetsam_snapshot_count == 0) {
4523 		memorystatus_init_jetsam_snapshot_locked(NULL, 0);
4524 	}
4525 
4526 	killtime = mach_absolute_time();
4527 	absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
4528 	tv_msec = tv_usec / 1000;
4529 
4530 	memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
4531 
4532 	proc_list_unlock();
4533 
4534 	killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
4535 
4536 	memorystatus_log("%lu.%03d memorystatus: killing_specific_process pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu\n",
4537 	    (unsigned long)tv_sec, tv_msec, victim_pid, ((p && *p->p_name) ? p->p_name : "unknown"),
4538 	    memorystatus_kill_cause_name[cause], (p ? p->p_memstat_effectivepriority: -1),
4539 	    footprint_of_killed_proc >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
4540 
4541 	if (!killed) {
4542 		proc_list_lock();
4543 		p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
4544 		proc_list_unlock();
4545 	}
4546 
4547 	proc_rele(p);
4548 
4549 	return killed;
4550 }
4551 
4552 
4553 /*
4554  * Toggle the P_MEMSTAT_SKIP bit.
4555  * Takes the proc_list_lock.
4556  */
4557 void
proc_memstat_skip(proc_t p,boolean_t set)4558 proc_memstat_skip(proc_t p, boolean_t set)
4559 {
4560 #if DEVELOPMENT || DEBUG
4561 	if (p) {
4562 		proc_list_lock();
4563 		if (set == TRUE) {
4564 			p->p_memstat_state |= P_MEMSTAT_SKIP;
4565 		} else {
4566 			p->p_memstat_state &= ~P_MEMSTAT_SKIP;
4567 		}
4568 		proc_list_unlock();
4569 	}
4570 #else
4571 #pragma unused(p, set)
4572 	/*
4573 	 * do nothing
4574 	 */
4575 #endif /* DEVELOPMENT || DEBUG */
4576 	return;
4577 }
4578 
4579 
4580 #if CONFIG_JETSAM
4581 /*
4582  * This is invoked when cpulimits have been exceeded while in fatal mode.
4583  * The jetsam_flags do not apply as those are for memory related kills.
4584  * We call this routine so that the offending process is killed with
4585  * a non-zero exit status.
4586  */
4587 void
jetsam_on_ledger_cpulimit_exceeded(void)4588 jetsam_on_ledger_cpulimit_exceeded(void)
4589 {
4590 	int retval = 0;
4591 	int jetsam_flags = 0;  /* make it obvious */
4592 	proc_t p = current_proc();
4593 	os_reason_t jetsam_reason = OS_REASON_NULL;
4594 
4595 	memorystatus_log("task_exceeded_cpulimit: killing pid %d [%s]\n", proc_getpid(p), (*p->p_name ? p->p_name : "(unknown)"));
4596 
4597 	jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_CPULIMIT);
4598 	if (jetsam_reason == OS_REASON_NULL) {
4599 		memorystatus_log_error("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
4600 	}
4601 
4602 	retval = jetsam_do_kill(p, jetsam_flags, jetsam_reason);
4603 
4604 	if (retval) {
4605 		memorystatus_log_error("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
4606 	}
4607 }
4608 
4609 #endif /* CONFIG_JETSAM */
4610 
4611 static void
memorystatus_get_task_memory_region_count(task_t task,uint64_t * count)4612 memorystatus_get_task_memory_region_count(task_t task, uint64_t *count)
4613 {
4614 	assert(task);
4615 	assert(count);
4616 
4617 	*count = get_task_memory_region_count(task);
4618 }
4619 
4620 
4621 #define MEMORYSTATUS_VM_MAP_FORK_ALLOWED     0x100000000
4622 #define MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED 0x200000000
4623 
4624 #if DEVELOPMENT || DEBUG
4625 
4626 /*
4627  * Sysctl only used to test memorystatus_allowed_vm_map_fork() path.
4628  *   set a new pidwatch value
4629  *	or
4630  *   get the current pidwatch value
4631  *
4632  * The pidwatch_val starts out with a PID to watch for in the map_fork path.
4633  * Its value is:
4634  * - OR'd with MEMORYSTATUS_VM_MAP_FORK_ALLOWED if we allow the map_fork.
4635  * - OR'd with MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED if we disallow the map_fork.
4636  * - set to -1ull if the map_fork() is aborted for other reasons.
4637  */
4638 
4639 uint64_t memorystatus_vm_map_fork_pidwatch_val = 0;
4640 
4641 static int sysctl_memorystatus_vm_map_fork_pidwatch SYSCTL_HANDLER_ARGS {
4642 #pragma unused(oidp, arg1, arg2)
4643 
4644 	uint64_t new_value = 0;
4645 	uint64_t old_value = 0;
4646 	int error = 0;
4647 
4648 	/*
4649 	 * The pid is held in the low 32 bits.
4650 	 * The 'allowed' flags are in the upper 32 bits.
4651 	 */
4652 	old_value = memorystatus_vm_map_fork_pidwatch_val;
4653 
4654 	error = sysctl_io_number(req, old_value, sizeof(old_value), &new_value, NULL);
4655 
4656 	if (error || !req->newptr) {
4657 		/*
4658 		 * No new value passed in.
4659 		 */
4660 		return error;
4661 	}
4662 
4663 	/*
4664 	 * A new pid was passed in via req->newptr.
4665 	 * Ignore any attempt to set the higher order bits.
4666 	 */
4667 	memorystatus_vm_map_fork_pidwatch_val = new_value & 0xFFFFFFFF;
4668 	memorystatus_log_debug("memorystatus: pidwatch old_value = 0x%llx, new_value = 0x%llx\n", old_value, new_value);
4669 
4670 	return error;
4671 }
4672 
4673 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_vm_map_fork_pidwatch, CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED,
4674     0, 0, sysctl_memorystatus_vm_map_fork_pidwatch, "Q", "get/set pid watched for in vm_map_fork");
4675 
4676 
4677 /*
4678  * Record if a watched process fails to qualify for a vm_map_fork().
4679  */
4680 void
memorystatus_abort_vm_map_fork(task_t task)4681 memorystatus_abort_vm_map_fork(task_t task)
4682 {
4683 	if (memorystatus_vm_map_fork_pidwatch_val != 0) {
4684 		proc_t p = get_bsdtask_info(task);
4685 		if (p != NULL && memorystatus_vm_map_fork_pidwatch_val == (uint64_t)proc_getpid(p)) {
4686 			memorystatus_vm_map_fork_pidwatch_val = -1ull;
4687 		}
4688 	}
4689 }
4690 
4691 static void
set_vm_map_fork_pidwatch(task_t task,uint64_t x)4692 set_vm_map_fork_pidwatch(task_t task, uint64_t x)
4693 {
4694 	if (memorystatus_vm_map_fork_pidwatch_val != 0) {
4695 		proc_t p = get_bsdtask_info(task);
4696 		if (p && (memorystatus_vm_map_fork_pidwatch_val == (uint64_t)proc_getpid(p))) {
4697 			memorystatus_vm_map_fork_pidwatch_val |= x;
4698 		}
4699 	}
4700 }
4701 
4702 #else /* DEVELOPMENT || DEBUG */
4703 
4704 
4705 static void
set_vm_map_fork_pidwatch(task_t task,uint64_t x)4706 set_vm_map_fork_pidwatch(task_t task, uint64_t x)
4707 {
4708 #pragma unused(task)
4709 #pragma unused(x)
4710 }
4711 
4712 #endif /* DEVELOPMENT || DEBUG */
4713 
4714 /*
4715  * Called during EXC_RESOURCE handling when a process exceeds a soft
4716  * memory limit.  This is the corpse fork path and here we decide if
4717  * vm_map_fork will be allowed when creating the corpse.
4718  * The task being considered is suspended.
4719  *
4720  * By default, a vm_map_fork is allowed to proceed.
4721  *
4722  * A few simple policy assumptions:
4723  *	If the device has a zero system-wide task limit,
4724  *	then the vm_map_fork is allowed. macOS always has a zero
4725  *	system wide task limit (unless overriden by a boot-arg).
4726  *
4727  *	And if a process's memory footprint calculates less
4728  *	than or equal to quarter of the system-wide task limit,
4729  *	then the vm_map_fork is allowed.  This calculation
4730  *	is based on the assumption that a process can
4731  *	munch memory up to the system-wide task limit.
4732  *
4733  *      For watchOS, which has a low task limit, we use a
4734  *      different value. Current task limit has been reduced
4735  *      to 300MB and it's been decided the limit should be 200MB.
4736  */
4737 int large_corpse_count = 0;
4738 boolean_t
memorystatus_allowed_vm_map_fork(task_t task,bool * is_large)4739 memorystatus_allowed_vm_map_fork(task_t task, bool *is_large)
4740 {
4741 	boolean_t is_allowed = TRUE;   /* default */
4742 	uint64_t footprint_in_bytes;
4743 	uint64_t max_allowed_bytes;
4744 	thread_t self = current_thread();
4745 
4746 	*is_large = false;
4747 
4748 	/* Jetsam in high bands blocks any new corpse */
4749 	if (os_atomic_load(&block_corpses, relaxed) != 0) {
4750 		memorystatus_log("memorystatus_allowed_vm_map_fork: corpse for pid %d blocked by jetsam).\n", task_pid(task));
4751 		ktriage_record(thread_tid(self), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_CORPSE, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_CORPSE_BLOCKED_JETSAM), 0 /* arg */);
4752 		return FALSE;
4753 	}
4754 
4755 	if (max_task_footprint_mb == 0) {
4756 		set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_ALLOWED);
4757 		return is_allowed;
4758 	}
4759 
4760 	footprint_in_bytes = get_task_phys_footprint(task);
4761 
4762 	/*
4763 	 * Maximum is 1/4 of the system-wide task limit by default.
4764 	 */
4765 	max_allowed_bytes = ((uint64_t)max_task_footprint_mb * 1024 * 1024) >> 2;
4766 
4767 #if XNU_TARGET_OS_WATCH
4768 	/*
4769 	 * For watches with > 1G, use a limit of 200MB and allow
4770 	 * one corpse at a time of up to 300MB.
4771 	 */
4772 #define LARGE_CORPSE_LIMIT 1
4773 	if (sane_size > 1 * 1024 * 1024 * 1024) {
4774 		int cnt = large_corpse_count;
4775 		if (footprint_in_bytes > 200 * 1024 * 1024 &&
4776 		    footprint_in_bytes <= 300 * 1024 * 1024 &&
4777 		    cnt < LARGE_CORPSE_LIMIT &&
4778 		    OSCompareAndSwap(cnt, cnt + 1, &large_corpse_count)) {
4779 			*is_large = true;
4780 			max_allowed_bytes = MAX(max_allowed_bytes, 300 * 1024 * 1024);
4781 		} else {
4782 			max_allowed_bytes = MAX(max_allowed_bytes, 200 * 1024 * 1024);
4783 		}
4784 	}
4785 #endif /* XNU_TARGET_OS_WATCH */
4786 
4787 #if DEBUG || DEVELOPMENT
4788 	if (corpse_threshold_system_limit) {
4789 		max_allowed_bytes = (uint64_t)max_task_footprint_mb * (1UL << 20);
4790 	}
4791 #endif /* DEBUG || DEVELOPMENT */
4792 
4793 	if (footprint_in_bytes > max_allowed_bytes) {
4794 		memorystatus_log("memorystatus disallowed vm_map_fork %lld  %lld\n", footprint_in_bytes, max_allowed_bytes);
4795 		set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED);
4796 		ktriage_record(thread_tid(self), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_CORPSE, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_CORPSE_PROC_TOO_BIG), 0 /* arg */);
4797 		return !is_allowed;
4798 	}
4799 
4800 	set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_ALLOWED);
4801 	return is_allowed;
4802 }
4803 
4804 void
memorystatus_get_task_page_counts(task_t task,uint32_t * footprint,uint32_t * max_footprint_lifetime,uint32_t * purgeable_pages)4805 memorystatus_get_task_page_counts(task_t task, uint32_t *footprint, uint32_t *max_footprint_lifetime, uint32_t *purgeable_pages)
4806 {
4807 	assert(task);
4808 	assert(footprint);
4809 
4810 	uint64_t pages;
4811 
4812 	pages = (get_task_phys_footprint(task) / PAGE_SIZE_64);
4813 	assert(((uint32_t)pages) == pages);
4814 	*footprint = (uint32_t)pages;
4815 
4816 	if (max_footprint_lifetime) {
4817 		pages = (get_task_phys_footprint_lifetime_max(task) / PAGE_SIZE_64);
4818 		assert(((uint32_t)pages) == pages);
4819 		*max_footprint_lifetime = (uint32_t)pages;
4820 	}
4821 	if (purgeable_pages) {
4822 		pages = (get_task_purgeable_size(task) / PAGE_SIZE_64);
4823 		assert(((uint32_t)pages) == pages);
4824 		*purgeable_pages = (uint32_t)pages;
4825 	}
4826 }
4827 
4828 static void
memorystatus_get_task_phys_footprint_page_counts(task_t task,uint64_t * internal_pages,uint64_t * internal_compressed_pages,uint64_t * purgeable_nonvolatile_pages,uint64_t * purgeable_nonvolatile_compressed_pages,uint64_t * alternate_accounting_pages,uint64_t * alternate_accounting_compressed_pages,uint64_t * iokit_mapped_pages,uint64_t * page_table_pages,uint64_t * frozen_to_swap_pages)4829 memorystatus_get_task_phys_footprint_page_counts(task_t task,
4830     uint64_t *internal_pages, uint64_t *internal_compressed_pages,
4831     uint64_t *purgeable_nonvolatile_pages, uint64_t *purgeable_nonvolatile_compressed_pages,
4832     uint64_t *alternate_accounting_pages, uint64_t *alternate_accounting_compressed_pages,
4833     uint64_t *iokit_mapped_pages, uint64_t *page_table_pages, uint64_t *frozen_to_swap_pages)
4834 {
4835 	assert(task);
4836 
4837 	if (internal_pages) {
4838 		*internal_pages = (get_task_internal(task) / PAGE_SIZE_64);
4839 	}
4840 
4841 	if (internal_compressed_pages) {
4842 		*internal_compressed_pages = (get_task_internal_compressed(task) / PAGE_SIZE_64);
4843 	}
4844 
4845 	if (purgeable_nonvolatile_pages) {
4846 		*purgeable_nonvolatile_pages = (get_task_purgeable_nonvolatile(task) / PAGE_SIZE_64);
4847 	}
4848 
4849 	if (purgeable_nonvolatile_compressed_pages) {
4850 		*purgeable_nonvolatile_compressed_pages = (get_task_purgeable_nonvolatile_compressed(task) / PAGE_SIZE_64);
4851 	}
4852 
4853 	if (alternate_accounting_pages) {
4854 		*alternate_accounting_pages = (get_task_alternate_accounting(task) / PAGE_SIZE_64);
4855 	}
4856 
4857 	if (alternate_accounting_compressed_pages) {
4858 		*alternate_accounting_compressed_pages = (get_task_alternate_accounting_compressed(task) / PAGE_SIZE_64);
4859 	}
4860 
4861 	if (iokit_mapped_pages) {
4862 		*iokit_mapped_pages = (get_task_iokit_mapped(task) / PAGE_SIZE_64);
4863 	}
4864 
4865 	if (page_table_pages) {
4866 		*page_table_pages = (get_task_page_table(task) / PAGE_SIZE_64);
4867 	}
4868 
4869 #if CONFIG_FREEZE
4870 	if (frozen_to_swap_pages) {
4871 		*frozen_to_swap_pages = (get_task_frozen_to_swap(task) / PAGE_SIZE_64);
4872 	}
4873 #else /* CONFIG_FREEZE */
4874 #pragma unused(frozen_to_swap_pages)
4875 #endif /* CONFIG_FREEZE */
4876 }
4877 
4878 #if CONFIG_FREEZE
4879 /*
4880  * Copies the source entry into the destination snapshot.
4881  * Returns true on success. Fails if the destination snapshot is full.
4882  * Caller must hold the proc list lock.
4883  */
4884 static bool
memorystatus_jetsam_snapshot_copy_entry_locked(memorystatus_jetsam_snapshot_t * dst_snapshot,unsigned int dst_snapshot_size,const memorystatus_jetsam_snapshot_entry_t * src_entry)4885 memorystatus_jetsam_snapshot_copy_entry_locked(memorystatus_jetsam_snapshot_t *dst_snapshot, unsigned int dst_snapshot_size, const memorystatus_jetsam_snapshot_entry_t *src_entry)
4886 {
4887 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
4888 	assert(dst_snapshot);
4889 
4890 	if (dst_snapshot->entry_count == dst_snapshot_size) {
4891 		/* Destination snapshot is full. Can not be updated until it is consumed. */
4892 		return false;
4893 	}
4894 	if (dst_snapshot->entry_count == 0) {
4895 		memorystatus_init_jetsam_snapshot_header(dst_snapshot);
4896 	}
4897 	memorystatus_jetsam_snapshot_entry_t *dst_entry = &dst_snapshot->entries[dst_snapshot->entry_count++];
4898 	memcpy(dst_entry, src_entry, sizeof(memorystatus_jetsam_snapshot_entry_t));
4899 	return true;
4900 }
4901 #endif /* CONFIG_FREEZE */
4902 
4903 static bool
memorystatus_init_jetsam_snapshot_entry_with_kill_locked(memorystatus_jetsam_snapshot_t * snapshot,proc_t p,uint32_t kill_cause,uint64_t killtime,memorystatus_jetsam_snapshot_entry_t ** entry)4904 memorystatus_init_jetsam_snapshot_entry_with_kill_locked(memorystatus_jetsam_snapshot_t *snapshot, proc_t p, uint32_t kill_cause, uint64_t killtime, memorystatus_jetsam_snapshot_entry_t **entry)
4905 {
4906 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
4907 	memorystatus_jetsam_snapshot_entry_t *snapshot_list = snapshot->entries;
4908 	size_t i = snapshot->entry_count;
4909 
4910 	if (memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[i], (snapshot->js_gencount)) == TRUE) {
4911 		*entry = &snapshot_list[i];
4912 		(*entry)->killed       = kill_cause;
4913 		(*entry)->jse_killtime = killtime;
4914 
4915 		snapshot->entry_count = i + 1;
4916 		return true;
4917 	}
4918 	return false;
4919 }
4920 
4921 /*
4922  * This routine only acts on the global jetsam event snapshot.
4923  * Updating the process's entry can race when the memorystatus_thread
4924  * has chosen to kill a process that is racing to exit on another core.
4925  */
4926 static void
memorystatus_update_jetsam_snapshot_entry_locked(proc_t p,uint32_t kill_cause,uint64_t killtime)4927 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p, uint32_t kill_cause, uint64_t killtime)
4928 {
4929 	memorystatus_jetsam_snapshot_entry_t *entry = NULL;
4930 	memorystatus_jetsam_snapshot_t *snapshot    = NULL;
4931 	memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
4932 
4933 	unsigned int i;
4934 #if CONFIG_FREEZE
4935 	bool copied_to_freezer_snapshot = false;
4936 #endif /* CONFIG_FREEZE */
4937 
4938 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
4939 
4940 	if (memorystatus_jetsam_snapshot_count == 0) {
4941 		/*
4942 		 * No active snapshot.
4943 		 * Nothing to do.
4944 		 */
4945 		goto exit;
4946 	}
4947 
4948 	/*
4949 	 * Sanity check as this routine should only be called
4950 	 * from a jetsam kill path.
4951 	 */
4952 	assert(kill_cause != 0 && killtime != 0);
4953 
4954 	snapshot       = memorystatus_jetsam_snapshot;
4955 	snapshot_list  = memorystatus_jetsam_snapshot->entries;
4956 
4957 	for (i = 0; i < memorystatus_jetsam_snapshot_count; i++) {
4958 		if (snapshot_list[i].pid == proc_getpid(p)) {
4959 			entry = &snapshot_list[i];
4960 
4961 			if (entry->killed || entry->jse_killtime) {
4962 				/*
4963 				 * We apparently raced on the exit path
4964 				 * for this process, as it's snapshot entry
4965 				 * has already recorded a kill.
4966 				 */
4967 				assert(entry->killed && entry->jse_killtime);
4968 				break;
4969 			}
4970 
4971 			/*
4972 			 * Update the entry we just found in the snapshot.
4973 			 */
4974 
4975 			entry->killed       = kill_cause;
4976 			entry->jse_killtime = killtime;
4977 			entry->jse_gencount = snapshot->js_gencount;
4978 			entry->jse_idle_delta = p->p_memstat_idle_delta;
4979 #if CONFIG_FREEZE
4980 			entry->jse_thaw_count = p->p_memstat_thaw_count;
4981 			entry->jse_freeze_skip_reason = p->p_memstat_freeze_skip_reason;
4982 #else /* CONFIG_FREEZE */
4983 			entry->jse_thaw_count = 0;
4984 			entry->jse_freeze_skip_reason = kMemorystatusFreezeSkipReasonNone;
4985 #endif /* CONFIG_FREEZE */
4986 
4987 			/*
4988 			 * If a process has moved between bands since snapshot was
4989 			 * initialized, then likely these fields changed too.
4990 			 */
4991 			if (entry->priority != p->p_memstat_effectivepriority) {
4992 				strlcpy(entry->name, p->p_name, sizeof(entry->name));
4993 				entry->priority  = p->p_memstat_effectivepriority;
4994 				entry->state     = memorystatus_build_state(p);
4995 				entry->user_data = p->p_memstat_userdata;
4996 				entry->fds       = p->p_fd.fd_nfiles;
4997 			}
4998 
4999 			/*
5000 			 * Always update the page counts on a kill.
5001 			 */
5002 
5003 			uint32_t pages              = 0;
5004 			uint32_t max_pages_lifetime = 0;
5005 			uint32_t purgeable_pages    = 0;
5006 
5007 			memorystatus_get_task_page_counts(proc_task(p), &pages, &max_pages_lifetime, &purgeable_pages);
5008 			entry->pages              = (uint64_t)pages;
5009 			entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
5010 			entry->purgeable_pages    = (uint64_t)purgeable_pages;
5011 
5012 			uint64_t internal_pages                        = 0;
5013 			uint64_t internal_compressed_pages             = 0;
5014 			uint64_t purgeable_nonvolatile_pages           = 0;
5015 			uint64_t purgeable_nonvolatile_compressed_pages = 0;
5016 			uint64_t alternate_accounting_pages            = 0;
5017 			uint64_t alternate_accounting_compressed_pages = 0;
5018 			uint64_t iokit_mapped_pages                    = 0;
5019 			uint64_t page_table_pages                      = 0;
5020 			uint64_t frozen_to_swap_pages                  = 0;
5021 
5022 			memorystatus_get_task_phys_footprint_page_counts(proc_task(p), &internal_pages, &internal_compressed_pages,
5023 			    &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
5024 			    &alternate_accounting_pages, &alternate_accounting_compressed_pages,
5025 			    &iokit_mapped_pages, &page_table_pages, &frozen_to_swap_pages);
5026 
5027 			entry->jse_internal_pages = internal_pages;
5028 			entry->jse_internal_compressed_pages = internal_compressed_pages;
5029 			entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
5030 			entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
5031 			entry->jse_alternate_accounting_pages = alternate_accounting_pages;
5032 			entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
5033 			entry->jse_iokit_mapped_pages = iokit_mapped_pages;
5034 			entry->jse_page_table_pages = page_table_pages;
5035 			entry->jse_frozen_to_swap_pages = frozen_to_swap_pages;
5036 
5037 			uint64_t region_count = 0;
5038 			memorystatus_get_task_memory_region_count(proc_task(p), &region_count);
5039 			entry->jse_memory_region_count = region_count;
5040 			entry->csflags = proc_getcsflags(p);
5041 			goto exit;
5042 		}
5043 	}
5044 
5045 	if (entry == NULL) {
5046 		/*
5047 		 * The entry was not found in the snapshot, so the process must have
5048 		 * launched after the snapshot was initialized.
5049 		 * Let's try to append the new entry.
5050 		 */
5051 		if (memorystatus_jetsam_snapshot_count < memorystatus_jetsam_snapshot_max) {
5052 			/*
5053 			 * A populated snapshot buffer exists
5054 			 * and there is room to init a new entry.
5055 			 */
5056 			assert(memorystatus_jetsam_snapshot_count == snapshot->entry_count);
5057 
5058 			if (memorystatus_init_jetsam_snapshot_entry_with_kill_locked(snapshot, p, kill_cause, killtime, &entry)) {
5059 				memorystatus_jetsam_snapshot_count++;
5060 
5061 				if (memorystatus_jetsam_snapshot_count >= memorystatus_jetsam_snapshot_max) {
5062 					/*
5063 					 * We just used the last slot in the snapshot buffer.
5064 					 * We only want to log it once... so we do it here
5065 					 * when we notice we've hit the max.
5066 					 */
5067 					memorystatus_log_error("memorystatus: WARNING snapshot buffer is full, count %d\n", memorystatus_jetsam_snapshot_count);
5068 				}
5069 			}
5070 		}
5071 	}
5072 
5073 exit:
5074 	if (entry) {
5075 #if CONFIG_FREEZE
5076 		if (memorystatus_jetsam_use_freezer_snapshot && isApp(p)) {
5077 			/* This is an app kill. Record it in the freezer snapshot so dasd can incorporate this in its recommendations. */
5078 			copied_to_freezer_snapshot = memorystatus_jetsam_snapshot_copy_entry_locked(memorystatus_jetsam_snapshot_freezer, memorystatus_jetsam_snapshot_freezer_max, entry);
5079 			if (copied_to_freezer_snapshot && memorystatus_jetsam_snapshot_freezer->entry_count == memorystatus_jetsam_snapshot_freezer_max) {
5080 				/*
5081 				 * We just used the last slot in the freezer snapshot buffer.
5082 				 * We only want to log it once... so we do it here
5083 				 * when we notice we've hit the max.
5084 				 */
5085 				memorystatus_log_error("memorystatus: WARNING freezer snapshot buffer is full, count %zu\n",
5086 				    memorystatus_jetsam_snapshot_freezer->entry_count);
5087 			}
5088 		}
5089 #endif /* CONFIG_FREEZE */
5090 	} else {
5091 		/*
5092 		 * If we reach here, the snapshot buffer could not be updated.
5093 		 * Most likely, the buffer is full, in which case we would have
5094 		 * logged a warning in the previous call.
5095 		 *
5096 		 * For now, we will stop appending snapshot entries.
5097 		 * When the buffer is consumed, the snapshot state will reset.
5098 		 */
5099 
5100 		memorystatus_log_error(
5101 			"memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
5102 			proc_getpid(p), p->p_memstat_effectivepriority, memorystatus_jetsam_snapshot_count);
5103 
5104 #if CONFIG_FREEZE
5105 		/* We still attempt to record this in the freezer snapshot */
5106 		if (memorystatus_jetsam_use_freezer_snapshot && isApp(p)) {
5107 			snapshot = memorystatus_jetsam_snapshot_freezer;
5108 			if (snapshot->entry_count < memorystatus_jetsam_snapshot_freezer_max) {
5109 				copied_to_freezer_snapshot = memorystatus_init_jetsam_snapshot_entry_with_kill_locked(snapshot, p, kill_cause, killtime, &entry);
5110 				if (copied_to_freezer_snapshot && memorystatus_jetsam_snapshot_freezer->entry_count == memorystatus_jetsam_snapshot_freezer_max) {
5111 					/*
5112 					 * We just used the last slot in the freezer snapshot buffer.
5113 					 * We only want to log it once... so we do it here
5114 					 * when we notice we've hit the max.
5115 					 */
5116 					memorystatus_log_error("memorystatus: WARNING freezer snapshot buffer is full, count %zu\n",
5117 					    memorystatus_jetsam_snapshot_freezer->entry_count);
5118 				}
5119 			}
5120 		}
5121 #endif /* CONFIG_FREEZE */
5122 	}
5123 
5124 	return;
5125 }
5126 
5127 #if CONFIG_JETSAM
5128 
5129 void
memorystatus_pages_update(unsigned int pages_avail)5130 memorystatus_pages_update(unsigned int pages_avail)
5131 {
5132 	memorystatus_available_pages = pages_avail;
5133 
5134 #if VM_PRESSURE_EVENTS
5135 	/*
5136 	 * Since memorystatus_available_pages changes, we should
5137 	 * re-evaluate the pressure levels on the system and
5138 	 * check if we need to wake the pressure thread.
5139 	 * We also update memorystatus_level in that routine.
5140 	 */
5141 	vm_pressure_response();
5142 
5143 	if (memorystatus_available_pages <= memorystatus_available_pages_pressure) {
5144 		if (memorystatus_hwm_candidates || (memorystatus_available_pages <= memorystatus_available_pages_critical)) {
5145 			memorystatus_thread_wake();
5146 		}
5147 	}
5148 #if CONFIG_FREEZE
5149 	/*
5150 	 * We can't grab the freezer_mutex here even though that synchronization would be correct to inspect
5151 	 * the # of frozen processes and wakeup the freezer thread. Reason being that we come here into this
5152 	 * code with (possibly) the page-queue locks held and preemption disabled. So trying to grab a mutex here
5153 	 * will result in the "mutex with preemption disabled" panic.
5154 	 */
5155 
5156 	if (memorystatus_freeze_thread_should_run()) {
5157 		/*
5158 		 * The freezer thread is usually woken up by some user-space call i.e. pid_hibernate(any process).
5159 		 * That trigger isn't invoked often enough and so we are enabling this explicit wakeup here.
5160 		 */
5161 		if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5162 			thread_wakeup((event_t)&memorystatus_freeze_wakeup);
5163 		}
5164 	}
5165 #endif /* CONFIG_FREEZE */
5166 
5167 #else /* VM_PRESSURE_EVENTS */
5168 
5169 	boolean_t critical, delta;
5170 
5171 	if (!memorystatus_delta) {
5172 		return;
5173 	}
5174 
5175 	critical = (pages_avail < memorystatus_available_pages_critical) ? TRUE : FALSE;
5176 	delta = ((pages_avail >= (memorystatus_available_pages + memorystatus_delta))
5177 	    || (memorystatus_available_pages >= (pages_avail + memorystatus_delta))) ? TRUE : FALSE;
5178 
5179 	if (critical || delta) {
5180 		unsigned int total_pages;
5181 
5182 		total_pages = (unsigned int) atop_64(max_mem);
5183 #if CONFIG_SECLUDED_MEMORY
5184 		total_pages -= vm_page_secluded_count;
5185 #endif /* CONFIG_SECLUDED_MEMORY */
5186 		memorystatus_level = memorystatus_available_pages * 100 / total_pages;
5187 		memorystatus_thread_wake();
5188 	}
5189 #endif /* VM_PRESSURE_EVENTS */
5190 }
5191 #endif /* CONFIG_JETSAM */
5192 
5193 static boolean_t
memorystatus_init_jetsam_snapshot_entry_locked(proc_t p,memorystatus_jetsam_snapshot_entry_t * entry,uint64_t gencount)5194 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p, memorystatus_jetsam_snapshot_entry_t *entry, uint64_t gencount)
5195 {
5196 	clock_sec_t                     tv_sec;
5197 	clock_usec_t                    tv_usec;
5198 	uint32_t pages = 0;
5199 	uint32_t max_pages_lifetime = 0;
5200 	uint32_t purgeable_pages = 0;
5201 	uint64_t internal_pages                         = 0;
5202 	uint64_t internal_compressed_pages              = 0;
5203 	uint64_t purgeable_nonvolatile_pages            = 0;
5204 	uint64_t purgeable_nonvolatile_compressed_pages = 0;
5205 	uint64_t alternate_accounting_pages             = 0;
5206 	uint64_t alternate_accounting_compressed_pages  = 0;
5207 	uint64_t iokit_mapped_pages                     = 0;
5208 	uint64_t page_table_pages                       = 0;
5209 	uint64_t frozen_to_swap_pages                   = 0;
5210 	uint64_t region_count                           = 0;
5211 	uint64_t cids[COALITION_NUM_TYPES];
5212 	uint32_t trust                                  = 0;
5213 	kern_return_t ret                               = 0;
5214 	memset(entry, 0, sizeof(memorystatus_jetsam_snapshot_entry_t));
5215 
5216 	entry->pid = proc_getpid(p);
5217 	strlcpy(&entry->name[0], p->p_name, sizeof(entry->name));
5218 	entry->priority = p->p_memstat_effectivepriority;
5219 
5220 	memorystatus_get_task_page_counts(proc_task(p), &pages, &max_pages_lifetime, &purgeable_pages);
5221 	entry->pages              = (uint64_t)pages;
5222 	entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
5223 	entry->purgeable_pages    = (uint64_t)purgeable_pages;
5224 
5225 	memorystatus_get_task_phys_footprint_page_counts(proc_task(p), &internal_pages, &internal_compressed_pages,
5226 	    &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
5227 	    &alternate_accounting_pages, &alternate_accounting_compressed_pages,
5228 	    &iokit_mapped_pages, &page_table_pages, &frozen_to_swap_pages);
5229 
5230 	entry->jse_internal_pages = internal_pages;
5231 	entry->jse_internal_compressed_pages = internal_compressed_pages;
5232 	entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
5233 	entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
5234 	entry->jse_alternate_accounting_pages = alternate_accounting_pages;
5235 	entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
5236 	entry->jse_iokit_mapped_pages = iokit_mapped_pages;
5237 	entry->jse_page_table_pages = page_table_pages;
5238 	entry->jse_frozen_to_swap_pages = frozen_to_swap_pages;
5239 
5240 	memorystatus_get_task_memory_region_count(proc_task(p), &region_count);
5241 	entry->jse_memory_region_count = region_count;
5242 
5243 	entry->state     = memorystatus_build_state(p);
5244 	entry->user_data = p->p_memstat_userdata;
5245 	proc_getexecutableuuid(p, &entry->uuid[0], sizeof(entry->uuid));
5246 	entry->fds       = p->p_fd.fd_nfiles;
5247 
5248 	absolutetime_to_microtime(get_task_cpu_time(proc_task(p)), &tv_sec, &tv_usec);
5249 	entry->cpu_time.tv_sec = (int64_t)tv_sec;
5250 	entry->cpu_time.tv_usec = (int64_t)tv_usec;
5251 
5252 	assert(p->p_stats != NULL);
5253 	entry->jse_starttime =  p->p_stats->ps_start;   /* abstime process started */
5254 	entry->jse_killtime = 0;                        /* abstime jetsam chose to kill process */
5255 	entry->killed       = 0;                        /* the jetsam kill cause */
5256 	entry->jse_gencount = gencount;                 /* indicates a pass through jetsam thread, when process was targeted to be killed */
5257 
5258 	entry->jse_idle_delta = p->p_memstat_idle_delta; /* Most recent timespan spent in idle-band */
5259 
5260 #if CONFIG_FREEZE
5261 	entry->jse_freeze_skip_reason = p->p_memstat_freeze_skip_reason;
5262 	entry->jse_thaw_count = p->p_memstat_thaw_count;
5263 #else /* CONFIG_FREEZE */
5264 	entry->jse_thaw_count = 0;
5265 	entry->jse_freeze_skip_reason = kMemorystatusFreezeSkipReasonNone;
5266 #endif /* CONFIG_FREEZE */
5267 
5268 	proc_coalitionids(p, cids);
5269 	entry->jse_coalition_jetsam_id = cids[COALITION_TYPE_JETSAM];
5270 	entry->csflags = proc_getcsflags(p);
5271 	ret = get_trust_level_kdp(get_task_pmap(proc_task(p)), &trust);
5272 	if (ret != KERN_SUCCESS) {
5273 		trust = KCDATA_INVALID_CS_TRUST_LEVEL;
5274 	}
5275 	entry->cs_trust_level = trust;
5276 	return TRUE;
5277 }
5278 
5279 static void
memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t * snapshot)5280 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t *snapshot)
5281 {
5282 	kern_return_t kr = KERN_SUCCESS;
5283 	mach_msg_type_number_t  count = HOST_VM_INFO64_COUNT;
5284 	vm_statistics64_data_t  vm_stat;
5285 
5286 	if ((kr = host_statistics64(host_self(), HOST_VM_INFO64, (host_info64_t)&vm_stat, &count)) != KERN_SUCCESS) {
5287 		memorystatus_log_error("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr);
5288 		memset(&snapshot->stats, 0, sizeof(snapshot->stats));
5289 	} else {
5290 		snapshot->stats.free_pages      = vm_stat.free_count;
5291 		snapshot->stats.active_pages    = vm_stat.active_count;
5292 		snapshot->stats.inactive_pages  = vm_stat.inactive_count;
5293 		snapshot->stats.throttled_pages = vm_stat.throttled_count;
5294 		snapshot->stats.purgeable_pages = vm_stat.purgeable_count;
5295 		snapshot->stats.wired_pages     = vm_stat.wire_count;
5296 
5297 		snapshot->stats.speculative_pages = vm_stat.speculative_count;
5298 		snapshot->stats.filebacked_pages  = vm_stat.external_page_count;
5299 		snapshot->stats.anonymous_pages   = vm_stat.internal_page_count;
5300 		snapshot->stats.compressions      = vm_stat.compressions;
5301 		snapshot->stats.decompressions    = vm_stat.decompressions;
5302 		snapshot->stats.compressor_pages  = vm_stat.compressor_page_count;
5303 		snapshot->stats.total_uncompressed_pages_in_compressor = vm_stat.total_uncompressed_pages_in_compressor;
5304 	}
5305 
5306 	get_zone_map_size(&snapshot->stats.zone_map_size, &snapshot->stats.zone_map_capacity);
5307 
5308 	bzero(snapshot->stats.largest_zone_name, sizeof(snapshot->stats.largest_zone_name));
5309 	get_largest_zone_info(snapshot->stats.largest_zone_name, sizeof(snapshot->stats.largest_zone_name),
5310 	    &snapshot->stats.largest_zone_size);
5311 }
5312 
5313 /*
5314  * Collect vm statistics at boot.
5315  * Called only once (see kern_exec.c)
5316  * Data can be consumed at any time.
5317  */
5318 void
memorystatus_init_at_boot_snapshot()5319 memorystatus_init_at_boot_snapshot()
5320 {
5321 	memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot);
5322 	memorystatus_at_boot_snapshot.entry_count = 0;
5323 	memorystatus_at_boot_snapshot.notification_time = 0;   /* updated when consumed */
5324 	memorystatus_at_boot_snapshot.snapshot_time = mach_absolute_time();
5325 }
5326 
5327 static void
memorystatus_init_jetsam_snapshot_header(memorystatus_jetsam_snapshot_t * snapshot)5328 memorystatus_init_jetsam_snapshot_header(memorystatus_jetsam_snapshot_t *snapshot)
5329 {
5330 	memorystatus_init_snapshot_vmstats(snapshot);
5331 	snapshot->snapshot_time = mach_absolute_time();
5332 	snapshot->notification_time = 0;
5333 	snapshot->js_gencount = 0;
5334 }
5335 
5336 static void
memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t * od_snapshot,uint32_t ods_list_count)5337 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t *od_snapshot, uint32_t ods_list_count )
5338 {
5339 	proc_t p, next_p;
5340 	unsigned int b = 0, i = 0;
5341 
5342 	memorystatus_jetsam_snapshot_t *snapshot = NULL;
5343 	memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
5344 	unsigned int snapshot_max = 0;
5345 
5346 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
5347 
5348 	if (od_snapshot) {
5349 		/*
5350 		 * This is an on_demand snapshot
5351 		 */
5352 		snapshot      = od_snapshot;
5353 		snapshot_list = od_snapshot->entries;
5354 		snapshot_max  = ods_list_count;
5355 	} else {
5356 		/*
5357 		 * This is a jetsam event snapshot
5358 		 */
5359 		snapshot      = memorystatus_jetsam_snapshot;
5360 		snapshot_list = memorystatus_jetsam_snapshot->entries;
5361 		snapshot_max  = memorystatus_jetsam_snapshot_max;
5362 	}
5363 
5364 	memorystatus_init_jetsam_snapshot_header(snapshot);
5365 
5366 	next_p = memorystatus_get_first_proc_locked(&b, TRUE);
5367 	while (next_p) {
5368 		p = next_p;
5369 		next_p = memorystatus_get_next_proc_locked(&b, p, TRUE);
5370 
5371 		if (FALSE == memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[i], snapshot->js_gencount)) {
5372 			continue;
5373 		}
5374 
5375 		if (++i == snapshot_max) {
5376 			break;
5377 		}
5378 	}
5379 
5380 	snapshot->entry_count = i;
5381 
5382 	if (!od_snapshot) {
5383 		/* update the system buffer count */
5384 		memorystatus_jetsam_snapshot_count = i;
5385 	}
5386 }
5387 
5388 #if DEVELOPMENT || DEBUG
5389 
5390 /*
5391  * Verify that the given bucket has been sorted correctly.
5392  *
5393  * Walks through the bucket and verifies that all pids in the
5394  * expected_order buffer are in that bucket and in the same
5395  * relative order.
5396  *
5397  * The proc_list_lock must be held by the caller.
5398  */
5399 static int
memorystatus_verify_sort_order(unsigned int bucket_index,pid_t * expected_order,size_t num_pids)5400 memorystatus_verify_sort_order(unsigned int bucket_index, pid_t *expected_order, size_t num_pids)
5401 {
5402 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
5403 
5404 	int error = 0;
5405 	proc_t p = NULL;
5406 	size_t i = 0;
5407 
5408 	/*
5409 	 * NB: We allow other procs to be mixed in within the expected ones.
5410 	 * We just need the expected procs to be in the right order relative to each other.
5411 	 */
5412 	p = memorystatus_get_first_proc_locked(&bucket_index, FALSE);
5413 	while (p) {
5414 		if (proc_getpid(p) == expected_order[i]) {
5415 			i++;
5416 		}
5417 		if (i == num_pids) {
5418 			break;
5419 		}
5420 		p = memorystatus_get_next_proc_locked(&bucket_index, p, FALSE);
5421 	}
5422 	if (i != num_pids) {
5423 		char buffer[128];
5424 		size_t len = sizeof(buffer);
5425 		size_t buffer_idx = 0;
5426 		memorystatus_log_error("memorystatus_verify_sort_order: Processes in bucket %d were not sorted properly\n", bucket_index);
5427 		for (i = 0; i < num_pids; i++) {
5428 			int num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%d,", expected_order[i]);
5429 			if (num_written <= 0) {
5430 				break;
5431 			}
5432 			if (buffer_idx + (unsigned int) num_written >= len) {
5433 				break;
5434 			}
5435 			buffer_idx += num_written;
5436 		}
5437 		memorystatus_log_error("memorystatus_verify_sort_order: Expected order [%s]\n", buffer);
5438 		memset(buffer, 0, len);
5439 		buffer_idx = 0;
5440 		p = memorystatus_get_first_proc_locked(&bucket_index, FALSE);
5441 		i = 0;
5442 		memorystatus_log_error("memorystatus_verify_sort_order: Actual order:\n");
5443 		while (p) {
5444 			int num_written;
5445 			if (buffer_idx == 0) {
5446 				num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%zu: %d,", i, proc_getpid(p));
5447 			} else {
5448 				num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%d,", proc_getpid(p));
5449 			}
5450 			if (num_written <= 0) {
5451 				break;
5452 			}
5453 			buffer_idx += (unsigned int) num_written;
5454 			assert(buffer_idx <= len);
5455 			if (i % 10 == 0) {
5456 				memorystatus_log_error("memorystatus_verify_sort_order: %s\n", buffer);
5457 				buffer_idx = 0;
5458 			}
5459 			p = memorystatus_get_next_proc_locked(&bucket_index, p, FALSE);
5460 			i++;
5461 		}
5462 		if (buffer_idx != 0) {
5463 			memorystatus_log_error("memorystatus_verify_sort_order: %s\n", buffer);
5464 		}
5465 		error = EINVAL;
5466 	}
5467 	return error;
5468 }
5469 
5470 /*
5471  * Triggers a sort_order on a specified jetsam priority band.
5472  * This is for testing only, used to force a path through the sort
5473  * function.
5474  */
5475 static int
memorystatus_cmd_test_jetsam_sort(int priority,int sort_order,user_addr_t expected_order_user,size_t expected_order_user_len)5476 memorystatus_cmd_test_jetsam_sort(int priority,
5477     int sort_order,
5478     user_addr_t expected_order_user,
5479     size_t expected_order_user_len)
5480 {
5481 	int error = 0;
5482 	unsigned int bucket_index = 0;
5483 	static size_t kMaxPids = 8;
5484 	pid_t expected_order[kMaxPids];
5485 	size_t copy_size = sizeof(expected_order);
5486 	size_t num_pids;
5487 
5488 	if (expected_order_user_len < copy_size) {
5489 		copy_size = expected_order_user_len;
5490 	}
5491 	num_pids = copy_size / sizeof(pid_t);
5492 
5493 	error = copyin(expected_order_user, expected_order, copy_size);
5494 	if (error != 0) {
5495 		return error;
5496 	}
5497 
5498 	if (priority == -1) {
5499 		/* Use as shorthand for default priority */
5500 		bucket_index = JETSAM_PRIORITY_DEFAULT;
5501 	} else {
5502 		bucket_index = (unsigned int)priority;
5503 	}
5504 
5505 	/*
5506 	 * Acquire lock before sorting so we can check the sort order
5507 	 * while still holding the lock.
5508 	 */
5509 	proc_list_lock();
5510 
5511 	memorystatus_sort_bucket_locked(bucket_index, sort_order);
5512 
5513 	if (expected_order_user != CAST_USER_ADDR_T(NULL) && expected_order_user_len > 0) {
5514 		error = memorystatus_verify_sort_order(bucket_index, expected_order, num_pids);
5515 	}
5516 
5517 	proc_list_unlock();
5518 
5519 	return error;
5520 }
5521 
5522 #endif /* DEVELOPMENT || DEBUG */
5523 
5524 /*
5525  * Prepare the process to be killed (set state, update snapshot) and kill it.
5526  */
5527 static uint64_t memorystatus_purge_before_jetsam_success = 0;
5528 
5529 static boolean_t
memorystatus_kill_proc(proc_t p,uint32_t cause,os_reason_t jetsam_reason,bool * killed,uint64_t * footprint_of_killed_proc)5530 memorystatus_kill_proc(proc_t p, uint32_t cause, os_reason_t jetsam_reason, bool *killed, uint64_t *footprint_of_killed_proc)
5531 {
5532 	pid_t aPid = 0;
5533 	uint32_t aPid_ep = 0;
5534 
5535 	uint64_t        killtime = 0;
5536 	clock_sec_t     tv_sec;
5537 	clock_usec_t    tv_usec;
5538 	uint32_t        tv_msec;
5539 	boolean_t       retval = FALSE;
5540 
5541 	aPid = proc_getpid(p);
5542 	aPid_ep = p->p_memstat_effectivepriority;
5543 
5544 	if (cause != kMemorystatusKilledVnodes && cause != kMemorystatusKilledZoneMapExhaustion) {
5545 		/*
5546 		 * Genuine memory pressure and not other (vnode/zone) resource exhaustion.
5547 		 */
5548 		boolean_t success = FALSE;
5549 		uint64_t num_pages_purged;
5550 		uint64_t num_pages_reclaimed = 0;
5551 		uint64_t num_pages_unsecluded = 0;
5552 
5553 		networking_memstatus_callout(p, cause);
5554 		num_pages_purged = vm_purgeable_purge_task_owned(proc_task(p));
5555 		num_pages_reclaimed += num_pages_purged;
5556 #if CONFIG_SECLUDED_MEMORY
5557 		if (cause == kMemorystatusKilledVMPageShortage &&
5558 		    vm_page_secluded_count > 0 &&
5559 		    task_can_use_secluded_mem(proc_task(p), FALSE)) {
5560 			/*
5561 			 * We're about to kill a process that has access
5562 			 * to the secluded pool.  Drain that pool into the
5563 			 * free or active queues to make these pages re-appear
5564 			 * as "available", which might make us no longer need
5565 			 * to kill that process.
5566 			 * Since the secluded pool does not get refilled while
5567 			 * a process has access to it, it should remain
5568 			 * drained.
5569 			 */
5570 			num_pages_unsecluded = vm_page_secluded_drain();
5571 			num_pages_reclaimed += num_pages_unsecluded;
5572 		}
5573 #endif /* CONFIG_SECLUDED_MEMORY */
5574 
5575 		if (num_pages_reclaimed) {
5576 			/*
5577 			 * We actually reclaimed something and so let's
5578 			 * check if we need to continue with the kill.
5579 			 */
5580 			if (cause == kMemorystatusKilledHiwat) {
5581 				uint64_t footprint_in_bytes = get_task_phys_footprint(proc_task(p));
5582 				uint64_t memlimit_in_bytes  = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL);  /* convert MB to bytes */
5583 				success = (footprint_in_bytes <= memlimit_in_bytes);
5584 			} else {
5585 				success = !memorystatus_avail_pages_below_pressure();
5586 #if CONFIG_SECLUDED_MEMORY
5587 				if (!success && num_pages_unsecluded) {
5588 					/*
5589 					 * We just drained the secluded pool
5590 					 * because we're about to kill a
5591 					 * process that has access to it.
5592 					 * This is an important process and
5593 					 * we'd rather not kill it unless
5594 					 * absolutely necessary, so declare
5595 					 * success even if draining the pool
5596 					 * did not quite get us out of the
5597 					 * "pressure" level but still got
5598 					 * us out of the "critical" level.
5599 					 */
5600 					success = !memorystatus_avail_pages_below_critical();
5601 				}
5602 #endif /* CONFIG_SECLUDED_MEMORY */
5603 			}
5604 
5605 			if (success) {
5606 				memorystatus_purge_before_jetsam_success++;
5607 
5608 				memorystatus_log_info("memorystatus: reclaimed %llu pages (%llu purged, %llu unsecluded) from pid %d [%s] and avoided %s\n",
5609 				    num_pages_reclaimed, num_pages_purged, num_pages_unsecluded, aPid, ((p && *p->p_name) ? p->p_name : "unknown"), memorystatus_kill_cause_name[cause]);
5610 
5611 				*killed = false;
5612 				*footprint_of_killed_proc = num_pages_reclaimed + num_pages_purged + num_pages_unsecluded;
5613 
5614 				return TRUE;
5615 			}
5616 		}
5617 	}
5618 
5619 	killtime = mach_absolute_time();
5620 	absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
5621 	tv_msec = tv_usec / 1000;
5622 
5623 	proc_list_lock();
5624 	memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
5625 	proc_list_unlock();
5626 
5627 	char kill_reason_string[128];
5628 
5629 	if (cause == kMemorystatusKilledHiwat) {
5630 		strlcpy(kill_reason_string, "killing_highwater_process", 128);
5631 	} else {
5632 		if (aPid_ep == JETSAM_PRIORITY_IDLE) {
5633 			strlcpy(kill_reason_string, "killing_idle_process", 128);
5634 		} else {
5635 			strlcpy(kill_reason_string, "killing_top_process", 128);
5636 		}
5637 	}
5638 
5639 	/*
5640 	 * memorystatus_do_kill drops a reference, so take another one so we can
5641 	 * continue to use this exit reason even after memorystatus_do_kill()
5642 	 * returns
5643 	 */
5644 	os_reason_ref(jetsam_reason);
5645 
5646 	retval = memorystatus_do_kill(p, cause, jetsam_reason, footprint_of_killed_proc);
5647 	*killed = retval;
5648 
5649 	memorystatus_log("%lu.%03d memorystatus: %s pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu compressor_size:%u\n",
5650 	    (unsigned long)tv_sec, tv_msec, kill_reason_string,
5651 	    aPid, ((p && *p->p_name) ? p->p_name : "unknown"),
5652 	    memorystatus_kill_cause_name[cause], aPid_ep,
5653 	    (*footprint_of_killed_proc) >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, vm_compressor_pool_size());
5654 
5655 	return retval;
5656 }
5657 
5658 /*
5659  * Jetsam the first process in the queue.
5660  */
5661 static bool
memorystatus_kill_top_process(bool any,bool sort_flag,uint32_t cause,os_reason_t jetsam_reason,int32_t max_priority,bool only_swappable,int32_t * priority,uint32_t * errors,uint64_t * memory_reclaimed)5662 memorystatus_kill_top_process(bool any, bool sort_flag, uint32_t cause, os_reason_t jetsam_reason,
5663     int32_t max_priority, bool only_swappable,
5664     int32_t *priority, uint32_t *errors, uint64_t *memory_reclaimed)
5665 {
5666 	pid_t aPid;
5667 	proc_t p = PROC_NULL, next_p = PROC_NULL;
5668 	bool new_snapshot = false, force_new_snapshot = false, killed = false, freed_mem = false;
5669 	unsigned int i = 0;
5670 	uint32_t aPid_ep;
5671 	int32_t local_max_kill_prio = JETSAM_PRIORITY_IDLE;
5672 	uint64_t footprint_of_killed_proc = 0;
5673 
5674 #ifndef CONFIG_FREEZE
5675 #pragma unused(any)
5676 #endif
5677 
5678 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
5679 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES);
5680 
5681 
5682 #if CONFIG_JETSAM
5683 	if (sort_flag) {
5684 		(void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
5685 	}
5686 
5687 	*memory_reclaimed = 0;
5688 	local_max_kill_prio = MIN(max_kill_priority, max_priority);
5689 
5690 #if VM_PRESSURE_EVENTS
5691 	if (cause == kMemorystatusKilledSustainedPressure) {
5692 		local_max_kill_prio = memorystatus_sustained_pressure_maximum_band;
5693 	}
5694 #endif /* VM_PRESSURE_EVENTS */
5695 
5696 	force_new_snapshot = false;
5697 
5698 #else /* CONFIG_JETSAM */
5699 	(void) max_priority;
5700 
5701 	if (sort_flag) {
5702 		(void)memorystatus_sort_bucket(JETSAM_PRIORITY_IDLE, JETSAM_SORT_DEFAULT);
5703 	}
5704 
5705 	/*
5706 	 * On macos, we currently only have 2 reasons to be here:
5707 	 *
5708 	 * kMemorystatusKilledZoneMapExhaustion
5709 	 * AND
5710 	 * kMemorystatusKilledVMCompressorSpaceShortage
5711 	 *
5712 	 * If we are here because of kMemorystatusKilledZoneMapExhaustion, we will consider
5713 	 * any and all processes as eligible kill candidates since we need to avoid a panic.
5714 	 *
5715 	 * Since this function can be called async. it is harder to toggle the max_kill_priority
5716 	 * value before and after a call. And so we use this local variable to set the upper band
5717 	 * on the eligible kill bands.
5718 	 */
5719 	if (cause == kMemorystatusKilledZoneMapExhaustion) {
5720 		local_max_kill_prio = JETSAM_PRIORITY_MAX;
5721 	} else {
5722 		local_max_kill_prio = max_kill_priority;
5723 	}
5724 
5725 	/*
5726 	 * And, because we are here under extreme circumstances, we force a snapshot even for
5727 	 * IDLE kills.
5728 	 */
5729 	force_new_snapshot = true;
5730 
5731 #endif /* CONFIG_JETSAM */
5732 
5733 	if (cause != kMemorystatusKilledZoneMapExhaustion &&
5734 	    jetsam_current_thread() != NULL &&
5735 	    jetsam_current_thread()->limit_to_low_bands &&
5736 	    local_max_kill_prio > JETSAM_PRIORITY_MAIL) {
5737 		local_max_kill_prio = JETSAM_PRIORITY_MAIL;
5738 	}
5739 
5740 	proc_list_lock();
5741 
5742 	next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5743 	while (next_p && (next_p->p_memstat_effectivepriority <= local_max_kill_prio)) {
5744 		p = next_p;
5745 		next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
5746 
5747 
5748 		aPid = proc_getpid(p);
5749 		aPid_ep = p->p_memstat_effectivepriority;
5750 
5751 		if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP)) {
5752 			continue;   /* with lock held */
5753 		}
5754 
5755 		if (cause == kMemorystatusKilledVnodes) {
5756 			/*
5757 			 * If the system runs out of vnodes, we systematically jetsam
5758 			 * processes in hopes of stumbling onto a vnode gain that helps
5759 			 * the system recover.  The process that happens to trigger
5760 			 * this path has no known relationship to the vnode shortage.
5761 			 * Deadlock avoidance: attempt to safeguard the caller.
5762 			 */
5763 
5764 			if (p == current_proc()) {
5765 				/* do not jetsam the current process */
5766 				continue;
5767 			}
5768 		}
5769 
5770 		if (only_swappable && !task_donates_own_pages(proc_task(p))) {
5771 			continue;
5772 		}
5773 
5774 #if CONFIG_FREEZE
5775 		boolean_t skip;
5776 		boolean_t reclaim_proc = !(p->p_memstat_state & P_MEMSTAT_LOCKED);
5777 		if (any || reclaim_proc) {
5778 			skip = FALSE;
5779 		} else {
5780 			skip = TRUE;
5781 		}
5782 
5783 		if (skip) {
5784 			continue;
5785 		} else
5786 #endif
5787 		{
5788 			if (proc_ref(p, true) == p) {
5789 				/*
5790 				 * Mark as terminated so that if exit1() indicates success, but the process (for example)
5791 				 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
5792 				 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
5793 				 * acquisition of the proc lock.
5794 				 */
5795 				p->p_memstat_state |= P_MEMSTAT_TERMINATED;
5796 			} else {
5797 				/*
5798 				 * We need to restart the search again because
5799 				 * proc_ref _can_ drop the proc_list lock
5800 				 * and we could have lost our stored next_p via
5801 				 * an exit() on another core.
5802 				 */
5803 				i = 0;
5804 				next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5805 				continue;
5806 			}
5807 
5808 			/*
5809 			 * Capture a snapshot if none exists and:
5810 			 * - we are forcing a new snapshot creation, either because:
5811 			 *      - on a particular platform we need these snapshots every time, OR
5812 			 *	- a boot-arg/embedded device tree property has been set.
5813 			 * - priority was not requested (this is something other than an ambient kill)
5814 			 * - the priority was requested *and* the targeted process is not at idle priority
5815 			 */
5816 			if ((memorystatus_jetsam_snapshot_count == 0) &&
5817 			    (force_new_snapshot || memorystatus_idle_snapshot || ((!priority) || (priority && (aPid_ep != JETSAM_PRIORITY_IDLE))))) {
5818 				memorystatus_init_jetsam_snapshot_locked(NULL, 0);
5819 				new_snapshot = true;
5820 			}
5821 
5822 			proc_list_unlock();
5823 
5824 			freed_mem = memorystatus_kill_proc(p, cause, jetsam_reason, &killed, &footprint_of_killed_proc); /* purged and/or killed 'p' */
5825 			/* Success? */
5826 			if (freed_mem) {
5827 				*memory_reclaimed = footprint_of_killed_proc;
5828 				if (killed) {
5829 					if (priority) {
5830 						*priority = aPid_ep;
5831 					}
5832 				} else {
5833 					/* purged */
5834 					proc_list_lock();
5835 					p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
5836 					proc_list_unlock();
5837 				}
5838 				proc_rele(p);
5839 				goto exit;
5840 			}
5841 
5842 			/*
5843 			 * Failure - first unwind the state,
5844 			 * then fall through to restart the search.
5845 			 */
5846 			proc_list_lock();
5847 			proc_rele(p);
5848 			p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
5849 			p->p_memstat_state |= P_MEMSTAT_ERROR;
5850 			*errors += 1;
5851 
5852 			i = 0;
5853 			next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5854 		}
5855 	}
5856 
5857 	proc_list_unlock();
5858 
5859 exit:
5860 	os_reason_free(jetsam_reason);
5861 
5862 	if (!killed) {
5863 		/* Clear snapshot if freshly captured and no target was found */
5864 		if (new_snapshot) {
5865 			proc_list_lock();
5866 			memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
5867 			proc_list_unlock();
5868 		}
5869 	}
5870 
5871 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
5872 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, killed, *memory_reclaimed);
5873 
5874 	return killed;
5875 }
5876 
5877 /*
5878  * Jetsam aggressively
5879  */
5880 static boolean_t
memorystatus_kill_processes_aggressive(uint32_t cause,int aggr_count,int32_t priority_max,int max_kills,uint32_t * errors,uint64_t * memory_reclaimed)5881 memorystatus_kill_processes_aggressive(uint32_t cause, int aggr_count,
5882     int32_t priority_max, int max_kills, uint32_t *errors, uint64_t *memory_reclaimed)
5883 {
5884 	pid_t aPid;
5885 	proc_t p = PROC_NULL, next_p = PROC_NULL;
5886 	boolean_t new_snapshot = FALSE, killed = FALSE;
5887 	int kill_count = 0;
5888 	unsigned int i = 0;
5889 	int32_t aPid_ep = 0;
5890 	unsigned int memorystatus_level_snapshot = 0;
5891 	uint64_t killtime = 0;
5892 	clock_sec_t     tv_sec;
5893 	clock_usec_t    tv_usec;
5894 	uint32_t        tv_msec;
5895 	os_reason_t jetsam_reason = OS_REASON_NULL;
5896 	uint64_t footprint_of_killed_proc = 0;
5897 
5898 	*memory_reclaimed = 0;
5899 
5900 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
5901 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, priority_max);
5902 
5903 	if (priority_max >= JETSAM_PRIORITY_FOREGROUND) {
5904 		/*
5905 		 * Check if aggressive jetsam has been asked to kill upto or beyond the
5906 		 * JETSAM_PRIORITY_FOREGROUND bucket. If yes, sort the FG band based on
5907 		 * coalition footprint.
5908 		 */
5909 		memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
5910 	}
5911 
5912 	jetsam_reason = os_reason_create(OS_REASON_JETSAM, cause);
5913 	if (jetsam_reason == OS_REASON_NULL) {
5914 		memorystatus_log_error("memorystatus_kill_processes_aggressive: failed to allocate exit reason\n");
5915 	}
5916 	memorystatus_log("memorystatus: aggressively killing up to %d processes below band %d.\n", max_kills, priority_max + 1);
5917 	proc_list_lock();
5918 
5919 	next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5920 	while (next_p) {
5921 		if (proc_list_exited(next_p) ||
5922 		    ((unsigned int)(next_p->p_memstat_effectivepriority) != i)) {
5923 			/*
5924 			 * We have raced with next_p running on another core.
5925 			 * It may be exiting or it may have moved to a different
5926 			 * jetsam priority band.  This means we have lost our
5927 			 * place in line while traversing the jetsam list.  We
5928 			 * attempt to recover by rewinding to the beginning of the band
5929 			 * we were already traversing.  By doing this, we do not guarantee
5930 			 * that no process escapes this aggressive march, but we can make
5931 			 * skipping an entire range of processes less likely. (PR-21069019)
5932 			 */
5933 
5934 			memorystatus_log_debug(
5935 				"memorystatus: aggressive%d: rewinding band %d, %s(%d) moved or exiting.\n",
5936 				aggr_count, i, (*next_p->p_name ? next_p->p_name : "unknown"), proc_getpid(next_p));
5937 
5938 			next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5939 			continue;
5940 		}
5941 
5942 		p = next_p;
5943 		next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
5944 
5945 		if (p->p_memstat_effectivepriority > priority_max) {
5946 			/*
5947 			 * Bail out of this killing spree if we have
5948 			 * reached beyond the priority_max jetsam band.
5949 			 * That is, we kill up to and through the
5950 			 * priority_max jetsam band.
5951 			 */
5952 			proc_list_unlock();
5953 			goto exit;
5954 		}
5955 
5956 		aPid = proc_getpid(p);
5957 		aPid_ep = p->p_memstat_effectivepriority;
5958 
5959 		if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP)) {
5960 			continue;
5961 		}
5962 
5963 		/*
5964 		 * Capture a snapshot if none exists.
5965 		 */
5966 		if (memorystatus_jetsam_snapshot_count == 0) {
5967 			memorystatus_init_jetsam_snapshot_locked(NULL, 0);
5968 			new_snapshot = TRUE;
5969 		}
5970 
5971 		/*
5972 		 * Mark as terminated so that if exit1() indicates success, but the process (for example)
5973 		 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
5974 		 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
5975 		 * acquisition of the proc lock.
5976 		 */
5977 		p->p_memstat_state |= P_MEMSTAT_TERMINATED;
5978 
5979 		killtime = mach_absolute_time();
5980 		absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
5981 		tv_msec = tv_usec / 1000;
5982 
5983 		/* Shift queue, update stats */
5984 		memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
5985 
5986 		/*
5987 		 * In order to kill the target process, we will drop the proc_list_lock.
5988 		 * To guaranteee that p and next_p don't disappear out from under the lock,
5989 		 * we must take a ref on both.
5990 		 * If we cannot get a reference, then it's likely we've raced with
5991 		 * that process exiting on another core.
5992 		 */
5993 		if (proc_ref(p, true) == p) {
5994 			if (next_p) {
5995 				while (next_p && (proc_ref(next_p, true) != next_p)) {
5996 					proc_t temp_p;
5997 
5998 					/*
5999 					 * We must have raced with next_p exiting on another core.
6000 					 * Recover by getting the next eligible process in the band.
6001 					 */
6002 
6003 					memorystatus_log_debug(
6004 						"memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
6005 						aggr_count, proc_getpid(next_p), (*next_p->p_name ? next_p->p_name : "(unknown)"));
6006 
6007 					temp_p = next_p;
6008 					next_p = memorystatus_get_next_proc_locked(&i, temp_p, TRUE);
6009 				}
6010 			}
6011 			proc_list_unlock();
6012 
6013 			memorystatus_log(
6014 				"%lu.%03d memorystatus: %s%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
6015 				(unsigned long)tv_sec, tv_msec,
6016 				((aPid_ep == JETSAM_PRIORITY_IDLE) ? "killing_idle_process_aggressive" : "killing_top_process_aggressive"),
6017 				aggr_count, aPid, (*p->p_name ? p->p_name : "unknown"),
6018 				memorystatus_kill_cause_name[cause], aPid_ep, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
6019 
6020 			memorystatus_level_snapshot = memorystatus_level;
6021 
6022 			/*
6023 			 * memorystatus_do_kill() drops a reference, so take another one so we can
6024 			 * continue to use this exit reason even after memorystatus_do_kill()
6025 			 * returns.
6026 			 */
6027 			os_reason_ref(jetsam_reason);
6028 			killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
6029 
6030 			/* Success? */
6031 			if (killed) {
6032 				*memory_reclaimed += footprint_of_killed_proc;
6033 				proc_rele(p);
6034 				kill_count++;
6035 				p = NULL;
6036 				killed = FALSE;
6037 
6038 				/*
6039 				 * Continue the killing spree.
6040 				 */
6041 				proc_list_lock();
6042 				if (next_p) {
6043 					proc_rele(next_p);
6044 				}
6045 
6046 				if (kill_count == max_kills) {
6047 					memorystatus_log_info(
6048 						"memorystatus: giving up aggressive kill after killing %d processes below band %d.\n", max_kills, priority_max + 1);
6049 					break;
6050 				}
6051 
6052 				if (aPid_ep == JETSAM_PRIORITY_FOREGROUND && memorystatus_aggressive_jetsam_lenient == TRUE) {
6053 					if (memorystatus_level > memorystatus_level_snapshot && ((memorystatus_level - memorystatus_level_snapshot) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD)) {
6054 #if DEVELOPMENT || DEBUG
6055 						memorystatus_log_info("Disabling Lenient mode after one-time deployment.\n");
6056 #endif /* DEVELOPMENT || DEBUG */
6057 						memorystatus_aggressive_jetsam_lenient = FALSE;
6058 						break;
6059 					}
6060 				}
6061 
6062 				continue;
6063 			}
6064 
6065 			/*
6066 			 * Failure - first unwind the state,
6067 			 * then fall through to restart the search.
6068 			 */
6069 			proc_list_lock();
6070 			proc_rele(p);
6071 			if (next_p) {
6072 				proc_rele(next_p);
6073 			}
6074 			p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
6075 			p->p_memstat_state |= P_MEMSTAT_ERROR;
6076 			*errors += 1;
6077 			p = NULL;
6078 		}
6079 
6080 		/*
6081 		 * Failure - restart the search at the beginning of
6082 		 * the band we were already traversing.
6083 		 *
6084 		 * We might have raced with "p" exiting on another core, resulting in no
6085 		 * ref on "p".  Or, we may have failed to kill "p".
6086 		 *
6087 		 * Either way, we fall thru to here, leaving the proc in the
6088 		 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
6089 		 *
6090 		 * And, we hold the the proc_list_lock at this point.
6091 		 */
6092 
6093 		next_p = memorystatus_get_first_proc_locked(&i, TRUE);
6094 	}
6095 
6096 	proc_list_unlock();
6097 
6098 exit:
6099 	os_reason_free(jetsam_reason);
6100 
6101 	/* Clear snapshot if freshly captured and no target was found */
6102 	if (new_snapshot && (kill_count == 0)) {
6103 		proc_list_lock();
6104 		memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
6105 		proc_list_unlock();
6106 	}
6107 
6108 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
6109 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, 0, kill_count, *memory_reclaimed);
6110 
6111 	if (kill_count > 0) {
6112 		return TRUE;
6113 	} else {
6114 		return FALSE;
6115 	}
6116 }
6117 
6118 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t * errors,boolean_t * purged,uint64_t * memory_reclaimed)6119 memorystatus_kill_hiwat_proc(uint32_t *errors, boolean_t *purged, uint64_t *memory_reclaimed)
6120 {
6121 	pid_t aPid = 0;
6122 	proc_t p = PROC_NULL, next_p = PROC_NULL;
6123 	bool new_snapshot = false, killed = false, freed_mem = false;
6124 	unsigned int i = 0;
6125 	uint32_t aPid_ep;
6126 	os_reason_t jetsam_reason = OS_REASON_NULL;
6127 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_START,
6128 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES);
6129 
6130 	jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_HIGHWATER);
6131 	if (jetsam_reason == OS_REASON_NULL) {
6132 		memorystatus_log_error("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
6133 	}
6134 
6135 	proc_list_lock();
6136 
6137 	next_p = memorystatus_get_first_proc_locked(&i, TRUE);
6138 	while (next_p) {
6139 		uint64_t footprint_in_bytes = 0;
6140 		uint64_t memlimit_in_bytes  = 0;
6141 		boolean_t skip = 0;
6142 
6143 		p = next_p;
6144 		next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
6145 
6146 		aPid = proc_getpid(p);
6147 		aPid_ep = p->p_memstat_effectivepriority;
6148 
6149 		if (p->p_memstat_state  & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP)) {
6150 			continue;
6151 		}
6152 
6153 		/* skip if no limit set */
6154 		if (p->p_memstat_memlimit <= 0) {
6155 			continue;
6156 		}
6157 
6158 		footprint_in_bytes = get_task_phys_footprint(proc_task(p));
6159 		memlimit_in_bytes  = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL);   /* convert MB to bytes */
6160 		skip = (footprint_in_bytes <= memlimit_in_bytes);
6161 
6162 #if CONFIG_FREEZE
6163 		if (!skip) {
6164 			if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
6165 				skip = TRUE;
6166 			} else {
6167 				skip = FALSE;
6168 			}
6169 		}
6170 #endif
6171 
6172 		if (skip) {
6173 			continue;
6174 		} else {
6175 			if (memorystatus_jetsam_snapshot_count == 0) {
6176 				memorystatus_init_jetsam_snapshot_locked(NULL, 0);
6177 				new_snapshot = true;
6178 			}
6179 
6180 			if (proc_ref(p, true) == p) {
6181 				/*
6182 				 * Mark as terminated so that if exit1() indicates success, but the process (for example)
6183 				 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
6184 				 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
6185 				 * acquisition of the proc lock.
6186 				 */
6187 				p->p_memstat_state |= P_MEMSTAT_TERMINATED;
6188 
6189 				proc_list_unlock();
6190 			} else {
6191 				/*
6192 				 * We need to restart the search again because
6193 				 * proc_ref _can_ drop the proc_list lock
6194 				 * and we could have lost our stored next_p via
6195 				 * an exit() on another core.
6196 				 */
6197 				i = 0;
6198 				next_p = memorystatus_get_first_proc_locked(&i, TRUE);
6199 				continue;
6200 			}
6201 
6202 			footprint_in_bytes = 0;
6203 			freed_mem = memorystatus_kill_proc(p, kMemorystatusKilledHiwat, jetsam_reason, &killed, &footprint_in_bytes); /* purged and/or killed 'p' */
6204 
6205 			/* Success? */
6206 			if (freed_mem) {
6207 				if (!killed) {
6208 					/* purged 'p'..don't reset HWM candidate count */
6209 					*purged = TRUE;
6210 
6211 					proc_list_lock();
6212 					p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
6213 					proc_list_unlock();
6214 				} else {
6215 					*memory_reclaimed = footprint_in_bytes;
6216 				}
6217 				proc_rele(p);
6218 				goto exit;
6219 			}
6220 			/*
6221 			 * Failure - first unwind the state,
6222 			 * then fall through to restart the search.
6223 			 */
6224 			proc_list_lock();
6225 			proc_rele(p);
6226 			p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
6227 			p->p_memstat_state |= P_MEMSTAT_ERROR;
6228 			*errors += 1;
6229 
6230 			i = 0;
6231 			next_p = memorystatus_get_first_proc_locked(&i, TRUE);
6232 		}
6233 	}
6234 
6235 	proc_list_unlock();
6236 
6237 exit:
6238 	os_reason_free(jetsam_reason);
6239 
6240 	if (!killed) {
6241 		*memory_reclaimed = 0;
6242 
6243 		/* Clear snapshot if freshly captured and no target was found */
6244 		if (new_snapshot) {
6245 			proc_list_lock();
6246 			memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
6247 			proc_list_unlock();
6248 		}
6249 	}
6250 
6251 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_END,
6252 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, killed, *memory_reclaimed, 0);
6253 
6254 	return killed;
6255 }
6256 
6257 /*
6258  * Jetsam a process pinned in the elevated band.
6259  *
6260  * Return:  true -- a pinned process was jetsammed
6261  *	    false -- no pinned process was jetsammed
6262  */
6263 boolean_t
memorystatus_kill_elevated_process(uint32_t cause,os_reason_t jetsam_reason,unsigned int band,int aggr_count,uint32_t * errors,uint64_t * memory_reclaimed)6264 memorystatus_kill_elevated_process(uint32_t cause, os_reason_t jetsam_reason, unsigned int band, int aggr_count, uint32_t *errors, uint64_t *memory_reclaimed)
6265 {
6266 	pid_t aPid = 0;
6267 	proc_t p = PROC_NULL, next_p = PROC_NULL;
6268 	boolean_t new_snapshot = FALSE, killed = FALSE;
6269 	int kill_count = 0;
6270 	uint32_t aPid_ep;
6271 	uint64_t killtime = 0;
6272 	clock_sec_t     tv_sec;
6273 	clock_usec_t    tv_usec;
6274 	uint32_t        tv_msec;
6275 	uint64_t footprint_of_killed_proc = 0;
6276 
6277 
6278 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
6279 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES);
6280 
6281 #if CONFIG_FREEZE
6282 	boolean_t consider_frozen_only = FALSE;
6283 
6284 	if (band == (unsigned int) memorystatus_freeze_jetsam_band) {
6285 		consider_frozen_only = TRUE;
6286 	}
6287 #endif /* CONFIG_FREEZE */
6288 
6289 	proc_list_lock();
6290 
6291 	next_p = memorystatus_get_first_proc_locked(&band, FALSE);
6292 	while (next_p) {
6293 		p = next_p;
6294 		next_p = memorystatus_get_next_proc_locked(&band, p, FALSE);
6295 
6296 		aPid = proc_getpid(p);
6297 		aPid_ep = p->p_memstat_effectivepriority;
6298 
6299 		/*
6300 		 * Only pick a process pinned in this elevated band
6301 		 */
6302 		if (!(p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) {
6303 			continue;
6304 		}
6305 
6306 		if (p->p_memstat_state  & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP)) {
6307 			continue;
6308 		}
6309 
6310 #if CONFIG_FREEZE
6311 		if (consider_frozen_only && !(p->p_memstat_state & P_MEMSTAT_FROZEN)) {
6312 			continue;
6313 		}
6314 
6315 		if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
6316 			continue;
6317 		}
6318 #endif /* CONFIG_FREEZE */
6319 
6320 #if DEVELOPMENT || DEBUG
6321 		memorystatus_log_info(
6322 			"jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
6323 			aggr_count, aPid, (*p->p_name ? p->p_name : "unknown"), MEMORYSTATUS_LOG_AVAILABLE_PAGES);
6324 #endif /* DEVELOPMENT || DEBUG */
6325 
6326 		if (memorystatus_jetsam_snapshot_count == 0) {
6327 			memorystatus_init_jetsam_snapshot_locked(NULL, 0);
6328 			new_snapshot = TRUE;
6329 		}
6330 
6331 		p->p_memstat_state |= P_MEMSTAT_TERMINATED;
6332 
6333 		killtime = mach_absolute_time();
6334 		absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
6335 		tv_msec = tv_usec / 1000;
6336 
6337 		memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
6338 
6339 		if (proc_ref(p, true) == p) {
6340 			proc_list_unlock();
6341 
6342 			/*
6343 			 * memorystatus_do_kill drops a reference, so take another one so we can
6344 			 * continue to use this exit reason even after memorystatus_do_kill()
6345 			 * returns
6346 			 */
6347 			os_reason_ref(jetsam_reason);
6348 			killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
6349 
6350 			memorystatus_log("%lu.%03d memorystatus: killing_top_process_elevated%d pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu\n",
6351 			    (unsigned long)tv_sec, tv_msec,
6352 			    aggr_count,
6353 			    aPid, ((p && *p->p_name) ? p->p_name : "unknown"),
6354 			    memorystatus_kill_cause_name[cause], aPid_ep,
6355 			    footprint_of_killed_proc >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
6356 
6357 			/* Success? */
6358 			if (killed) {
6359 				*memory_reclaimed = footprint_of_killed_proc;
6360 				proc_rele(p);
6361 				kill_count++;
6362 				goto exit;
6363 			}
6364 
6365 			/*
6366 			 * Failure - first unwind the state,
6367 			 * then fall through to restart the search.
6368 			 */
6369 			proc_list_lock();
6370 			proc_rele(p);
6371 			p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
6372 			p->p_memstat_state |= P_MEMSTAT_ERROR;
6373 			*errors += 1;
6374 		}
6375 
6376 		/*
6377 		 * Failure - restart the search.
6378 		 *
6379 		 * We might have raced with "p" exiting on another core, resulting in no
6380 		 * ref on "p".  Or, we may have failed to kill "p".
6381 		 *
6382 		 * Either way, we fall thru to here, leaving the proc in the
6383 		 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
6384 		 *
6385 		 * And, we hold the the proc_list_lock at this point.
6386 		 */
6387 
6388 		next_p = memorystatus_get_first_proc_locked(&band, FALSE);
6389 	}
6390 
6391 	proc_list_unlock();
6392 
6393 exit:
6394 	os_reason_free(jetsam_reason);
6395 
6396 	if (kill_count == 0) {
6397 		*memory_reclaimed = 0;
6398 
6399 		/* Clear snapshot if freshly captured and no target was found */
6400 		if (new_snapshot) {
6401 			proc_list_lock();
6402 			memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
6403 			proc_list_unlock();
6404 		}
6405 	}
6406 
6407 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
6408 	    MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, kill_count, *memory_reclaimed);
6409 
6410 	return killed;
6411 }
6412 
6413 boolean_t
memorystatus_kill_on_VM_compressor_space_shortage(boolean_t async)6414 memorystatus_kill_on_VM_compressor_space_shortage(boolean_t async)
6415 {
6416 	if (async) {
6417 		os_atomic_store(&memorystatus_compressor_space_shortage, true, release);
6418 		memorystatus_thread_wake();
6419 		return true;
6420 	} else {
6421 		os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE);
6422 		if (jetsam_reason == OS_REASON_NULL) {
6423 			memorystatus_log_error("memorystatus_kill_on_VM_compressor_space_shortage -- sync: failed to allocate jetsam reason\n");
6424 		}
6425 
6426 		return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMCompressorSpaceShortage, jetsam_reason);
6427 	}
6428 }
6429 
6430 #if CONFIG_JETSAM
6431 
6432 void
memorystatus_kill_on_vps_starvation(void)6433 memorystatus_kill_on_vps_starvation(void)
6434 {
6435 	os_atomic_store(&memorystatus_pageout_starved, true, release);
6436 	memorystatus_thread_wake();
6437 }
6438 
6439 boolean_t
memorystatus_kill_on_vnode_limit(void)6440 memorystatus_kill_on_vnode_limit(void)
6441 {
6442 	os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_VNODE);
6443 	if (jetsam_reason == OS_REASON_NULL) {
6444 		memorystatus_log_error("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
6445 	}
6446 
6447 	return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes, jetsam_reason);
6448 }
6449 
6450 boolean_t
memorystatus_kill_on_sustained_pressure()6451 memorystatus_kill_on_sustained_pressure()
6452 {
6453 	os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_SUSTAINED_PRESSURE);
6454 	if (jetsam_reason == OS_REASON_NULL) {
6455 		memorystatus_log_error("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
6456 	}
6457 
6458 	return memorystatus_kill_process_sync(-1, kMemorystatusKilledSustainedPressure, jetsam_reason);
6459 }
6460 
6461 boolean_t
memorystatus_kill_with_jetsam_reason_sync(pid_t pid,os_reason_t jetsam_reason)6462 memorystatus_kill_with_jetsam_reason_sync(pid_t pid, os_reason_t jetsam_reason)
6463 {
6464 	uint32_t kill_cause = jetsam_reason->osr_code <= JETSAM_REASON_MEMORYSTATUS_MAX ?
6465 	    (uint32_t) jetsam_reason->osr_code : JETSAM_REASON_INVALID;
6466 	return memorystatus_kill_process_sync(pid, kill_cause, jetsam_reason);
6467 }
6468 
6469 #endif /* CONFIG_JETSAM */
6470 
6471 boolean_t
memorystatus_kill_on_zone_map_exhaustion(pid_t pid)6472 memorystatus_kill_on_zone_map_exhaustion(pid_t pid)
6473 {
6474 	boolean_t res = FALSE;
6475 	if (pid == -1) {
6476 		os_atomic_store(&memorystatus_zone_map_is_exhausted, true, release);
6477 		memorystatus_thread_wake();
6478 		return true;
6479 	} else {
6480 		os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_ZONE_MAP_EXHAUSTION);
6481 		if (jetsam_reason == OS_REASON_NULL) {
6482 			memorystatus_log_error("memorystatus_kill_on_zone_map_exhaustion: failed to allocate jetsam reason\n");
6483 		}
6484 
6485 		res = memorystatus_kill_process_sync(pid, kMemorystatusKilledZoneMapExhaustion, jetsam_reason);
6486 	}
6487 	return res;
6488 }
6489 
6490 void
memorystatus_on_pageout_scan_end(void)6491 memorystatus_on_pageout_scan_end(void)
6492 {
6493 	/* No-op */
6494 }
6495 
6496 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
6497 static int
memorystatus_get_priority_list(memorystatus_priority_entry_t ** list_ptr,size_t * buffer_size,size_t * list_size,boolean_t size_only)6498 memorystatus_get_priority_list(memorystatus_priority_entry_t **list_ptr, size_t *buffer_size, size_t *list_size, boolean_t size_only)
6499 {
6500 	uint32_t list_count, i = 0;
6501 	memorystatus_priority_entry_t *list_entry;
6502 	proc_t p;
6503 
6504 	list_count = memorystatus_list_count;
6505 	*list_size = sizeof(memorystatus_priority_entry_t) * list_count;
6506 
6507 	/* Just a size check? */
6508 	if (size_only) {
6509 		return 0;
6510 	}
6511 
6512 	/* Otherwise, validate the size of the buffer */
6513 	if (*buffer_size < *list_size) {
6514 		return EINVAL;
6515 	}
6516 
6517 	*list_ptr = kalloc_data(*list_size, Z_WAITOK | Z_ZERO);
6518 	if (!*list_ptr) {
6519 		return ENOMEM;
6520 	}
6521 
6522 	*buffer_size = *list_size;
6523 	*list_size = 0;
6524 
6525 	list_entry = *list_ptr;
6526 
6527 	proc_list_lock();
6528 
6529 	p = memorystatus_get_first_proc_locked(&i, TRUE);
6530 	while (p && (*list_size < *buffer_size)) {
6531 		list_entry->pid = proc_getpid(p);
6532 		list_entry->priority = p->p_memstat_effectivepriority;
6533 		list_entry->user_data = p->p_memstat_userdata;
6534 
6535 		if (p->p_memstat_memlimit <= 0) {
6536 			task_get_phys_footprint_limit(proc_task(p), &list_entry->limit);
6537 		} else {
6538 			list_entry->limit = p->p_memstat_memlimit;
6539 		}
6540 
6541 		list_entry->state = memorystatus_build_state(p);
6542 		list_entry++;
6543 
6544 		*list_size += sizeof(memorystatus_priority_entry_t);
6545 
6546 		p = memorystatus_get_next_proc_locked(&i, p, TRUE);
6547 	}
6548 
6549 	proc_list_unlock();
6550 
6551 	memorystatus_log_debug("memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size);
6552 
6553 	return 0;
6554 }
6555 
6556 static int
memorystatus_get_priority_pid(pid_t pid,user_addr_t buffer,size_t buffer_size)6557 memorystatus_get_priority_pid(pid_t pid, user_addr_t buffer, size_t buffer_size)
6558 {
6559 	int error = 0;
6560 	memorystatus_priority_entry_t mp_entry;
6561 	kern_return_t ret;
6562 
6563 	/* Validate inputs */
6564 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_priority_entry_t))) {
6565 		return EINVAL;
6566 	}
6567 
6568 	proc_t p = proc_find(pid);
6569 	if (!p) {
6570 		return ESRCH;
6571 	}
6572 
6573 	memset(&mp_entry, 0, sizeof(memorystatus_priority_entry_t));
6574 
6575 	mp_entry.pid = proc_getpid(p);
6576 	mp_entry.priority = p->p_memstat_effectivepriority;
6577 	mp_entry.user_data = p->p_memstat_userdata;
6578 	if (p->p_memstat_memlimit <= 0) {
6579 		ret = task_get_phys_footprint_limit(proc_task(p), &mp_entry.limit);
6580 		if (ret != KERN_SUCCESS) {
6581 			proc_rele(p);
6582 			return EINVAL;
6583 		}
6584 	} else {
6585 		mp_entry.limit = p->p_memstat_memlimit;
6586 	}
6587 	mp_entry.state = memorystatus_build_state(p);
6588 
6589 	proc_rele(p);
6590 
6591 	error = copyout(&mp_entry, buffer, buffer_size);
6592 
6593 	return error;
6594 }
6595 
6596 static int
memorystatus_cmd_get_priority_list(pid_t pid,user_addr_t buffer,size_t buffer_size,int32_t * retval)6597 memorystatus_cmd_get_priority_list(pid_t pid, user_addr_t buffer, size_t buffer_size, int32_t *retval)
6598 {
6599 	int error = 0;
6600 	boolean_t size_only;
6601 	size_t list_size;
6602 
6603 	/*
6604 	 * When a non-zero pid is provided, the 'list' has only one entry.
6605 	 */
6606 
6607 	size_only = ((buffer == USER_ADDR_NULL) ? TRUE: FALSE);
6608 
6609 	if (pid != 0) {
6610 		list_size = sizeof(memorystatus_priority_entry_t) * 1;
6611 		if (!size_only) {
6612 			error = memorystatus_get_priority_pid(pid, buffer, buffer_size);
6613 		}
6614 	} else {
6615 		memorystatus_priority_entry_t *list = NULL;
6616 		error = memorystatus_get_priority_list(&list, &buffer_size, &list_size, size_only);
6617 
6618 		if (error == 0) {
6619 			if (!size_only) {
6620 				error = copyout(list, buffer, list_size);
6621 			}
6622 
6623 			kfree_data(list, buffer_size);
6624 		}
6625 	}
6626 
6627 	if (error == 0) {
6628 		assert(list_size <= INT32_MAX);
6629 		*retval = (int32_t) list_size;
6630 	}
6631 
6632 	return error;
6633 }
6634 
6635 static void
memorystatus_clear_errors(void)6636 memorystatus_clear_errors(void)
6637 {
6638 	proc_t p;
6639 	unsigned int i = 0;
6640 
6641 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_START);
6642 
6643 	proc_list_lock();
6644 
6645 	p = memorystatus_get_first_proc_locked(&i, TRUE);
6646 	while (p) {
6647 		if (p->p_memstat_state & P_MEMSTAT_ERROR) {
6648 			p->p_memstat_state &= ~P_MEMSTAT_ERROR;
6649 		}
6650 		p = memorystatus_get_next_proc_locked(&i, p, TRUE);
6651 	}
6652 
6653 	proc_list_unlock();
6654 
6655 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_END);
6656 }
6657 
6658 #if CONFIG_JETSAM
6659 static void
memorystatus_update_levels_locked(void)6660 memorystatus_update_levels_locked(void)
6661 {
6662 	/*
6663 	 * If there's an entry in the first bucket, we have idle processes.
6664 	 */
6665 	memstat_bucket_t *first_bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
6666 	if (first_bucket->count) {
6667 		memorystatus_available_pages_critical = memorystatus_available_pages_critical_idle;
6668 	} else {
6669 		memorystatus_available_pages_critical = memorystatus_available_pages_critical_base;
6670 	}
6671 
6672 	if (memorystatus_available_pages_critical > memorystatus_available_pages_pressure) {
6673 		/*
6674 		 * The critical threshold must never exceed the pressure threshold
6675 		 */
6676 		memorystatus_available_pages_critical = memorystatus_available_pages_pressure;
6677 	}
6678 
6679 	if (memorystatus_jetsam_policy & kPolicyMoreFree) {
6680 		memorystatus_available_pages_critical += memorystatus_policy_more_free_offset_pages;
6681 	}
6682 }
6683 
6684 void
memorystatus_fast_jetsam_override(boolean_t enable_override)6685 memorystatus_fast_jetsam_override(boolean_t enable_override)
6686 {
6687 	/* If fast jetsam is not enabled, simply return */
6688 	if (!fast_jetsam_enabled) {
6689 		return;
6690 	}
6691 
6692 	if (enable_override) {
6693 		if ((memorystatus_jetsam_policy & kPolicyMoreFree) == kPolicyMoreFree) {
6694 			return;
6695 		}
6696 		proc_list_lock();
6697 		memorystatus_jetsam_policy |= kPolicyMoreFree;
6698 		memorystatus_thread_pool_max();
6699 		memorystatus_update_levels_locked();
6700 		proc_list_unlock();
6701 	} else {
6702 		if ((memorystatus_jetsam_policy & kPolicyMoreFree) == 0) {
6703 			return;
6704 		}
6705 		proc_list_lock();
6706 		memorystatus_jetsam_policy &= ~kPolicyMoreFree;
6707 		memorystatus_thread_pool_default();
6708 		memorystatus_update_levels_locked();
6709 		proc_list_unlock();
6710 	}
6711 }
6712 
6713 
6714 static int
6715 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
6716 {
6717 #pragma unused(arg1, arg2, oidp)
6718 	int error = 0, more_free = 0;
6719 
6720 	/*
6721 	 * TODO: Enable this privilege check?
6722 	 *
6723 	 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
6724 	 * if (error)
6725 	 *	return (error);
6726 	 */
6727 
6728 	error = sysctl_handle_int(oidp, &more_free, 0, req);
6729 	if (error || !req->newptr) {
6730 		return error;
6731 	}
6732 
6733 	if (more_free) {
6734 		memorystatus_fast_jetsam_override(true);
6735 	} else {
6736 		memorystatus_fast_jetsam_override(false);
6737 	}
6738 
6739 	return 0;
6740 }
6741 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_policy_more_free, CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_LOCKED | CTLFLAG_MASKED,
6742     0, 0, &sysctl_kern_memorystatus_policy_more_free, "I", "");
6743 
6744 #endif /* CONFIG_JETSAM */
6745 
6746 /*
6747  * Get the at_boot snapshot
6748  */
6749 static int
memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t ** snapshot,size_t * snapshot_size,boolean_t size_only)6750 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
6751 {
6752 	size_t input_size = *snapshot_size;
6753 
6754 	/*
6755 	 * The at_boot snapshot has no entry list.
6756 	 */
6757 	*snapshot_size = sizeof(memorystatus_jetsam_snapshot_t);
6758 
6759 	if (size_only) {
6760 		return 0;
6761 	}
6762 
6763 	/*
6764 	 * Validate the size of the snapshot buffer
6765 	 */
6766 	if (input_size < *snapshot_size) {
6767 		return EINVAL;
6768 	}
6769 
6770 	/*
6771 	 * Update the notification_time only
6772 	 */
6773 	memorystatus_at_boot_snapshot.notification_time = mach_absolute_time();
6774 	*snapshot = &memorystatus_at_boot_snapshot;
6775 
6776 	memorystatus_log_debug(
6777 		"memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
6778 		(long)input_size, (long)*snapshot_size, 0);
6779 	return 0;
6780 }
6781 
6782 #if CONFIG_FREEZE
6783 static int
memorystatus_get_jetsam_snapshot_freezer(memorystatus_jetsam_snapshot_t ** snapshot,size_t * snapshot_size,boolean_t size_only)6784 memorystatus_get_jetsam_snapshot_freezer(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
6785 {
6786 	size_t input_size = *snapshot_size;
6787 
6788 	if (memorystatus_jetsam_snapshot_freezer->entry_count > 0) {
6789 		*snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_freezer->entry_count));
6790 	} else {
6791 		*snapshot_size = 0;
6792 	}
6793 	assert(*snapshot_size <= memorystatus_jetsam_snapshot_freezer_size);
6794 
6795 	if (size_only) {
6796 		return 0;
6797 	}
6798 
6799 	if (input_size < *snapshot_size) {
6800 		return EINVAL;
6801 	}
6802 
6803 	*snapshot = memorystatus_jetsam_snapshot_freezer;
6804 
6805 	memorystatus_log_debug(
6806 		"memorystatus_get_jetsam_snapshot_freezer: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
6807 		(long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_freezer->entry_count);
6808 
6809 	return 0;
6810 }
6811 #endif /* CONFIG_FREEZE */
6812 
6813 static int
memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t ** snapshot,size_t * snapshot_size,boolean_t size_only)6814 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
6815 {
6816 	size_t input_size = *snapshot_size;
6817 	uint32_t ods_list_count = memorystatus_list_count;
6818 	memorystatus_jetsam_snapshot_t *ods = NULL;     /* The on_demand snapshot buffer */
6819 
6820 	*snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (ods_list_count));
6821 
6822 	if (size_only) {
6823 		return 0;
6824 	}
6825 
6826 	/*
6827 	 * Validate the size of the snapshot buffer.
6828 	 * This is inherently racey. May want to revisit
6829 	 * this error condition and trim the output when
6830 	 * it doesn't fit.
6831 	 */
6832 	if (input_size < *snapshot_size) {
6833 		return EINVAL;
6834 	}
6835 
6836 	/*
6837 	 * Allocate and initialize a snapshot buffer.
6838 	 */
6839 	ods = kalloc_data(*snapshot_size, Z_WAITOK | Z_ZERO);
6840 	if (!ods) {
6841 		return ENOMEM;
6842 	}
6843 
6844 	proc_list_lock();
6845 	memorystatus_init_jetsam_snapshot_locked(ods, ods_list_count);
6846 	proc_list_unlock();
6847 
6848 	/*
6849 	 * Return the kernel allocated, on_demand buffer.
6850 	 * The caller of this routine will copy the data out
6851 	 * to user space and then free the kernel allocated
6852 	 * buffer.
6853 	 */
6854 	*snapshot = ods;
6855 
6856 	memorystatus_log_debug(
6857 		"memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
6858 		(long)input_size, (long)*snapshot_size, (long)ods_list_count);
6859 
6860 	return 0;
6861 }
6862 
6863 static int
memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t ** snapshot,size_t * snapshot_size,boolean_t size_only)6864 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
6865 {
6866 	size_t input_size = *snapshot_size;
6867 
6868 	if (memorystatus_jetsam_snapshot_count > 0) {
6869 		*snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count));
6870 	} else {
6871 		*snapshot_size = 0;
6872 	}
6873 
6874 	if (size_only) {
6875 		return 0;
6876 	}
6877 
6878 	if (input_size < *snapshot_size) {
6879 		return EINVAL;
6880 	}
6881 
6882 	*snapshot = memorystatus_jetsam_snapshot;
6883 
6884 	memorystatus_log_debug(
6885 		"memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
6886 		(long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_count);
6887 
6888 	return 0;
6889 }
6890 
6891 
6892 static int
memorystatus_cmd_get_jetsam_snapshot(int32_t flags,user_addr_t buffer,size_t buffer_size,int32_t * retval)6893 memorystatus_cmd_get_jetsam_snapshot(int32_t flags, user_addr_t buffer, size_t buffer_size, int32_t *retval)
6894 {
6895 	int error = EINVAL;
6896 	boolean_t size_only;
6897 	boolean_t is_default_snapshot = FALSE;
6898 	boolean_t is_on_demand_snapshot = FALSE;
6899 	boolean_t is_at_boot_snapshot = FALSE;
6900 #if CONFIG_FREEZE
6901 	bool is_freezer_snapshot = false;
6902 #endif /* CONFIG_FREEZE */
6903 	memorystatus_jetsam_snapshot_t *snapshot;
6904 
6905 	size_only = ((buffer == USER_ADDR_NULL) ? TRUE : FALSE);
6906 
6907 	if (flags == 0) {
6908 		/* Default */
6909 		is_default_snapshot = TRUE;
6910 		error = memorystatus_get_jetsam_snapshot(&snapshot, &buffer_size, size_only);
6911 	} else {
6912 		if (flags & ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND | MEMORYSTATUS_SNAPSHOT_AT_BOOT | MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER)) {
6913 			/*
6914 			 * Unsupported bit set in flag.
6915 			 */
6916 			return EINVAL;
6917 		}
6918 
6919 		if (flags & (flags - 0x1)) {
6920 			/*
6921 			 * Can't have multiple flags set at the same time.
6922 			 */
6923 			return EINVAL;
6924 		}
6925 
6926 		if (flags & MEMORYSTATUS_SNAPSHOT_ON_DEMAND) {
6927 			is_on_demand_snapshot = TRUE;
6928 			/*
6929 			 * When not requesting the size only, the following call will allocate
6930 			 * an on_demand snapshot buffer, which is freed below.
6931 			 */
6932 			error = memorystatus_get_on_demand_snapshot(&snapshot, &buffer_size, size_only);
6933 		} else if (flags & MEMORYSTATUS_SNAPSHOT_AT_BOOT) {
6934 			is_at_boot_snapshot = TRUE;
6935 			error = memorystatus_get_at_boot_snapshot(&snapshot, &buffer_size, size_only);
6936 #if CONFIG_FREEZE
6937 		} else if (flags & MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER) {
6938 			is_freezer_snapshot = true;
6939 			error = memorystatus_get_jetsam_snapshot_freezer(&snapshot, &buffer_size, size_only);
6940 #endif /* CONFIG_FREEZE */
6941 		} else {
6942 			/*
6943 			 * Invalid flag setting.
6944 			 */
6945 			return EINVAL;
6946 		}
6947 	}
6948 
6949 	if (error) {
6950 		goto out;
6951 	}
6952 
6953 	/*
6954 	 * Copy the data out to user space and clear the snapshot buffer.
6955 	 * If working with the jetsam snapshot,
6956 	 *	clearing the buffer means, reset the count.
6957 	 * If working with an on_demand snapshot
6958 	 *	clearing the buffer means, free it.
6959 	 * If working with the at_boot snapshot
6960 	 *	there is nothing to clear or update.
6961 	 * If working with a copy of the snapshot
6962 	 *	there is nothing to clear or update.
6963 	 * If working with the freezer snapshot
6964 	 *	clearing the buffer means, reset the count.
6965 	 */
6966 	if (!size_only) {
6967 		if ((error = copyout(snapshot, buffer, buffer_size)) == 0) {
6968 #if CONFIG_FREEZE
6969 			if (is_default_snapshot || is_freezer_snapshot) {
6970 #else
6971 			if (is_default_snapshot) {
6972 #endif /* CONFIG_FREEZE */
6973 				/*
6974 				 * The jetsam snapshot is never freed, its count is simply reset.
6975 				 * However, we make a copy for any parties that might be interested
6976 				 * in the previous fully populated snapshot.
6977 				 */
6978 				proc_list_lock();
6979 #if DEVELOPMENT || DEBUG
6980 				if (memorystatus_testing_pid != 0 && memorystatus_testing_pid != proc_getpid(current_proc())) {
6981 					/* Snapshot is currently owned by someone else. Don't consume it. */
6982 					proc_list_unlock();
6983 					goto out;
6984 				}
6985 #endif /* (DEVELOPMENT || DEBUG)*/
6986 				if (is_default_snapshot) {
6987 					snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
6988 					memorystatus_jetsam_snapshot_last_timestamp = 0;
6989 				}
6990 #if CONFIG_FREEZE
6991 				else if (is_freezer_snapshot) {
6992 					memorystatus_jetsam_snapshot_freezer->entry_count = 0;
6993 				}
6994 #endif /* CONFIG_FREEZE */
6995 				proc_list_unlock();
6996 			}
6997 		}
6998 
6999 		if (is_on_demand_snapshot) {
7000 			/*
7001 			 * The on_demand snapshot is always freed,
7002 			 * even if the copyout failed.
7003 			 */
7004 			kfree_data(snapshot, buffer_size);
7005 		}
7006 	}
7007 
7008 out:
7009 	if (error == 0) {
7010 		assert(buffer_size <= INT32_MAX);
7011 		*retval = (int32_t) buffer_size;
7012 	}
7013 	return error;
7014 }
7015 
7016 #if DEVELOPMENT || DEBUG
7017 static int
7018 memorystatus_cmd_set_testing_pid(int32_t flags)
7019 {
7020 	int error = EINVAL;
7021 	proc_t caller = current_proc();
7022 	assert(caller != kernproc);
7023 	proc_list_lock();
7024 	if (flags & MEMORYSTATUS_FLAGS_SET_TESTING_PID) {
7025 		if (memorystatus_testing_pid == 0) {
7026 			memorystatus_testing_pid = proc_getpid(caller);
7027 			error = 0;
7028 		} else if (memorystatus_testing_pid == proc_getpid(caller)) {
7029 			error = 0;
7030 		} else {
7031 			/* We don't allow ownership to be taken from another proc. */
7032 			error = EBUSY;
7033 		}
7034 	} else if (flags & MEMORYSTATUS_FLAGS_UNSET_TESTING_PID) {
7035 		if (memorystatus_testing_pid == proc_getpid(caller)) {
7036 			memorystatus_testing_pid = 0;
7037 			error = 0;
7038 		} else if (memorystatus_testing_pid != 0) {
7039 			/* We don't allow ownership to be taken from another proc. */
7040 			error = EPERM;
7041 		}
7042 	}
7043 	proc_list_unlock();
7044 
7045 	return error;
7046 }
7047 #endif /* DEVELOPMENT || DEBUG */
7048 
7049 /*
7050  *      Routine:	memorystatus_cmd_grp_set_priorities
7051  *	Purpose:	Update priorities for a group of processes.
7052  *
7053  *	[priority]
7054  *		Move each process out of its effective priority
7055  *		band and into a new priority band.
7056  *		Maintains relative order from lowest to highest priority.
7057  *		In single band, maintains relative order from head to tail.
7058  *
7059  *		eg: before	[effectivepriority | pid]
7060  *				[18 | p101              ]
7061  *				[17 | p55, p67, p19     ]
7062  *				[12 | p103 p10          ]
7063  *				[ 7 | p25               ]
7064  *			        [ 0 | p71, p82,         ]
7065  *
7066  *		after	[ new band | pid]
7067  *			[ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7068  *
7069  *	Returns:  0 on success, else non-zero.
7070  *
7071  *	Caveat:   We know there is a race window regarding recycled pids.
7072  *		  A process could be killed before the kernel can act on it here.
7073  *		  If a pid cannot be found in any of the jetsam priority bands,
7074  *		  then we simply ignore it.  No harm.
7075  *		  But, if the pid has been recycled then it could be an issue.
7076  *		  In that scenario, we might move an unsuspecting process to the new
7077  *		  priority band. It's not clear how the kernel can safeguard
7078  *		  against this, but it would be an extremely rare case anyway.
7079  *		  The caller of this api might avoid such race conditions by
7080  *		  ensuring that the processes passed in the pid list are suspended.
7081  */
7082 
7083 
7084 static int
7085 memorystatus_cmd_grp_set_priorities(user_addr_t buffer, size_t buffer_size)
7086 {
7087 	/*
7088 	 * We only handle setting priority
7089 	 * per process
7090 	 */
7091 
7092 	int error = 0;
7093 	memorystatus_properties_entry_v1_t *entries = NULL;
7094 	size_t entry_count = 0;
7095 
7096 	/* This will be the ordered proc list */
7097 	typedef struct memorystatus_internal_properties {
7098 		proc_t proc;
7099 		int32_t priority;
7100 	} memorystatus_internal_properties_t;
7101 
7102 	memorystatus_internal_properties_t *table = NULL;
7103 	uint32_t table_count = 0;
7104 
7105 	size_t i = 0;
7106 	uint32_t bucket_index = 0;
7107 	boolean_t head_insert;
7108 	int32_t new_priority;
7109 
7110 	proc_t p;
7111 
7112 	/* Verify inputs */
7113 	if ((buffer == USER_ADDR_NULL) || (buffer_size == 0)) {
7114 		error = EINVAL;
7115 		goto out;
7116 	}
7117 
7118 	entry_count = (buffer_size / sizeof(memorystatus_properties_entry_v1_t));
7119 	if (entry_count == 0) {
7120 		/* buffer size was not large enough for a single entry */
7121 		error = EINVAL;
7122 		goto out;
7123 	}
7124 
7125 	if ((entries = kalloc_data(buffer_size, Z_WAITOK)) == NULL) {
7126 		error = ENOMEM;
7127 		goto out;
7128 	}
7129 
7130 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_START, MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY, entry_count);
7131 
7132 	if ((error = copyin(buffer, entries, buffer_size)) != 0) {
7133 		goto out;
7134 	}
7135 
7136 	/* Verify sanity of input priorities */
7137 	if (entries[0].version == MEMORYSTATUS_MPE_VERSION_1) {
7138 		if ((buffer_size % MEMORYSTATUS_MPE_VERSION_1_SIZE) != 0) {
7139 			error = EINVAL;
7140 			goto out;
7141 		}
7142 	} else {
7143 		error = EINVAL;
7144 		goto out;
7145 	}
7146 
7147 	for (i = 0; i < entry_count; i++) {
7148 		if (entries[i].priority == -1) {
7149 			/* Use as shorthand for default priority */
7150 			entries[i].priority = JETSAM_PRIORITY_DEFAULT;
7151 		} else if (entries[i].priority > JETSAM_PRIORITY_IDLE && entries[i].priority <= applications_aging_band) {
7152 			/*
7153 			 * Everything between idle and the aging bands are reserved for internal use.
7154 			 * if requested, adjust to JETSAM_PRIORITY_IDLE.
7155 			 * Entitled processes (just munch) can use a subset of this range for testing.
7156 			 */
7157 			if (entries[i].priority > JETSAM_PRIORITY_ENTITLED_MAX ||
7158 			    !current_task_can_use_entitled_range()) {
7159 				entries[i].priority = JETSAM_PRIORITY_IDLE;
7160 			}
7161 		} else if (entries[i].priority == JETSAM_PRIORITY_IDLE_HEAD) {
7162 			/* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7163 			 * queue */
7164 			/* Deal with this later */
7165 		} else if ((entries[i].priority < 0) || (entries[i].priority >= MEMSTAT_BUCKET_COUNT)) {
7166 			/* Sanity check */
7167 			error = EINVAL;
7168 			goto out;
7169 		}
7170 	}
7171 
7172 	table = kalloc_type(memorystatus_internal_properties_t, entry_count,
7173 	    Z_WAITOK | Z_ZERO);
7174 	if (table == NULL) {
7175 		error = ENOMEM;
7176 		goto out;
7177 	}
7178 
7179 
7180 	/*
7181 	 * For each jetsam bucket entry, spin through the input property list.
7182 	 * When a matching pid is found, populate an adjacent table with the
7183 	 * appropriate proc pointer and new property values.
7184 	 * This traversal automatically preserves order from lowest
7185 	 * to highest priority.
7186 	 */
7187 
7188 	bucket_index = 0;
7189 
7190 	proc_list_lock();
7191 
7192 	/* Create the ordered table */
7193 	p = memorystatus_get_first_proc_locked(&bucket_index, TRUE);
7194 	while (p && (table_count < entry_count)) {
7195 		for (i = 0; i < entry_count; i++) {
7196 			if (proc_getpid(p) == entries[i].pid) {
7197 				/* Build the table data  */
7198 				table[table_count].proc = p;
7199 				table[table_count].priority = entries[i].priority;
7200 				table_count++;
7201 				break;
7202 			}
7203 		}
7204 		p = memorystatus_get_next_proc_locked(&bucket_index, p, TRUE);
7205 	}
7206 
7207 	/* We now have ordered list of procs ready to move */
7208 	for (i = 0; i < table_count; i++) {
7209 		p = table[i].proc;
7210 		assert(p != NULL);
7211 
7212 		/* Allow head inserts -- but relative order is now  */
7213 		if (table[i].priority == JETSAM_PRIORITY_IDLE_HEAD) {
7214 			new_priority = JETSAM_PRIORITY_IDLE;
7215 			head_insert = true;
7216 		} else {
7217 			new_priority = table[i].priority;
7218 			head_insert = false;
7219 		}
7220 
7221 		/* Not allowed */
7222 		if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
7223 			continue;
7224 		}
7225 
7226 		/*
7227 		 * Take appropriate steps if moving proc out of
7228 		 * either of the aging bands.
7229 		 */
7230 		if ((p->p_memstat_effectivepriority == system_procs_aging_band) || (p->p_memstat_effectivepriority == applications_aging_band)) {
7231 			memorystatus_invalidate_idle_demotion_locked(p, TRUE);
7232 		}
7233 
7234 		memorystatus_update_priority_locked(p, new_priority, head_insert, false);
7235 	}
7236 
7237 	proc_list_unlock();
7238 
7239 	/*
7240 	 * if (table_count != entry_count)
7241 	 * then some pids were not found in a jetsam band.
7242 	 * harmless but interesting...
7243 	 */
7244 out:
7245 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_END, MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY, entry_count, table_count);
7246 
7247 	kfree_data(entries, buffer_size);
7248 	kfree_type(memorystatus_internal_properties_t, entry_count, table);
7249 
7250 	return error;
7251 }
7252 
7253 memorystatus_internal_probabilities_t *memorystatus_global_probabilities_table = NULL;
7254 size_t memorystatus_global_probabilities_size = 0;
7255 
7256 static int
7257 memorystatus_cmd_grp_set_probabilities(user_addr_t buffer, size_t buffer_size)
7258 {
7259 	int error = 0;
7260 	memorystatus_properties_entry_v1_t *entries = NULL;
7261 	size_t entry_count = 0, i = 0;
7262 	memorystatus_internal_probabilities_t *tmp_table_new = NULL, *tmp_table_old = NULL;
7263 	size_t tmp_table_new_size = 0, tmp_table_old_size = 0;
7264 #if DEVELOPMENT || DEBUG
7265 	if (memorystatus_testing_pid != 0 && memorystatus_testing_pid != proc_getpid(current_proc())) {
7266 		/* probabilites are currently owned by someone else. Don't change them. */
7267 		error = EPERM;
7268 		goto out;
7269 	}
7270 #endif /* (DEVELOPMENT || DEBUG)*/
7271 
7272 	/* Verify inputs */
7273 	if ((buffer == USER_ADDR_NULL) || (buffer_size == 0)) {
7274 		error = EINVAL;
7275 		goto out;
7276 	}
7277 
7278 	entry_count = (buffer_size / sizeof(memorystatus_properties_entry_v1_t));
7279 	if (entry_count == 0) {
7280 		error = EINVAL;
7281 		goto out;
7282 	}
7283 
7284 	if ((entries = kalloc_data(buffer_size, Z_WAITOK)) == NULL) {
7285 		error = ENOMEM;
7286 		goto out;
7287 	}
7288 
7289 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_START, MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY, entry_count);
7290 
7291 	if ((error = copyin(buffer, entries, buffer_size)) != 0) {
7292 		goto out;
7293 	}
7294 
7295 	if (entries[0].version == MEMORYSTATUS_MPE_VERSION_1) {
7296 		if ((buffer_size % MEMORYSTATUS_MPE_VERSION_1_SIZE) != 0) {
7297 			error = EINVAL;
7298 			goto out;
7299 		}
7300 	} else {
7301 		error = EINVAL;
7302 		goto out;
7303 	}
7304 
7305 	/* Verify sanity of input priorities */
7306 	for (i = 0; i < entry_count; i++) {
7307 		/*
7308 		 * 0 - low probability of use.
7309 		 * 1 - high probability of use.
7310 		 *
7311 		 * Keeping this field an int (& not a bool) to allow
7312 		 * us to experiment with different values/approaches
7313 		 * later on.
7314 		 */
7315 		if (entries[i].use_probability > 1) {
7316 			error = EINVAL;
7317 			goto out;
7318 		}
7319 	}
7320 
7321 	tmp_table_new_size = sizeof(memorystatus_internal_probabilities_t) * entry_count;
7322 
7323 	if ((tmp_table_new = kalloc_data(tmp_table_new_size, Z_WAITOK | Z_ZERO)) == NULL) {
7324 		error = ENOMEM;
7325 		goto out;
7326 	}
7327 
7328 	proc_list_lock();
7329 
7330 	if (memorystatus_global_probabilities_table) {
7331 		tmp_table_old = memorystatus_global_probabilities_table;
7332 		tmp_table_old_size = memorystatus_global_probabilities_size;
7333 	}
7334 
7335 	memorystatus_global_probabilities_table = tmp_table_new;
7336 	memorystatus_global_probabilities_size = tmp_table_new_size;
7337 	tmp_table_new = NULL;
7338 
7339 	for (i = 0; i < entry_count; i++) {
7340 		/* Build the table data  */
7341 		strlcpy(memorystatus_global_probabilities_table[i].proc_name, entries[i].proc_name, MAXCOMLEN + 1);
7342 		memorystatus_global_probabilities_table[i].use_probability = entries[i].use_probability;
7343 	}
7344 
7345 	proc_list_unlock();
7346 
7347 out:
7348 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_END, MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY, entry_count, tmp_table_new_size);
7349 
7350 	kfree_data(entries, buffer_size);
7351 	kfree_data(tmp_table_old, tmp_table_old_size);
7352 
7353 	return error;
7354 }
7355 
7356 static int
7357 memorystatus_cmd_grp_set_properties(int32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7358 {
7359 	int error = 0;
7360 
7361 	if ((flags & MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY) == MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY) {
7362 		error = memorystatus_cmd_grp_set_priorities(buffer, buffer_size);
7363 	} else if ((flags & MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY) == MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY) {
7364 		error = memorystatus_cmd_grp_set_probabilities(buffer, buffer_size);
7365 #if CONFIG_FREEZE
7366 	} else if ((flags & MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY) == MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY) {
7367 		error = memorystatus_cmd_grp_set_freeze_list(buffer, buffer_size);
7368 	} else if ((flags & MEMORYSTATUS_FLAGS_GRP_SET_DEMOTE_PRIORITY) == MEMORYSTATUS_FLAGS_GRP_SET_DEMOTE_PRIORITY) {
7369 		error = memorystatus_cmd_grp_set_demote_list(buffer, buffer_size);
7370 #endif /* CONFIG_FREEZE */
7371 	} else {
7372 		error = EINVAL;
7373 	}
7374 
7375 	return error;
7376 }
7377 
7378 /*
7379  * This routine is used to update a process's jetsam priority position and stored user_data.
7380  * It is not used for the setting of memory limits, which is why the last 6 args to the
7381  * memorystatus_update() call are 0 or FALSE.
7382  *
7383  * Flags passed into this call are used to distinguish the motivation behind a jetsam priority
7384  * transition.  By default, the kernel updates the process's original requested priority when
7385  * no flag is passed.  But when the MEMORYSTATUS_SET_PRIORITY_ASSERTION flag is used, the kernel
7386  * updates the process's assertion driven priority.
7387  *
7388  * The assertion flag was introduced for use by the device's assertion mediator (eg: runningboardd).
7389  * When an assertion is controlling a process's jetsam priority, it may conflict with that process's
7390  * dirty/clean (active/inactive) jetsam state.  The kernel attempts to resolve a priority transition
7391  * conflict by reviewing the process state and then choosing the maximum jetsam band at play,
7392  * eg: requested priority versus assertion priority.
7393  */
7394 
7395 static int
7396 memorystatus_cmd_set_priority_properties(pid_t pid, uint32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7397 {
7398 	int error = 0;
7399 	boolean_t is_assertion = FALSE;         /* priority is driven by an assertion */
7400 	memorystatus_priority_properties_t mpp_entry;
7401 
7402 	/* Validate inputs */
7403 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_priority_properties_t))) {
7404 		return EINVAL;
7405 	}
7406 
7407 	/* Validate flags */
7408 	if (flags == 0) {
7409 		/*
7410 		 * Default. This path updates requestedpriority.
7411 		 */
7412 	} else {
7413 		if (flags & ~(MEMORYSTATUS_SET_PRIORITY_ASSERTION)) {
7414 			/*
7415 			 * Unsupported bit set in flag.
7416 			 */
7417 			return EINVAL;
7418 		} else if (flags & MEMORYSTATUS_SET_PRIORITY_ASSERTION) {
7419 			is_assertion = TRUE;
7420 		}
7421 	}
7422 
7423 	error = copyin(buffer, &mpp_entry, buffer_size);
7424 
7425 	if (error == 0) {
7426 		proc_t p;
7427 
7428 		p = proc_find(pid);
7429 		if (!p) {
7430 			return ESRCH;
7431 		}
7432 
7433 		if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
7434 			proc_rele(p);
7435 			return EPERM;
7436 		}
7437 
7438 		if (is_assertion) {
7439 			memorystatus_log_debug("memorystatus: set assertion priority(%d) target %s:%d\n",
7440 			    mpp_entry.priority, (*p->p_name ? p->p_name : "unknown"), proc_getpid(p));
7441 		}
7442 
7443 		error = memorystatus_update(p, mpp_entry.priority, mpp_entry.user_data, is_assertion, FALSE, FALSE, 0, 0, FALSE, FALSE);
7444 		proc_rele(p);
7445 	}
7446 
7447 	return error;
7448 }
7449 
7450 static int
7451 memorystatus_cmd_set_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7452 {
7453 	int error = 0;
7454 	memorystatus_memlimit_properties_t mmp_entry;
7455 
7456 	/* Validate inputs */
7457 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_memlimit_properties_t))) {
7458 		return EINVAL;
7459 	}
7460 
7461 	error = copyin(buffer, &mmp_entry, buffer_size);
7462 
7463 	if (error == 0) {
7464 		error = memorystatus_set_memlimit_properties(pid, &mmp_entry);
7465 	}
7466 
7467 	return error;
7468 }
7469 
7470 #if DEBUG || DEVELOPMENT
7471 static int
7472 memorystatus_cmd_set_diag_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7473 {
7474 	int error = 0;
7475 	memorystatus_diag_memlimit_properties_t mmp_entry;
7476 	proc_t p = proc_find(pid);
7477 	if (!p) {
7478 		return ESRCH;
7479 	}
7480 
7481 	/* Validate inputs */
7482 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_diag_memlimit_properties_t))) {
7483 		proc_rele(p);
7484 		return EINVAL;
7485 	}
7486 
7487 	error = copyin(buffer, &mmp_entry, buffer_size);
7488 
7489 	if (error == 0) {
7490 		proc_list_lock();
7491 		error = memorystatus_set_diag_memlimit_properties_internal(p, &mmp_entry);
7492 		proc_list_unlock();
7493 	}
7494 	proc_rele(p);
7495 	return error;
7496 }
7497 
7498 static int
7499 memorystatus_cmd_get_diag_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7500 {
7501 	int error = 0;
7502 	memorystatus_diag_memlimit_properties_t mmp_entry;
7503 	proc_t p = proc_find(pid);
7504 	if (!p) {
7505 		return ESRCH;
7506 	}
7507 
7508 	/* Validate inputs */
7509 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_diag_memlimit_properties_t))) {
7510 		proc_rele(p);
7511 		return EINVAL;
7512 	}
7513 	proc_list_lock();
7514 	error = memorystatus_get_diag_memlimit_properties_internal(p, &mmp_entry);
7515 	proc_list_unlock();
7516 	proc_rele(p);
7517 	if (error == 0) {
7518 		error = copyout(&mmp_entry, buffer, buffer_size);
7519 	}
7520 
7521 
7522 	return error;
7523 }
7524 #endif //DEBUG || DEVELOPMENT
7525 
7526 static void
7527 memorystatus_get_memlimit_properties_internal(proc_t p, memorystatus_memlimit_properties_t* p_entry)
7528 {
7529 	memset(p_entry, 0, sizeof(memorystatus_memlimit_properties_t));
7530 
7531 	if (p->p_memstat_memlimit_active > 0) {
7532 		p_entry->memlimit_active = p->p_memstat_memlimit_active;
7533 	} else {
7534 		task_convert_phys_footprint_limit(-1, &p_entry->memlimit_active);
7535 	}
7536 
7537 	if (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) {
7538 		p_entry->memlimit_active_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7539 	}
7540 
7541 	/*
7542 	 * Get the inactive limit and attributes
7543 	 */
7544 	if (p->p_memstat_memlimit_inactive <= 0) {
7545 		task_convert_phys_footprint_limit(-1, &p_entry->memlimit_inactive);
7546 	} else {
7547 		p_entry->memlimit_inactive = p->p_memstat_memlimit_inactive;
7548 	}
7549 	if (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) {
7550 		p_entry->memlimit_inactive_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7551 	}
7552 }
7553 
7554 /*
7555  * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7556  * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7557  * limits will be the same in the no-limit case.  Instead we convert limits <= 0 using
7558  * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7559  * to the task's ledgers via task_set_phys_footprint_limit().
7560  */
7561 static int
7562 memorystatus_cmd_get_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7563 {
7564 	memorystatus_memlimit_properties2_t mmp_entry;
7565 
7566 	/* Validate inputs */
7567 	if ((pid == 0) || (buffer == USER_ADDR_NULL) ||
7568 	    ((buffer_size != sizeof(memorystatus_memlimit_properties_t)) &&
7569 	    (buffer_size != sizeof(memorystatus_memlimit_properties2_t)))) {
7570 		return EINVAL;
7571 	}
7572 
7573 	memset(&mmp_entry, 0, sizeof(memorystatus_memlimit_properties2_t));
7574 
7575 	proc_t p = proc_find(pid);
7576 	if (!p) {
7577 		return ESRCH;
7578 	}
7579 
7580 	/*
7581 	 * Get the active limit and attributes.
7582 	 * No locks taken since we hold a reference to the proc.
7583 	 */
7584 
7585 	memorystatus_get_memlimit_properties_internal(p, &mmp_entry.v1);
7586 
7587 #if CONFIG_JETSAM
7588 #if DEVELOPMENT || DEBUG
7589 	/*
7590 	 * Get the limit increased via SPI
7591 	 */
7592 	mmp_entry.memlimit_increase = roundToNearestMB(p->p_memlimit_increase);
7593 	mmp_entry.memlimit_increase_bytes = p->p_memlimit_increase;
7594 #endif /* DEVELOPMENT || DEBUG */
7595 #endif /* CONFIG_JETSAM */
7596 
7597 	proc_rele(p);
7598 
7599 	int error = copyout(&mmp_entry, buffer, buffer_size);
7600 
7601 	return error;
7602 }
7603 
7604 
7605 /*
7606  * SPI for kbd - pr24956468
7607  * This is a very simple snapshot that calculates how much a
7608  * process's phys_footprint exceeds a specific memory limit.
7609  * Only the inactive memory limit is supported for now.
7610  * The delta is returned as bytes in excess or zero.
7611  */
7612 static int
7613 memorystatus_cmd_get_memlimit_excess_np(pid_t pid, uint32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval)
7614 {
7615 	int error = 0;
7616 	uint64_t footprint_in_bytes = 0;
7617 	uint64_t delta_in_bytes = 0;
7618 	int32_t  memlimit_mb = 0;
7619 	uint64_t memlimit_bytes = 0;
7620 
7621 	/* Validate inputs */
7622 	if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(uint64_t)) || (flags != 0)) {
7623 		return EINVAL;
7624 	}
7625 
7626 	proc_t p = proc_find(pid);
7627 	if (!p) {
7628 		return ESRCH;
7629 	}
7630 
7631 	/*
7632 	 * Get the inactive limit.
7633 	 * No locks taken since we hold a reference to the proc.
7634 	 */
7635 
7636 	if (p->p_memstat_memlimit_inactive <= 0) {
7637 		task_convert_phys_footprint_limit(-1, &memlimit_mb);
7638 	} else {
7639 		memlimit_mb = p->p_memstat_memlimit_inactive;
7640 	}
7641 
7642 	footprint_in_bytes = get_task_phys_footprint(proc_task(p));
7643 
7644 	proc_rele(p);
7645 
7646 	memlimit_bytes = memlimit_mb * 1024 * 1024;     /* MB to bytes */
7647 
7648 	/*
7649 	 * Computed delta always returns >= 0 bytes
7650 	 */
7651 	if (footprint_in_bytes > memlimit_bytes) {
7652 		delta_in_bytes = footprint_in_bytes - memlimit_bytes;
7653 	}
7654 
7655 	error = copyout(&delta_in_bytes, buffer, sizeof(delta_in_bytes));
7656 
7657 	return error;
7658 }
7659 
7660 
7661 static int
7662 memorystatus_cmd_get_pressure_status(int32_t *retval)
7663 {
7664 	int error;
7665 
7666 	/* Need privilege for check */
7667 	error = priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE, 0);
7668 	if (error) {
7669 		return error;
7670 	}
7671 
7672 	/* Inherently racy, so it's not worth taking a lock here */
7673 	*retval = (kVMPressureNormal != memorystatus_vm_pressure_level) ? 1 : 0;
7674 
7675 	return error;
7676 }
7677 
7678 int
7679 memorystatus_get_pressure_status_kdp()
7680 {
7681 	return (kVMPressureNormal != memorystatus_vm_pressure_level) ? 1 : 0;
7682 }
7683 
7684 /*
7685  * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
7686  *
7687  * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
7688  * So, with 2-level HWM preserving previous behavior will map as follows.
7689  *      - treat the limit passed in as both an active and inactive limit.
7690  *      - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
7691  *
7692  * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
7693  *      - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
7694  *      - so mapping is (active/non-fatal, inactive/non-fatal)
7695  *
7696  * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
7697  *      - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
7698  *      - so mapping is (active/fatal, inactive/fatal)
7699  */
7700 
7701 #if CONFIG_JETSAM
7702 static int
7703 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid, int32_t high_water_mark, __unused int32_t *retval, boolean_t is_fatal_limit)
7704 {
7705 	int error = 0;
7706 	memorystatus_memlimit_properties_t entry;
7707 
7708 	entry.memlimit_active = high_water_mark;
7709 	entry.memlimit_active_attr = 0;
7710 	entry.memlimit_inactive = high_water_mark;
7711 	entry.memlimit_inactive_attr = 0;
7712 
7713 	if (is_fatal_limit == TRUE) {
7714 		entry.memlimit_active_attr   |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7715 		entry.memlimit_inactive_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7716 	}
7717 
7718 	error = memorystatus_set_memlimit_properties(pid, &entry);
7719 	return error;
7720 }
7721 
7722 static int
7723 memorystatus_cmd_mark_process_coalition_swappable(pid_t pid, __unused int32_t *retval)
7724 {
7725 	int error = 0;
7726 	proc_t p = PROC_NULL;
7727 	coalition_t coal = COALITION_NULL;
7728 
7729 	if (!memorystatus_swap_all_apps) {
7730 		/* Swap is not supported on this device. */
7731 		return ENOTSUP;
7732 	}
7733 	p = proc_find(pid);
7734 	if (!p) {
7735 		return ESRCH;
7736 	}
7737 	coal = task_get_coalition((task_t) proc_task(p), COALITION_TYPE_JETSAM);
7738 	if (coal && coalition_is_leader((task_t) proc_task(p), coal)) {
7739 		coalition_mark_swappable(coal);
7740 	} else {
7741 		/* This SPI is only supported on coalition leaders. */
7742 		error = EINVAL;
7743 	}
7744 
7745 	proc_rele(p);
7746 	return error;
7747 }
7748 
7749 static int
7750 memorystatus_cmd_get_process_coalition_is_swappable(pid_t pid, int32_t *retval)
7751 {
7752 	int error = 0;
7753 	proc_t p = PROC_NULL;
7754 	coalition_t coal = COALITION_NULL;
7755 
7756 	if (!memorystatus_swap_all_apps) {
7757 		/* Swap is not supported on this device. */
7758 		return ENOTSUP;
7759 	}
7760 	p = proc_find(pid);
7761 	if (!p) {
7762 		return ESRCH;
7763 	}
7764 	coal = task_get_coalition((task_t) proc_task(p), COALITION_TYPE_JETSAM);
7765 	if (coal) {
7766 		*retval = coalition_is_swappable(coal);
7767 	} else {
7768 		error = EINVAL;
7769 	}
7770 
7771 	proc_rele(p);
7772 	return error;
7773 }
7774 
7775 static int
7776 memorystatus_cmd_convert_memlimit_mb(pid_t pid, int32_t limit, int32_t *retval)
7777 {
7778 	int error = 0;
7779 	proc_t p;
7780 	p = proc_find(pid);
7781 	if (!p) {
7782 		return ESRCH;
7783 	}
7784 	if (limit <= 0) {
7785 		/*
7786 		 * A limit of <= 0 implies that the task gets its default limit.
7787 		 */
7788 		limit = memorystatus_get_default_task_active_limit(p);
7789 		if (limit <= 0) {
7790 			/* Task uses system wide default limit */
7791 			limit = max_task_footprint_mb ? max_task_footprint_mb : INT32_MAX;
7792 		}
7793 		*retval = limit;
7794 	} else {
7795 #if DEVELOPMENT || DEBUG
7796 		/* add the current increase to it, for roots */
7797 		limit += roundToNearestMB(p->p_memlimit_increase);
7798 #endif /* DEVELOPMENT || DEBUG */
7799 		*retval = limit;
7800 	}
7801 
7802 	proc_rele(p);
7803 	return error;
7804 }
7805 #endif /* CONFIG_JETSAM */
7806 
7807 static int
7808 memorystatus_set_memlimit_properties_internal(proc_t p, memorystatus_memlimit_properties_t *p_entry)
7809 {
7810 	int error = 0;
7811 
7812 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
7813 
7814 	/*
7815 	 * Store the active limit variants in the proc.
7816 	 */
7817 	SET_ACTIVE_LIMITS_LOCKED(p, p_entry->memlimit_active, p_entry->memlimit_active_attr);
7818 
7819 	/*
7820 	 * Store the inactive limit variants in the proc.
7821 	 */
7822 	SET_INACTIVE_LIMITS_LOCKED(p, p_entry->memlimit_inactive, p_entry->memlimit_inactive_attr);
7823 
7824 	/*
7825 	 * Enforce appropriate limit variant by updating the cached values
7826 	 * and writing the ledger.
7827 	 * Limit choice is based on process active/inactive state.
7828 	 */
7829 
7830 	if (memorystatus_highwater_enabled) {
7831 		boolean_t is_fatal;
7832 		boolean_t use_active;
7833 
7834 		if (proc_jetsam_state_is_active_locked(p) == TRUE) {
7835 			CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
7836 			use_active = TRUE;
7837 		} else {
7838 			CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
7839 			use_active = FALSE;
7840 		}
7841 
7842 		/* Enforce the limit by writing to the ledgers */
7843 		error = (task_set_phys_footprint_limit_internal(proc_task(p), ((p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1), NULL, use_active, is_fatal) == 0) ? 0 : EINVAL;
7844 
7845 		memorystatus_log_info(
7846 			"memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
7847 			proc_getpid(p), (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
7848 			(p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, p->p_memstat_dirty,
7849 			(p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
7850 		DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit, proc_t, p, int32_t, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1));
7851 	}
7852 
7853 	return error;
7854 }
7855 
7856 #if DEBUG || DEVELOPMENT
7857 static int
7858 memorystatus_set_diag_memlimit_properties_internal(proc_t p, memorystatus_diag_memlimit_properties_t *p_entry)
7859 {
7860 	int error = 0;
7861 	uint64_t old_limit = 0;
7862 
7863 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
7864 	/* Enforce the limit by writing to the ledgers */
7865 	error = (task_set_diag_footprint_limit_internal(proc_task(p), p_entry->memlimit, &old_limit) == KERN_SUCCESS) ? KERN_SUCCESS : EINVAL;
7866 
7867 	memorystatus_log_debug( "memorystatus_set_diag_memlimit_properties: new limit on pid %d (%lluMB old %lluMB)\n",
7868 	    proc_getpid(p), (p_entry->memlimit > 0 ? p_entry->memlimit : -1), (old_limit)
7869 	    );
7870 	DTRACE_MEMORYSTATUS2(memorystatus_diag_memlimit_properties_t, proc_t, p, int32_t, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1));
7871 	return error;
7872 }
7873 
7874 static int
7875 memorystatus_get_diag_memlimit_properties_internal(proc_t p, memorystatus_diag_memlimit_properties_t *p_entry)
7876 {
7877 	int error = 0;
7878 	/* Enforce the limit by writing to the ledgers */
7879 	error = (task_get_diag_footprint_limit_internal(proc_task(p), &p_entry->memlimit, &p_entry->threshold_enabled) == KERN_SUCCESS) ? KERN_SUCCESS : EINVAL;
7880 
7881 	DTRACE_MEMORYSTATUS2(memorystatus_diag_memlimit_properties_t, proc_t, p, int32_t, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1));
7882 	return error;
7883 }
7884 #endif // DEBUG || DEVELOPMENT
7885 
7886 bool
7887 memorystatus_task_has_increased_memory_limit_entitlement(task_t task)
7888 {
7889 	static const char kIncreasedMemoryLimitEntitlement[] = "com.apple.developer.kernel.increased-memory-limit";
7890 	if (memorystatus_entitled_max_task_footprint_mb == 0) {
7891 		// Entitlement is not supported on this device.
7892 		return false;
7893 	}
7894 
7895 	return IOTaskHasEntitlement(task, kIncreasedMemoryLimitEntitlement);
7896 }
7897 
7898 bool
7899 memorystatus_task_has_legacy_footprint_entitlement(task_t task)
7900 {
7901 	return IOTaskHasEntitlement(task, "com.apple.private.memory.legacy_footprint");
7902 }
7903 
7904 bool
7905 memorystatus_task_has_ios13extended_footprint_limit(task_t task)
7906 {
7907 	if (max_mem < 1500ULL * 1024 * 1024 ||
7908 	    max_mem > 2ULL * 1024 * 1024 * 1024) {
7909 		/* ios13extended_footprint is only for 2GB devices */
7910 		return false;
7911 	}
7912 	return IOTaskHasEntitlement(task, "com.apple.developer.memory.ios13extended_footprint");
7913 }
7914 
7915 static int32_t
7916 memorystatus_get_default_task_active_limit(proc_t p)
7917 {
7918 	bool entitled = memorystatus_task_has_increased_memory_limit_entitlement(proc_task(p));
7919 	int32_t limit = -1;
7920 
7921 	/*
7922 	 * Check for the various entitlement footprint hacks
7923 	 * and try to apply each one. Note that if multiple entitlements are present
7924 	 * whichever results in the largest limit applies.
7925 	 */
7926 	if (entitled) {
7927 		limit = MAX(limit, memorystatus_entitled_max_task_footprint_mb);
7928 	}
7929 #if __arm64__
7930 	if (legacy_footprint_entitlement_mode == LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE &&
7931 	    memorystatus_task_has_legacy_footprint_entitlement(proc_task(p))) {
7932 		limit = MAX(limit, max_task_footprint_mb + legacy_footprint_bonus_mb);
7933 	}
7934 #endif /* __arm64__ */
7935 	if (memorystatus_task_has_ios13extended_footprint_limit(proc_task(p))) {
7936 		limit = MAX(limit, memorystatus_ios13extended_footprint_limit_mb);
7937 	}
7938 
7939 	return limit;
7940 }
7941 
7942 static int32_t
7943 memorystatus_get_default_task_inactive_limit(proc_t p)
7944 {
7945 	// Currently the default active and inactive limits are always the same.
7946 	return memorystatus_get_default_task_active_limit(p);
7947 }
7948 
7949 static int
7950 memorystatus_set_memlimit_properties(pid_t pid, memorystatus_memlimit_properties_t *entry)
7951 {
7952 	memorystatus_memlimit_properties_t set_entry;
7953 
7954 	proc_t p = proc_find(pid);
7955 	if (!p) {
7956 		return ESRCH;
7957 	}
7958 
7959 	/*
7960 	 * Check for valid attribute flags.
7961 	 */
7962 	const uint32_t valid_attrs = MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7963 	if ((entry->memlimit_active_attr & (~valid_attrs)) != 0) {
7964 		proc_rele(p);
7965 		return EINVAL;
7966 	}
7967 	if ((entry->memlimit_inactive_attr & (~valid_attrs)) != 0) {
7968 		proc_rele(p);
7969 		return EINVAL;
7970 	}
7971 
7972 	/*
7973 	 * Setup the active memlimit properties
7974 	 */
7975 	set_entry.memlimit_active = entry->memlimit_active;
7976 	set_entry.memlimit_active_attr = entry->memlimit_active_attr & MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7977 
7978 	/*
7979 	 * Setup the inactive memlimit properties
7980 	 */
7981 	set_entry.memlimit_inactive = entry->memlimit_inactive;
7982 	set_entry.memlimit_inactive_attr = entry->memlimit_inactive_attr & MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7983 
7984 	/*
7985 	 * Setting a limit of <= 0 implies that the process has no
7986 	 * high-water-mark and has no per-task-limit.  That means
7987 	 * the system_wide task limit is in place, which by the way,
7988 	 * is always fatal.
7989 	 */
7990 
7991 	if (set_entry.memlimit_active <= 0) {
7992 		/*
7993 		 * Enforce the fatal system_wide task limit while process is active.
7994 		 */
7995 		set_entry.memlimit_active = memorystatus_get_default_task_active_limit(p);
7996 		set_entry.memlimit_active_attr = MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7997 	}
7998 #if CONFIG_JETSAM
7999 #if DEVELOPMENT || DEBUG
8000 	else {
8001 		/* add the current increase to it, for roots */
8002 		set_entry.memlimit_active += roundToNearestMB(p->p_memlimit_increase);
8003 	}
8004 #endif /* DEVELOPMENT || DEBUG */
8005 #endif /* CONFIG_JETSAM */
8006 
8007 	if (set_entry.memlimit_inactive <= 0) {
8008 		/*
8009 		 * Enforce the fatal system_wide task limit while process is inactive.
8010 		 */
8011 		set_entry.memlimit_inactive = memorystatus_get_default_task_inactive_limit(p);
8012 		set_entry.memlimit_inactive_attr = MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
8013 	}
8014 #if CONFIG_JETSAM
8015 #if DEVELOPMENT || DEBUG
8016 	else {
8017 		/* add the current increase to it, for roots */
8018 		set_entry.memlimit_inactive += roundToNearestMB(p->p_memlimit_increase);
8019 	}
8020 #endif /* DEVELOPMENT || DEBUG */
8021 #endif /* CONFIG_JETSAM */
8022 
8023 	proc_list_lock();
8024 
8025 	int error = memorystatus_set_memlimit_properties_internal(p, &set_entry);
8026 
8027 	proc_list_unlock();
8028 	proc_rele(p);
8029 
8030 	return error;
8031 }
8032 
8033 /*
8034  * Returns the jetsam priority (effective or requested) of the process
8035  * associated with this task.
8036  */
8037 int
8038 proc_get_memstat_priority(proc_t p, boolean_t effective_priority)
8039 {
8040 	if (p) {
8041 		if (effective_priority) {
8042 			return p->p_memstat_effectivepriority;
8043 		} else {
8044 			return p->p_memstat_requestedpriority;
8045 		}
8046 	}
8047 	return 0;
8048 }
8049 
8050 static int
8051 memorystatus_get_process_is_managed(pid_t pid, int *is_managed)
8052 {
8053 	proc_t p = NULL;
8054 
8055 	/* Validate inputs */
8056 	if (pid == 0) {
8057 		return EINVAL;
8058 	}
8059 
8060 	p = proc_find(pid);
8061 	if (!p) {
8062 		return ESRCH;
8063 	}
8064 
8065 	proc_list_lock();
8066 	*is_managed = ((p->p_memstat_state & P_MEMSTAT_MANAGED) ? 1 : 0);
8067 	proc_rele(p);
8068 	proc_list_unlock();
8069 
8070 	return 0;
8071 }
8072 
8073 static int
8074 memorystatus_set_process_is_managed(pid_t pid, boolean_t set_managed)
8075 {
8076 	proc_t p = NULL;
8077 
8078 	/* Validate inputs */
8079 	if (pid == 0) {
8080 		return EINVAL;
8081 	}
8082 
8083 	p = proc_find(pid);
8084 	if (!p) {
8085 		return ESRCH;
8086 	}
8087 
8088 	proc_list_lock();
8089 	if (set_managed == TRUE) {
8090 		p->p_memstat_state |= P_MEMSTAT_MANAGED;
8091 		/*
8092 		 * The P_MEMSTAT_MANAGED bit is set by Runningboard for Apps.
8093 		 * Also opt them in to being frozen (they might have started
8094 		 * off with the P_MEMSTAT_FREEZE_DISABLED bit set.)
8095 		 */
8096 		p->p_memstat_state &= ~P_MEMSTAT_FREEZE_DISABLED;
8097 	} else {
8098 		p->p_memstat_state &= ~P_MEMSTAT_MANAGED;
8099 	}
8100 	proc_list_unlock();
8101 
8102 	proc_rele(p);
8103 
8104 	return 0;
8105 }
8106 
8107 int
8108 memorystatus_control(struct proc *p, struct memorystatus_control_args *args, int *ret)
8109 {
8110 	int error = EINVAL;
8111 	boolean_t skip_auth_check = FALSE;
8112 	os_reason_t jetsam_reason = OS_REASON_NULL;
8113 
8114 #if !CONFIG_JETSAM
8115     #pragma unused(ret)
8116     #pragma unused(jetsam_reason)
8117 #endif
8118 
8119 	/* We don't need entitlements if we're setting / querying the freeze preference or frozen status for a process. */
8120 	if (args->command == MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE ||
8121 	    args->command == MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE ||
8122 	    args->command == MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN) {
8123 		skip_auth_check = TRUE;
8124 	}
8125 
8126 	/*
8127 	 * On development kernel, we don't need entitlements if we're adjusting the limit.
8128 	 * This required for limit adjustment by dyld when roots are detected, see rdar://99669958
8129 	 */
8130 #if DEVELOPMENT || DEBUG
8131 	if (args->command == MEMORYSTATUS_CMD_INCREASE_JETSAM_TASK_LIMIT && proc_getpid(p) == args->pid) {
8132 		skip_auth_check = TRUE;
8133 	}
8134 #endif /* DEVELOPMENT || DEBUG */
8135 
8136 	/* Need to be root or have entitlement. */
8137 	if (!kauth_cred_issuser(kauth_cred_get()) && !IOCurrentTaskHasEntitlement(MEMORYSTATUS_ENTITLEMENT) && !skip_auth_check) {
8138 		error = EPERM;
8139 		goto out;
8140 	}
8141 
8142 	/*
8143 	 * Sanity check.
8144 	 * Do not enforce it for snapshots.
8145 	 */
8146 	if (args->command != MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT) {
8147 		if (args->buffersize > MEMORYSTATUS_BUFFERSIZE_MAX) {
8148 			error = EINVAL;
8149 			goto out;
8150 		}
8151 	}
8152 
8153 #if CONFIG_MACF
8154 	error = mac_proc_check_memorystatus_control(p, args->command, args->pid);
8155 	if (error) {
8156 		goto out;
8157 	}
8158 #endif /* MAC */
8159 
8160 	switch (args->command) {
8161 	case MEMORYSTATUS_CMD_GET_PRIORITY_LIST:
8162 		error = memorystatus_cmd_get_priority_list(args->pid, args->buffer, args->buffersize, ret);
8163 		break;
8164 	case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES:
8165 		error = memorystatus_cmd_set_priority_properties(args->pid, args->flags, args->buffer, args->buffersize, ret);
8166 		break;
8167 	case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES:
8168 		error = memorystatus_cmd_set_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
8169 		break;
8170 	case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES:
8171 		error = memorystatus_cmd_get_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
8172 		break;
8173 	case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS:
8174 		error = memorystatus_cmd_get_memlimit_excess_np(args->pid, args->flags, args->buffer, args->buffersize, ret);
8175 		break;
8176 	case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES:
8177 		error = memorystatus_cmd_grp_set_properties((int32_t)args->flags, args->buffer, args->buffersize, ret);
8178 		break;
8179 	case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT:
8180 		error = memorystatus_cmd_get_jetsam_snapshot((int32_t)args->flags, args->buffer, args->buffersize, ret);
8181 		break;
8182 #if DEVELOPMENT || DEBUG
8183 	case MEMORYSTATUS_CMD_SET_TESTING_PID:
8184 		error = memorystatus_cmd_set_testing_pid((int32_t) args->flags);
8185 		break;
8186 #endif
8187 	case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS:
8188 		error = memorystatus_cmd_get_pressure_status(ret);
8189 		break;
8190 #if CONFIG_JETSAM
8191 	case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK:
8192 		/*
8193 		 * This call does not distinguish between active and inactive limits.
8194 		 * Default behavior in 2-level HWM world is to set both.
8195 		 * Non-fatal limit is also assumed for both.
8196 		 */
8197 		error = memorystatus_cmd_set_jetsam_memory_limit(args->pid, (int32_t)args->flags, ret, FALSE);
8198 		break;
8199 	case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT:
8200 		/*
8201 		 * This call does not distinguish between active and inactive limits.
8202 		 * Default behavior in 2-level HWM world is to set both.
8203 		 * Fatal limit is also assumed for both.
8204 		 */
8205 		error = memorystatus_cmd_set_jetsam_memory_limit(args->pid, (int32_t)args->flags, ret, TRUE);
8206 		break;
8207 	case MEMORYSTATUS_CMD_MARK_PROCESS_COALITION_SWAPPABLE:
8208 		error = memorystatus_cmd_mark_process_coalition_swappable(args->pid, ret);
8209 		break;
8210 
8211 	case MEMORYSTATUS_CMD_GET_PROCESS_COALITION_IS_SWAPPABLE:
8212 		error = memorystatus_cmd_get_process_coalition_is_swappable(args->pid, ret);
8213 		break;
8214 
8215 	case MEMORYSTATUS_CMD_CONVERT_MEMLIMIT_MB:
8216 		error = memorystatus_cmd_convert_memlimit_mb(args->pid, (int32_t) args->flags, ret);
8217 		break;
8218 #endif /* CONFIG_JETSAM */
8219 		/* Test commands */
8220 #if DEVELOPMENT || DEBUG
8221 	case MEMORYSTATUS_CMD_TEST_JETSAM:
8222 		jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_GENERIC);
8223 		if (jetsam_reason == OS_REASON_NULL) {
8224 			memorystatus_log_error("memorystatus_control: failed to allocate jetsam reason\n");
8225 		}
8226 
8227 		error = memorystatus_kill_process_sync(args->pid, kMemorystatusKilled, jetsam_reason) ? 0 : EINVAL;
8228 		break;
8229 	case MEMORYSTATUS_CMD_TEST_JETSAM_SORT:
8230 		error = memorystatus_cmd_test_jetsam_sort(args->pid, (int32_t)args->flags, args->buffer, args->buffersize);
8231 		break;
8232 #else /* DEVELOPMENT || DEBUG */
8233 	#pragma unused(jetsam_reason)
8234 #endif /* DEVELOPMENT || DEBUG */
8235 	case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE:
8236 		if (memorystatus_aggressive_jetsam_lenient_allowed == FALSE) {
8237 #if DEVELOPMENT || DEBUG
8238 			memorystatus_log_info("Enabling Lenient Mode\n");
8239 #endif /* DEVELOPMENT || DEBUG */
8240 
8241 			memorystatus_aggressive_jetsam_lenient_allowed = TRUE;
8242 			memorystatus_aggressive_jetsam_lenient = TRUE;
8243 			error = 0;
8244 		}
8245 		break;
8246 	case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE:
8247 #if DEVELOPMENT || DEBUG
8248 		memorystatus_log_info("Disabling Lenient mode\n");
8249 #endif /* DEVELOPMENT || DEBUG */
8250 		memorystatus_aggressive_jetsam_lenient_allowed = FALSE;
8251 		memorystatus_aggressive_jetsam_lenient = FALSE;
8252 		error = 0;
8253 		break;
8254 	case MEMORYSTATUS_CMD_GET_AGGRESSIVE_JETSAM_LENIENT_MODE:
8255 		*ret = (memorystatus_aggressive_jetsam_lenient ? 1 : 0);
8256 		error = 0;
8257 		break;
8258 	case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE:
8259 	case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE:
8260 		error = memorystatus_low_mem_privileged_listener(args->command);
8261 		break;
8262 
8263 	case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE:
8264 	case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE:
8265 		error = memorystatus_update_inactive_jetsam_priority_band(args->pid, args->command, JETSAM_PRIORITY_ELEVATED_INACTIVE, args->flags ? TRUE : FALSE);
8266 		break;
8267 	case MEMORYSTATUS_CMD_SET_PROCESS_IS_MANAGED:
8268 		error = memorystatus_set_process_is_managed(args->pid, args->flags);
8269 		break;
8270 
8271 	case MEMORYSTATUS_CMD_GET_PROCESS_IS_MANAGED:
8272 		error = memorystatus_get_process_is_managed(args->pid, ret);
8273 		break;
8274 
8275 #if CONFIG_FREEZE
8276 	case MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE:
8277 		error = memorystatus_set_process_is_freezable(args->pid, args->flags ? TRUE : FALSE);
8278 		break;
8279 
8280 	case MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE:
8281 		error = memorystatus_get_process_is_freezable(args->pid, ret);
8282 		break;
8283 	case MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN:
8284 		error = memorystatus_get_process_is_frozen(args->pid, ret);
8285 		break;
8286 
8287 	case MEMORYSTATUS_CMD_FREEZER_CONTROL:
8288 		error = memorystatus_freezer_control(args->flags, args->buffer, args->buffersize, ret);
8289 		break;
8290 #endif /* CONFIG_FREEZE */
8291 
8292 #if DEVELOPMENT || DEBUG
8293 	case MEMORYSTATUS_CMD_INCREASE_JETSAM_TASK_LIMIT:
8294 		error = memorystatus_cmd_increase_jetsam_task_limit(args->pid, args->flags);
8295 		break;
8296 	case MEMORYSTATUS_CMD_SET_DIAG_LIMIT:
8297 		error = memorystatus_cmd_set_diag_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
8298 		break;
8299 	case MEMORYSTATUS_CMD_GET_DIAG_LIMIT:
8300 		error = memorystatus_cmd_get_diag_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
8301 		break;
8302 #endif /* DEVELOPMENT || DEBUG */
8303 
8304 	default:
8305 		error = EINVAL;
8306 		break;
8307 	}
8308 
8309 out:
8310 	return error;
8311 }
8312 
8313 /* Coalition support */
8314 
8315 /* sorting info for a particular priority bucket */
8316 typedef struct memstat_sort_info {
8317 	coalition_t     msi_coal;
8318 	uint64_t        msi_page_count;
8319 	pid_t           msi_pid;
8320 	int             msi_ntasks;
8321 } memstat_sort_info_t;
8322 
8323 /*
8324  * qsort from smallest page count to largest page count
8325  *
8326  * return < 0 for a < b
8327  *          0 for a == b
8328  *        > 0 for a > b
8329  */
8330 static int
8331 memstat_asc_cmp(const void *a, const void *b)
8332 {
8333 	const memstat_sort_info_t *msA = (const memstat_sort_info_t *)a;
8334 	const memstat_sort_info_t *msB = (const memstat_sort_info_t *)b;
8335 
8336 	return (int)((uint64_t)msA->msi_page_count - (uint64_t)msB->msi_page_count);
8337 }
8338 
8339 /*
8340  * Return the number of pids rearranged during this sort.
8341  */
8342 static int
8343 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index, int coal_sort_order)
8344 {
8345 #define MAX_SORT_PIDS           80
8346 #define MAX_COAL_LEADERS        10
8347 
8348 	unsigned int b = bucket_index;
8349 	int nleaders = 0;
8350 	int ntasks = 0;
8351 	proc_t p = NULL;
8352 	coalition_t coal = COALITION_NULL;
8353 	int pids_moved = 0;
8354 	int total_pids_moved = 0;
8355 	int i;
8356 
8357 	/*
8358 	 * The system is typically under memory pressure when in this
8359 	 * path, hence, we want to avoid dynamic memory allocation.
8360 	 */
8361 	memstat_sort_info_t leaders[MAX_COAL_LEADERS];
8362 	pid_t pid_list[MAX_SORT_PIDS];
8363 
8364 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
8365 		return 0;
8366 	}
8367 
8368 	/*
8369 	 * Clear the array that holds coalition leader information
8370 	 */
8371 	for (i = 0; i < MAX_COAL_LEADERS; i++) {
8372 		leaders[i].msi_coal = COALITION_NULL;
8373 		leaders[i].msi_page_count = 0;          /* will hold total coalition page count */
8374 		leaders[i].msi_pid = 0;                 /* will hold coalition leader pid */
8375 		leaders[i].msi_ntasks = 0;              /* will hold the number of tasks in a coalition */
8376 	}
8377 
8378 	p = memorystatus_get_first_proc_locked(&b, FALSE);
8379 	while (p) {
8380 		coal = task_get_coalition(proc_task(p), COALITION_TYPE_JETSAM);
8381 		if (coalition_is_leader(proc_task(p), coal)) {
8382 			if (nleaders < MAX_COAL_LEADERS) {
8383 				int coal_ntasks = 0;
8384 				uint64_t coal_page_count = coalition_get_page_count(coal, &coal_ntasks);
8385 				leaders[nleaders].msi_coal = coal;
8386 				leaders[nleaders].msi_page_count = coal_page_count;
8387 				leaders[nleaders].msi_pid = proc_getpid(p);           /* the coalition leader */
8388 				leaders[nleaders].msi_ntasks = coal_ntasks;
8389 				nleaders++;
8390 			} else {
8391 				/*
8392 				 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8393 				 * Abandoned coalitions will linger at the tail of the priority band
8394 				 * when this sort session ends.
8395 				 * TODO:  should this be an assert?
8396 				 */
8397 				memorystatus_log_error(
8398 					"%s: WARNING: more than %d leaders in priority band [%d]\n",
8399 					__FUNCTION__, MAX_COAL_LEADERS, bucket_index);
8400 				break;
8401 			}
8402 		}
8403 		p = memorystatus_get_next_proc_locked(&b, p, FALSE);
8404 	}
8405 
8406 	if (nleaders == 0) {
8407 		/* Nothing to sort */
8408 		return 0;
8409 	}
8410 
8411 	/*
8412 	 * Sort the coalition leader array, from smallest coalition page count
8413 	 * to largest coalition page count.  When inserted in the priority bucket,
8414 	 * smallest coalition is handled first, resulting in the last to be jetsammed.
8415 	 */
8416 	if (nleaders > 1) {
8417 		qsort(leaders, nleaders, sizeof(memstat_sort_info_t), memstat_asc_cmp);
8418 	}
8419 
8420 #if 0
8421 	for (i = 0; i < nleaders; i++) {
8422 		printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8423 		    __FUNCTION__, i, nleaders, leaders[i].msi_pid, leaders[i].msi_page_count,
8424 		    leaders[i].msi_ntasks);
8425 	}
8426 #endif
8427 
8428 	/*
8429 	 * During coalition sorting, processes in a priority band are rearranged
8430 	 * by being re-inserted at the head of the queue.  So, when handling a
8431 	 * list, the first process that gets moved to the head of the queue,
8432 	 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8433 	 *
8434 	 * So, for example, the coalition leader is expected to jetsam last,
8435 	 * after its coalition members.  Therefore, the coalition leader is
8436 	 * inserted at the head of the queue first.
8437 	 *
8438 	 * After processing a coalition, the jetsam order is as follows:
8439 	 *   undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8440 	 */
8441 
8442 	/*
8443 	 * Coalition members are rearranged in the priority bucket here,
8444 	 * based on their coalition role.
8445 	 */
8446 	total_pids_moved = 0;
8447 	for (i = 0; i < nleaders; i++) {
8448 		/* a bit of bookkeeping */
8449 		pids_moved = 0;
8450 
8451 		/* Coalition leaders are jetsammed last, so move into place first */
8452 		pid_list[0] = leaders[i].msi_pid;
8453 		pids_moved += memorystatus_move_list_locked(bucket_index, pid_list, 1);
8454 
8455 		/* xpc services should jetsam after extensions */
8456 		ntasks = coalition_get_pid_list(leaders[i].msi_coal, COALITION_ROLEMASK_XPC,
8457 		    coal_sort_order, pid_list, MAX_SORT_PIDS);
8458 
8459 		if (ntasks > 0) {
8460 			pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8461 			    (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8462 		}
8463 
8464 		/* extensions should jetsam after unmarked processes */
8465 		ntasks = coalition_get_pid_list(leaders[i].msi_coal, COALITION_ROLEMASK_EXT,
8466 		    coal_sort_order, pid_list, MAX_SORT_PIDS);
8467 
8468 		if (ntasks > 0) {
8469 			pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8470 			    (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8471 		}
8472 
8473 		/* undefined coalition members should be the first to jetsam */
8474 		ntasks = coalition_get_pid_list(leaders[i].msi_coal, COALITION_ROLEMASK_UNDEF,
8475 		    coal_sort_order, pid_list, MAX_SORT_PIDS);
8476 
8477 		if (ntasks > 0) {
8478 			pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8479 			    (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8480 		}
8481 
8482 #if 0
8483 		if (pids_moved == leaders[i].msi_ntasks) {
8484 			/*
8485 			 * All the pids in the coalition were found in this band.
8486 			 */
8487 			printf("%s: pids_moved[%d]  equal  total coalition ntasks[%d] \n", __FUNCTION__,
8488 			    pids_moved, leaders[i].msi_ntasks);
8489 		} else if (pids_moved > leaders[i].msi_ntasks) {
8490 			/*
8491 			 * Apparently new coalition members showed up during the sort?
8492 			 */
8493 			printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__,
8494 			    pids_moved, leaders[i].msi_ntasks);
8495 		} else {
8496 			/*
8497 			 * Apparently not all the pids in the coalition were found in this band?
8498 			 */
8499 			printf("%s: pids_moved[%d] were less than  expected coalition ntasks[%d] \n", __FUNCTION__,
8500 			    pids_moved, leaders[i].msi_ntasks);
8501 		}
8502 #endif
8503 
8504 		total_pids_moved += pids_moved;
8505 	} /* end for */
8506 
8507 	return total_pids_moved;
8508 }
8509 
8510 
8511 /*
8512  * Traverse a list of pids, searching for each within the priority band provided.
8513  * If pid is found, move it to the front of the priority band.
8514  * Never searches outside the priority band provided.
8515  *
8516  * Input:
8517  *	bucket_index - jetsam priority band.
8518  *	pid_list - pointer to a list of pids.
8519  *	list_sz  - number of pids in the list.
8520  *
8521  * Pid list ordering is important in that,
8522  * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8523  * The sort_order is set by the coalition default.
8524  *
8525  * Return:
8526  *	the number of pids found and hence moved within the priority band.
8527  */
8528 static int
8529 memorystatus_move_list_locked(unsigned int bucket_index, pid_t *pid_list, int list_sz)
8530 {
8531 	memstat_bucket_t *current_bucket;
8532 	int i;
8533 	int found_pids = 0;
8534 
8535 	if ((pid_list == NULL) || (list_sz <= 0)) {
8536 		return 0;
8537 	}
8538 
8539 	if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
8540 		return 0;
8541 	}
8542 
8543 	current_bucket = &memstat_bucket[bucket_index];
8544 	for (i = 0; i < list_sz; i++) {
8545 		unsigned int b = bucket_index;
8546 		proc_t p = NULL;
8547 		proc_t aProc = NULL;
8548 		pid_t  aPid;
8549 		int list_index;
8550 
8551 		list_index = ((list_sz - 1) - i);
8552 		aPid = pid_list[list_index];
8553 
8554 		/* never search beyond bucket_index provided */
8555 		p = memorystatus_get_first_proc_locked(&b, FALSE);
8556 		while (p) {
8557 			if (proc_getpid(p) == aPid) {
8558 				aProc = p;
8559 				break;
8560 			}
8561 			p = memorystatus_get_next_proc_locked(&b, p, FALSE);
8562 		}
8563 
8564 		if (aProc == NULL) {
8565 			/* pid not found in this band, just skip it */
8566 			continue;
8567 		} else {
8568 			TAILQ_REMOVE(&current_bucket->list, aProc, p_memstat_list);
8569 			TAILQ_INSERT_HEAD(&current_bucket->list, aProc, p_memstat_list);
8570 			found_pids++;
8571 		}
8572 	}
8573 	return found_pids;
8574 }
8575 
8576 int
8577 memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index)
8578 {
8579 	int32_t i = JETSAM_PRIORITY_IDLE;
8580 	int count = 0;
8581 
8582 	if (max_bucket_index >= MEMSTAT_BUCKET_COUNT) {
8583 		return -1;
8584 	}
8585 
8586 	while (i <= max_bucket_index) {
8587 		count += memstat_bucket[i++].count;
8588 	}
8589 
8590 	return count;
8591 }
8592 
8593 int
8594 memorystatus_update_priority_for_appnap(proc_t p, boolean_t is_appnap)
8595 {
8596 #if !CONFIG_JETSAM
8597 	if (!p || (!isApp(p)) || (p->p_memstat_state & (P_MEMSTAT_INTERNAL | P_MEMSTAT_MANAGED))) {
8598 		/*
8599 		 * Ineligible processes OR system processes e.g. launchd.
8600 		 *
8601 		 * We also skip processes that have the P_MEMSTAT_MANAGED bit set, i.e.
8602 		 * they're managed by assertiond. These are iOS apps that have been ported
8603 		 * to macOS. assertiond might be in the process of modifying the app's
8604 		 * priority / memory limit - so it might have the proc_list lock, and then try
8605 		 * to take the task lock. Meanwhile we've entered this function with the task lock
8606 		 * held, and we need the proc_list lock below. So we'll deadlock with assertiond.
8607 		 *
8608 		 * It should be fine to read the P_MEMSTAT_MANAGED bit without the proc_list
8609 		 * lock here, since assertiond only sets this bit on process launch.
8610 		 */
8611 		return -1;
8612 	}
8613 
8614 	/*
8615 	 * For macOS only:
8616 	 * We would like to use memorystatus_update() here to move the processes
8617 	 * within the bands. Unfortunately memorystatus_update() calls
8618 	 * memorystatus_update_priority_locked() which uses any band transitions
8619 	 * as an indication to modify ledgers. For that it needs the task lock
8620 	 * and since we came into this function with the task lock held, we'll deadlock.
8621 	 *
8622 	 * Unfortunately we can't completely disable ledger updates  because we still
8623 	 * need the ledger updates for a subset of processes i.e. daemons.
8624 	 * When all processes on all platforms support memory limits, we can simply call
8625 	 * memorystatus_update().
8626 	 *
8627 	 * It also has some logic to deal with 'aging' which, currently, is only applicable
8628 	 * on CONFIG_JETSAM configs. So, till every platform has CONFIG_JETSAM we'll need
8629 	 * to do this explicit band transition.
8630 	 */
8631 
8632 	memstat_bucket_t *current_bucket, *new_bucket;
8633 	int32_t priority = 0;
8634 
8635 	proc_list_lock();
8636 
8637 	if (proc_list_exited(p) ||
8638 	    (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED | P_MEMSTAT_SKIP))) {
8639 		/*
8640 		 * If the process is on its way out OR
8641 		 * jetsam has alread tried and failed to kill this process,
8642 		 * let's skip the whole jetsam band transition.
8643 		 */
8644 		proc_list_unlock();
8645 		return 0;
8646 	}
8647 
8648 	if (is_appnap) {
8649 		current_bucket = &memstat_bucket[p->p_memstat_effectivepriority];
8650 		new_bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
8651 		priority = JETSAM_PRIORITY_IDLE;
8652 	} else {
8653 		if (p->p_memstat_effectivepriority != JETSAM_PRIORITY_IDLE) {
8654 			/*
8655 			 * It is possible that someone pulled this process
8656 			 * out of the IDLE band without updating its app-nap
8657 			 * parameters.
8658 			 */
8659 			proc_list_unlock();
8660 			return 0;
8661 		}
8662 
8663 		current_bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
8664 		new_bucket = &memstat_bucket[p->p_memstat_requestedpriority];
8665 		priority = p->p_memstat_requestedpriority;
8666 	}
8667 
8668 	TAILQ_REMOVE(&current_bucket->list, p, p_memstat_list);
8669 	current_bucket->count--;
8670 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
8671 		current_bucket->relaunch_high_count--;
8672 	}
8673 	TAILQ_INSERT_TAIL(&new_bucket->list, p, p_memstat_list);
8674 	new_bucket->count++;
8675 	if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
8676 		new_bucket->relaunch_high_count++;
8677 	}
8678 	/*
8679 	 * Record idle start or idle delta.
8680 	 */
8681 	if (p->p_memstat_effectivepriority == priority) {
8682 		/*
8683 		 * This process is not transitioning between
8684 		 * jetsam priority buckets.  Do nothing.
8685 		 */
8686 	} else if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
8687 		uint64_t now;
8688 		/*
8689 		 * Transitioning out of the idle priority bucket.
8690 		 * Record idle delta.
8691 		 */
8692 		assert(p->p_memstat_idle_start != 0);
8693 		now = mach_absolute_time();
8694 		if (now > p->p_memstat_idle_start) {
8695 			p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
8696 		}
8697 	} else if (priority == JETSAM_PRIORITY_IDLE) {
8698 		/*
8699 		 * Transitioning into the idle priority bucket.
8700 		 * Record idle start.
8701 		 */
8702 		p->p_memstat_idle_start = mach_absolute_time();
8703 	}
8704 
8705 	KDBG(MEMSTAT_CODE(BSD_MEMSTAT_CHANGE_PRIORITY), proc_getpid(p), priority, p->p_memstat_effectivepriority);
8706 
8707 	p->p_memstat_effectivepriority = priority;
8708 
8709 	proc_list_unlock();
8710 
8711 	return 0;
8712 
8713 #else /* !CONFIG_JETSAM */
8714 	#pragma unused(p)
8715 	#pragma unused(is_appnap)
8716 	return -1;
8717 #endif /* !CONFIG_JETSAM */
8718 }
8719 
8720 uint64_t
8721 memorystatus_available_memory_internal(struct proc *p)
8722 {
8723 #ifdef XNU_TARGET_OS_OSX
8724 	if (p->p_memstat_memlimit <= 0) {
8725 		return 0;
8726 	}
8727 #endif /* XNU_TARGET_OS_OSX */
8728 	const uint64_t footprint_in_bytes = get_task_phys_footprint(proc_task(p));
8729 	int32_t memlimit_mb;
8730 	int64_t memlimit_bytes;
8731 	int64_t rc;
8732 
8733 	if (isApp(p) == FALSE) {
8734 		return 0;
8735 	}
8736 
8737 	if (p->p_memstat_memlimit > 0) {
8738 		memlimit_mb = p->p_memstat_memlimit;
8739 	} else if (task_convert_phys_footprint_limit(-1, &memlimit_mb) != KERN_SUCCESS) {
8740 		return 0;
8741 	}
8742 
8743 	if (memlimit_mb <= 0) {
8744 		memlimit_bytes = INT_MAX & ~((1 << 20) - 1);
8745 	} else {
8746 		memlimit_bytes = ((int64_t) memlimit_mb) << 20;
8747 	}
8748 
8749 	rc = memlimit_bytes - footprint_in_bytes;
8750 
8751 	return (rc >= 0) ? rc : 0;
8752 }
8753 
8754 int
8755 memorystatus_available_memory(struct proc *p, __unused struct memorystatus_available_memory_args *args, uint64_t *ret)
8756 {
8757 	*ret = memorystatus_available_memory_internal(p);
8758 
8759 	return 0;
8760 }
8761 
8762 void
8763 memorystatus_log_system_health(const memorystatus_system_health_t *status)
8764 {
8765 	static bool healthy = true;
8766 	bool prev_healthy = healthy;
8767 
8768 	healthy = memorystatus_is_system_healthy(status);
8769 
8770 	/*
8771 	 * Avoid spamming logs by only logging when the health level has changed
8772 	 */
8773 	if (prev_healthy == healthy) {
8774 		return;
8775 	}
8776 
8777 #if CONFIG_JETSAM
8778 	if (healthy && !status->msh_available_pages_below_pressure) {
8779 		memorystatus_log("memorystatus: System is healthy. memorystatus_available_pages: %llu compressor_size:%u\n",
8780 		    (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, vm_compressor_pool_size());
8781 		return;
8782 	}
8783 	if (healthy && status->msh_available_pages_below_pressure) {
8784 		memorystatus_log(
8785 			"memorystatus: System is below pressure level, but otherwise healthy. memorystatus_available_pages: %llu compressor_size:%u\n",
8786 			(uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, vm_compressor_pool_size());
8787 		return;
8788 	}
8789 	memorystatus_log("memorystatus: System is unhealthy!  memorystatus_available_pages: %llu compressor_size:%u\n",
8790 	    (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, vm_compressor_pool_size());
8791 	memorystatus_log(
8792 		"memorystatus: available_pages_below_critical=%d, compressor_needs_to_swap=%d, compressor_is_low_on_space=%d compressor_is_thrashing=%d compressed_pages_nearing_limit=%d filecache_is_thrashing=%d zone_map_is_exhausted=%d phantom_cache_pressure=%d swappable_compressor_segments_over_limit=%d swapin_queue_over_limit=%d swap_low=%d swap_full=%d\n",
8793 		status->msh_available_pages_below_critical, status->msh_compressor_needs_to_swap,
8794 		status->msh_compressor_is_low_on_space, status->msh_compressor_is_thrashing,
8795 		status->msh_compressed_pages_nearing_limit, status->msh_filecache_is_thrashing,
8796 		status->msh_zone_map_is_exhausted, status->msh_phantom_cache_pressure,
8797 		status->msh_swappable_compressor_segments_over_limit, status->msh_swapin_queue_over_limit,
8798 		status->msh_swap_low_on_space, status->msh_swap_out_of_space);
8799 #else /* CONFIG_JETSAM */
8800 	memorystatus_log("memorystatus: System is %s. memorystatus_available_pages: %llu compressor_size:%u\n",
8801 	    healthy ? "healthy" : "unhealthy",
8802 	    (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, vm_compressor_pool_size());
8803 	if (!healthy) {
8804 		memorystatus_log("memorystatus: zone_map_is_exhausted=%d\n",
8805 		    status->msh_zone_map_is_exhausted);
8806 	}
8807 #endif /* CONFIG_JETSAM */
8808 }
8809 
8810 uint32_t
8811 memorystatus_pick_kill_cause(const memorystatus_system_health_t *status)
8812 {
8813 	assert(!memorystatus_is_system_healthy(status));
8814 #if CONFIG_JETSAM
8815 	if (status->msh_compressor_is_thrashing) {
8816 		return kMemorystatusKilledVMCompressorThrashing;
8817 	} else if (status->msh_compressor_is_low_on_space) {
8818 		return kMemorystatusKilledVMCompressorSpaceShortage;
8819 	} else if (status->msh_filecache_is_thrashing) {
8820 		return kMemorystatusKilledFCThrashing;
8821 	} else if (status->msh_zone_map_is_exhausted) {
8822 		return kMemorystatusKilledZoneMapExhaustion;
8823 	} else if (status->msh_pageout_starved) {
8824 		return kMemorystatusKilledVMPageoutStarvation;
8825 	} else {
8826 		assert(status->msh_available_pages_below_critical);
8827 		return kMemorystatusKilledVMPageShortage;
8828 	}
8829 #else /* CONFIG_JETSAM */
8830 	assert(status->msh_zone_map_is_exhausted);
8831 	(void) status;
8832 	return kMemorystatusKilledZoneMapExhaustion;
8833 #endif /* CONFIG_JETSAM */
8834 }
8835 
8836 #if DEVELOPMENT || DEBUG
8837 static int
8838 memorystatus_cmd_increase_jetsam_task_limit(pid_t pid, uint32_t byte_increase)
8839 {
8840 	memorystatus_memlimit_properties_t mmp_entry;
8841 
8842 	/* Validate inputs */
8843 	if ((pid == 0) || (byte_increase == 0)) {
8844 		return EINVAL;
8845 	}
8846 
8847 	proc_t p = proc_find(pid);
8848 
8849 	if (!p) {
8850 		return ESRCH;
8851 	}
8852 
8853 	const uint32_t current_memlimit_increase = roundToNearestMB(p->p_memlimit_increase);
8854 	/* round to page */
8855 	const int32_t page_aligned_increase = (int32_t) MIN(round_page(p->p_memlimit_increase + byte_increase), INT32_MAX);
8856 
8857 	proc_list_lock();
8858 
8859 	memorystatus_get_memlimit_properties_internal(p, &mmp_entry);
8860 
8861 	if (mmp_entry.memlimit_active > 0) {
8862 		mmp_entry.memlimit_active -= current_memlimit_increase;
8863 		mmp_entry.memlimit_active += roundToNearestMB(page_aligned_increase);
8864 	}
8865 
8866 	if (mmp_entry.memlimit_inactive > 0) {
8867 		mmp_entry.memlimit_inactive -= current_memlimit_increase;
8868 		mmp_entry.memlimit_inactive += roundToNearestMB(page_aligned_increase);
8869 	}
8870 
8871 	/*
8872 	 * Store the updated delta limit in the proc.
8873 	 */
8874 	p->p_memlimit_increase = page_aligned_increase;
8875 
8876 	int error = memorystatus_set_memlimit_properties_internal(p, &mmp_entry);
8877 
8878 	proc_list_unlock();
8879 	proc_rele(p);
8880 
8881 	return error;
8882 }
8883 #endif /* DEVELOPMENT */
8884