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