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