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