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