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