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