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