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