2 * Copyright (c) 2006-2018 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 #include <kern/sched_prim.h>
31 #include <kern/kalloc.h>
32 #include <kern/assert.h>
33 #include <kern/debug.h>
34 #include <kern/locks.h>
35 #include <kern/task.h>
36 #include <kern/thread.h>
37 #include <kern/host.h>
38 #include <kern/policy_internal.h>
39 #include <kern/thread_group.h>
41 #include <IOKit/IOBSD.h>
43 #include <libkern/libkern.h>
44 #include <mach/coalition.h>
45 #include <mach/mach_time.h>
46 #include <mach/task.h>
47 #include <mach/host_priv.h>
48 #include <mach/mach_host.h>
50 #include <pexpert/pexpert.h>
51 #include <sys/coalition.h>
52 #include <sys/kern_event.h>
54 #include <sys/proc_info.h>
55 #include <sys/reason.h>
56 #include <sys/signal.h>
57 #include <sys/signalvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
63 #include <vm/vm_pageout.h>
64 #include <vm/vm_protos.h>
67 #include <vm/vm_map.h>
68 #endif /* CONFIG_FREEZE */
70 #include <sys/kern_memorystatus.h>
72 #include <mach/machine/sdt.h>
73 #include <libkern/section_keywords.h>
74 #include <stdatomic.h>
76 /* For logging clarity */
77 static const char *memorystatus_kill_cause_name
[] = {
78 "", /* kMemorystatusInvalid */
79 "jettisoned", /* kMemorystatusKilled */
80 "highwater", /* kMemorystatusKilledHiwat */
81 "vnode-limit", /* kMemorystatusKilledVnodes */
82 "vm-pageshortage", /* kMemorystatusKilledVMPageShortage */
83 "proc-thrashing", /* kMemorystatusKilledProcThrashing */
84 "fc-thrashing", /* kMemorystatusKilledFCThrashing */
85 "per-process-limit", /* kMemorystatusKilledPerProcessLimit */
86 "disk-space-shortage", /* kMemorystatusKilledDiskSpaceShortage */
87 "idle-exit", /* kMemorystatusKilledIdleExit */
88 "zone-map-exhaustion", /* kMemorystatusKilledZoneMapExhaustion */
89 "vm-compressor-thrashing", /* kMemorystatusKilledVMCompressorThrashing */
90 "vm-compressor-space-shortage", /* kMemorystatusKilledVMCompressorSpaceShortage */
94 memorystatus_priority_band_name(int32_t priority
)
97 case JETSAM_PRIORITY_FOREGROUND
:
99 case JETSAM_PRIORITY_AUDIO_AND_ACCESSORY
:
100 return "AUDIO_AND_ACCESSORY";
101 case JETSAM_PRIORITY_CONDUCTOR
:
103 case JETSAM_PRIORITY_HOME
:
105 case JETSAM_PRIORITY_EXECUTIVE
:
107 case JETSAM_PRIORITY_IMPORTANT
:
109 case JETSAM_PRIORITY_CRITICAL
:
116 /* Does cause indicate vm or fc thrashing? */
118 is_reason_thrashing(unsigned cause
)
121 case kMemorystatusKilledFCThrashing
:
122 case kMemorystatusKilledVMCompressorThrashing
:
123 case kMemorystatusKilledVMCompressorSpaceShortage
:
130 /* Is the zone map almost full? */
132 is_reason_zone_map_exhaustion(unsigned cause
)
134 if (cause
== kMemorystatusKilledZoneMapExhaustion
) {
141 * Returns the current zone map size and capacity to include in the jetsam snapshot.
142 * Defined in zalloc.c
144 extern void get_zone_map_size(uint64_t *current_size
, uint64_t *capacity
);
147 * Returns the name of the largest zone and its size to include in the jetsam snapshot.
148 * Defined in zalloc.c
150 extern void get_largest_zone_info(char *zone_name
, size_t zone_name_len
, uint64_t *zone_size
);
152 /* These are very verbose printfs(), enable with
153 * MEMORYSTATUS_DEBUG_LOG
155 #if MEMORYSTATUS_DEBUG_LOG
156 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
158 if (cond) { printf(format, ##__VA_ARGS__); } \
161 #define MEMORYSTATUS_DEBUG(cond, format, ...)
165 * Active / Inactive limit support
166 * proc list must be locked
168 * The SET_*** macros are used to initialize a limit
169 * for the first time.
171 * The CACHE_*** macros are use to cache the limit that will
172 * soon be in effect down in the ledgers.
175 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
177 (p)->p_memstat_memlimit_active = (limit); \
179 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
181 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
185 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
187 (p)->p_memstat_memlimit_inactive = (limit); \
189 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
191 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
195 #define CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal) \
197 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
198 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
199 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
202 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
207 #define CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal) \
209 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
210 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
211 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
214 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
220 /* General tunables */
222 unsigned long delta_percentage
= 5;
223 unsigned long critical_threshold_percentage
= 5;
224 unsigned long idle_offset_percentage
= 5;
225 unsigned long pressure_threshold_percentage
= 15;
226 unsigned long freeze_threshold_percentage
= 50;
227 unsigned long policy_more_free_offset_percentage
= 5;
229 /* General memorystatus stuff */
231 struct klist memorystatus_klist
;
232 static lck_mtx_t memorystatus_klist_mutex
;
234 static void memorystatus_klist_lock(void);
235 static void memorystatus_klist_unlock(void);
237 static uint64_t memorystatus_sysprocs_idle_delay_time
= 0;
238 static uint64_t memorystatus_apps_idle_delay_time
= 0;
241 * Memorystatus kevents
244 static int filt_memorystatusattach(struct knote
*kn
, struct kevent_internal_s
*kev
);
245 static void filt_memorystatusdetach(struct knote
*kn
);
246 static int filt_memorystatus(struct knote
*kn
, long hint
);
247 static int filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
248 static int filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
250 SECURITY_READ_ONLY_EARLY(struct filterops
) memorystatus_filtops
= {
251 .f_attach
= filt_memorystatusattach
,
252 .f_detach
= filt_memorystatusdetach
,
253 .f_event
= filt_memorystatus
,
254 .f_touch
= filt_memorystatustouch
,
255 .f_process
= filt_memorystatusprocess
,
259 kMemorystatusNoPressure
= 0x1,
260 kMemorystatusPressure
= 0x2,
261 kMemorystatusLowSwap
= 0x4,
262 kMemorystatusProcLimitWarn
= 0x8,
263 kMemorystatusProcLimitCritical
= 0x10
266 /* Idle guard handling */
268 static int32_t memorystatus_scheduled_idle_demotions_sysprocs
= 0;
269 static int32_t memorystatus_scheduled_idle_demotions_apps
= 0;
271 static thread_call_t memorystatus_idle_demotion_call
;
273 static void memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
);
274 static void memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
);
275 static void memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clean_state
);
276 static void memorystatus_reschedule_idle_demotion_locked(void);
278 static void memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
);
280 int memorystatus_update_priority_for_appnap(proc_t p
, boolean_t is_appnap
);
282 vm_pressure_level_t
convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
284 boolean_t
is_knote_registered_modify_task_pressure_bits(struct knote
*, int, task_t
, vm_pressure_level_t
, vm_pressure_level_t
);
285 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
);
286 void memorystatus_send_low_swap_note(void);
288 unsigned int memorystatus_level
= 0;
290 static int memorystatus_list_count
= 0;
293 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
295 typedef struct memstat_bucket
{
296 TAILQ_HEAD(, proc
) list
;
300 memstat_bucket_t memstat_bucket
[MEMSTAT_BUCKET_COUNT
];
302 int memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index
);
304 uint64_t memstat_idle_demotion_deadline
= 0;
306 int system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
307 int applications_aging_band
= JETSAM_PRIORITY_IDLE
;
309 #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)))
312 * Checking the p_memstat_state almost always requires the proc_list_lock
313 * because the jetsam thread could be on the other core changing the state.
315 * App -- almost always managed by a system process. Always have dirty tracking OFF. Can include extensions too.
316 * System Processes -- not managed by anybody. Always have dirty tracking ON. Can include extensions (here) too.
318 #define isApp(p) ((p->p_memstat_state & P_MEMSTAT_MANAGED) || ! (p->p_memstat_dirty & P_DIRTY_TRACK))
319 #define isSysProc(p) ( ! (p->p_memstat_state & P_MEMSTAT_MANAGED) || (p->p_memstat_dirty & P_DIRTY_TRACK))
321 #define kJetsamAgingPolicyNone (0)
322 #define kJetsamAgingPolicyLegacy (1)
323 #define kJetsamAgingPolicySysProcsReclaimedFirst (2)
324 #define kJetsamAgingPolicyAppsReclaimedFirst (3)
325 #define kJetsamAgingPolicyMax kJetsamAgingPolicyAppsReclaimedFirst
327 unsigned int jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
329 extern int corpse_for_fatal_memkill
;
330 extern unsigned long total_corpses_count(void) __attribute__((pure
));
331 extern void task_purge_all_corpses(void);
332 extern uint64_t vm_purgeable_purge_task_owned(task_t task
);
333 boolean_t
memorystatus_allowed_vm_map_fork(task_t
);
334 #if DEVELOPMENT || DEBUG
335 void memorystatus_abort_vm_map_fork(task_t
);
340 /* Keeping around for future use if we need a utility that can do this OR an app that needs a dynamic adjustment. */
343 sysctl_set_jetsam_aging_policy SYSCTL_HANDLER_ARGS
345 #pragma unused(oidp, arg1, arg2)
347 int error
= 0, val
= 0;
348 memstat_bucket_t
*old_bucket
= 0;
349 int old_system_procs_aging_band
= 0, new_system_procs_aging_band
= 0;
350 int old_applications_aging_band
= 0, new_applications_aging_band
= 0;
351 proc_t p
= NULL
, next_proc
= NULL
;
354 error
= sysctl_io_number(req
, jetsam_aging_policy
, sizeof(int), &val
, NULL
);
355 if (error
|| !req
->newptr
) {
359 if ((val
< 0) || (val
> kJetsamAgingPolicyMax
)) {
360 printf("jetsam: ordering policy sysctl has invalid value - %d\n", val
);
365 * We need to synchronize with any potential adding/removal from aging bands
366 * that might be in progress currently. We use the proc_list_lock() just for
367 * consistency with all the routines dealing with 'aging' processes. We need
368 * a lighterweight lock.
372 old_system_procs_aging_band
= system_procs_aging_band
;
373 old_applications_aging_band
= applications_aging_band
;
376 case kJetsamAgingPolicyNone
:
377 new_system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
378 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
381 case kJetsamAgingPolicyLegacy
:
383 * Legacy behavior where some daemons get a 10s protection once and only before the first clean->dirty->clean transition before going into IDLE band.
385 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
386 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
389 case kJetsamAgingPolicySysProcsReclaimedFirst
:
390 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
391 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
394 case kJetsamAgingPolicyAppsReclaimedFirst
:
395 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
396 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
403 if (old_system_procs_aging_band
&& (old_system_procs_aging_band
!= new_system_procs_aging_band
)) {
404 old_bucket
= &memstat_bucket
[old_system_procs_aging_band
];
405 p
= TAILQ_FIRST(&old_bucket
->list
);
408 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
411 if (new_system_procs_aging_band
== JETSAM_PRIORITY_IDLE
) {
412 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
415 memorystatus_update_priority_locked(p
, new_system_procs_aging_band
, false, true);
423 if (old_applications_aging_band
&& (old_applications_aging_band
!= new_applications_aging_band
)) {
424 old_bucket
= &memstat_bucket
[old_applications_aging_band
];
425 p
= TAILQ_FIRST(&old_bucket
->list
);
428 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
431 if (new_applications_aging_band
== JETSAM_PRIORITY_IDLE
) {
432 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
435 memorystatus_update_priority_locked(p
, new_applications_aging_band
, false, true);
443 jetsam_aging_policy
= val
;
444 system_procs_aging_band
= new_system_procs_aging_band
;
445 applications_aging_band
= new_applications_aging_band
;
452 SYSCTL_PROC(_kern
, OID_AUTO
, set_jetsam_aging_policy
, CTLTYPE_INT
| CTLFLAG_RW
,
453 0, 0, sysctl_set_jetsam_aging_policy
, "I", "Jetsam Aging Policy");
457 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
459 #pragma unused(oidp, arg1, arg2)
461 int error
= 0, val
= 0, old_time_in_secs
= 0;
462 uint64_t old_time_in_ns
= 0;
464 absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time
, &old_time_in_ns
);
465 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
467 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
468 if (error
|| !req
->newptr
) {
472 if ((val
< 0) || (val
> INT32_MAX
)) {
473 printf("jetsam: new idle delay interval has invalid value.\n");
477 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
482 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_sysprocs_idle_delay_time
, CTLTYPE_INT
| CTLFLAG_RW
,
483 0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time
, "I", "Aging window for system processes");
487 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
489 #pragma unused(oidp, arg1, arg2)
491 int error
= 0, val
= 0, old_time_in_secs
= 0;
492 uint64_t old_time_in_ns
= 0;
494 absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time
, &old_time_in_ns
);
495 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
497 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
498 if (error
|| !req
->newptr
) {
502 if ((val
< 0) || (val
> INT32_MAX
)) {
503 printf("jetsam: new idle delay interval has invalid value.\n");
507 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
512 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_apps_idle_delay_time
, CTLTYPE_INT
| CTLFLAG_RW
,
513 0, 0, sysctl_jetsam_set_apps_idle_delay_time
, "I", "Aging window for applications");
515 SYSCTL_INT(_kern
, OID_AUTO
, jetsam_aging_policy
, CTLTYPE_INT
| CTLFLAG_RD
, &jetsam_aging_policy
, 0, "");
517 static unsigned int memorystatus_dirty_count
= 0;
519 SYSCTL_INT(_kern
, OID_AUTO
, max_task_pmem
, CTLFLAG_RD
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
, &max_task_footprint_mb
, 0, "");
523 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_level
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_level
, 0, "");
525 #endif /* CONFIG_EMBEDDED */
528 memorystatus_get_level(__unused
struct proc
*p
, struct memorystatus_get_level_args
*args
, __unused
int *ret
)
530 user_addr_t level
= 0;
534 if (copyout(&memorystatus_level
, level
, sizeof(memorystatus_level
)) != 0) {
541 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
);
542 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
);
544 static void memorystatus_thread(void *param __unused
, wait_result_t wr __unused
);
548 static int memorystatus_highwater_enabled
= 1; /* Update the cached memlimit data. */
550 static boolean_t
proc_jetsam_state_is_active_locked(proc_t
);
551 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
552 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
555 static int memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
557 static int memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
);
559 static int memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
561 static int memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
563 int proc_get_memstat_priority(proc_t
, boolean_t
);
565 static boolean_t memorystatus_idle_snapshot
= 0;
567 unsigned int memorystatus_delta
= 0;
569 /* Jetsam Loop Detection */
570 static boolean_t memorystatus_jld_enabled
= FALSE
; /* Enable jetsam loop detection */
571 static uint32_t memorystatus_jld_eval_period_msecs
= 0; /* Init pass sets this based on device memory size */
572 static int memorystatus_jld_eval_aggressive_count
= 3; /* Raise the priority max after 'n' aggressive loops */
573 static int memorystatus_jld_eval_aggressive_priority_band_max
= 15; /* Kill aggressively up through this band */
576 * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
577 * --- 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.
580 * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
581 * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
583 * - 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.
585 * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
588 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD 25
589 boolean_t memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
590 boolean_t memorystatus_aggressive_jetsam_lenient
= FALSE
;
592 #if DEVELOPMENT || DEBUG
594 * Jetsam Loop Detection tunables.
597 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_period_msecs
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_jld_eval_period_msecs
, 0, "");
598 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_count
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_count
, 0, "");
599 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_priority_band_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_priority_band_max
, 0, "");
600 #endif /* DEVELOPMENT || DEBUG */
602 static uint32_t kill_under_pressure_cause
= 0;
605 * default jetsam snapshot support
607 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot
;
608 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot_copy
;
609 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
610 static unsigned int memorystatus_jetsam_snapshot_count
= 0;
611 static unsigned int memorystatus_jetsam_snapshot_copy_count
= 0;
612 static unsigned int memorystatus_jetsam_snapshot_max
= 0;
613 static unsigned int memorystatus_jetsam_snapshot_size
= 0;
614 static uint64_t memorystatus_jetsam_snapshot_last_timestamp
= 0;
615 static uint64_t memorystatus_jetsam_snapshot_timeout
= 0;
616 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
619 * snapshot support for memstats collected at boot.
621 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot
;
623 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
);
624 static boolean_t
memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
);
625 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
);
627 static void memorystatus_clear_errors(void);
628 static void memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
);
629 static void memorystatus_get_task_phys_footprint_page_counts(task_t task
,
630 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
631 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
632 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
633 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
);
635 static void memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
);
637 static uint32_t memorystatus_build_state(proc_t p
);
638 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
640 static boolean_t
memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
, int32_t *priority
, uint32_t *errors
);
641 static boolean_t
memorystatus_kill_top_process_aggressive(uint32_t cause
, int aggr_count
, int32_t priority_max
, uint32_t *errors
);
642 static boolean_t
memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, unsigned int band
, int aggr_count
, uint32_t *errors
);
643 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t *errors
, boolean_t
*purged
);
645 static boolean_t
memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
);
647 /* Priority Band Sorting Routines */
648 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
);
649 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
);
650 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
);
651 static int memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
);
654 typedef int (*cmpfunc_t
)(const void *a
, const void *b
);
655 extern void qsort(void *a
, size_t n
, size_t es
, cmpfunc_t cmp
);
656 static int memstat_asc_cmp(const void *a
, const void *b
);
660 extern unsigned int vm_page_free_count
;
661 extern unsigned int vm_page_active_count
;
662 extern unsigned int vm_page_inactive_count
;
663 extern unsigned int vm_page_throttled_count
;
664 extern unsigned int vm_page_purgeable_count
;
665 extern unsigned int vm_page_wire_count
;
666 #if CONFIG_SECLUDED_MEMORY
667 extern unsigned int vm_page_secluded_count
;
668 #endif /* CONFIG_SECLUDED_MEMORY */
671 unsigned int memorystatus_available_pages
= (unsigned int)-1;
672 unsigned int memorystatus_available_pages_pressure
= 0;
673 unsigned int memorystatus_available_pages_critical
= 0;
674 static unsigned int memorystatus_available_pages_critical_base
= 0;
675 static unsigned int memorystatus_available_pages_critical_idle_offset
= 0;
677 #if DEVELOPMENT || DEBUG
678 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
680 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_MASKED
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
681 #endif /* DEVELOPMENT || DEBUG */
683 static unsigned int memorystatus_jetsam_policy
= kPolicyDefault
;
684 unsigned int memorystatus_policy_more_free_offset_pages
= 0;
685 static void memorystatus_update_levels_locked(boolean_t critical_only
);
686 static unsigned int memorystatus_thread_wasted_wakeup
= 0;
688 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
689 extern void vm_thrashing_jetsam_done(void);
690 static int memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
);
692 int32_t max_kill_priority
= JETSAM_PRIORITY_MAX
;
694 #else /* CONFIG_JETSAM */
696 uint64_t memorystatus_available_pages
= (uint64_t)-1;
697 uint64_t memorystatus_available_pages_pressure
= (uint64_t)-1;
698 uint64_t memorystatus_available_pages_critical
= (uint64_t)-1;
700 int32_t max_kill_priority
= JETSAM_PRIORITY_IDLE
;
701 #endif /* CONFIG_JETSAM */
703 unsigned int memorystatus_frozen_count
= 0;
704 unsigned int memorystatus_frozen_processes_max
= 0;
705 unsigned int memorystatus_frozen_shared_mb
= 0;
706 unsigned int memorystatus_frozen_shared_mb_max
= 0;
707 unsigned int memorystatus_freeze_shared_mb_per_process_max
= 0; /* Max. MB allowed per process to be freezer-eligible. */
708 unsigned int memorystatus_freeze_private_shared_pages_ratio
= 2; /* Ratio of private:shared pages for a process to be freezer-eligible. */
709 unsigned int memorystatus_suspended_count
= 0;
710 unsigned int memorystatus_thaw_count
= 0;
711 unsigned int memorystatus_refreeze_eligible_count
= 0; /* # of processes currently thawed i.e. have state on disk & in-memory */
713 #if VM_PRESSURE_EVENTS
715 boolean_t
memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t exceeded
);
717 vm_pressure_level_t memorystatus_vm_pressure_level
= kVMPressureNormal
;
720 * We use this flag to signal if we have any HWM offenders
721 * on the system. This way we can reduce the number of wakeups
722 * of the memorystatus_thread when the system is between the
723 * "pressure" and "critical" threshold.
725 * The (re-)setting of this variable is done without any locks
726 * or synchronization simply because it is not possible (currently)
727 * to keep track of HWM offenders that drop down below their memory
728 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
729 * by allowing the unguarded modification of this variable.
731 boolean_t memorystatus_hwm_candidates
= 0;
733 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
736 * This value is the threshold that a process must meet to be considered for scavenging.
739 #define VM_PRESSURE_MINIMUM_RSIZE 6 /* MB */
740 #else /* CONFIG_EMBEDDED */
741 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
742 #endif /* CONFIG_EMBEDDED */
744 uint32_t vm_pressure_task_footprint_min
= VM_PRESSURE_MINIMUM_RSIZE
;
746 #if DEVELOPMENT || DEBUG
747 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_vm_pressure_task_footprint_min
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &vm_pressure_task_footprint_min
, 0, "");
748 #endif /* DEVELOPMENT || DEBUG */
750 #endif /* VM_PRESSURE_EVENTS */
753 #if DEVELOPMENT || DEBUG
755 lck_grp_attr_t
*disconnect_page_mappings_lck_grp_attr
;
756 lck_grp_t
*disconnect_page_mappings_lck_grp
;
757 static lck_mtx_t disconnect_page_mappings_mutex
;
759 extern boolean_t kill_on_no_paging_space
;
760 #endif /* DEVELOPMENT || DEBUG */
764 * Table that expresses the probability of a process
765 * being used in the next hour.
767 typedef struct memorystatus_internal_probabilities
{
768 char proc_name
[MAXCOMLEN
+ 1];
770 } memorystatus_internal_probabilities_t
;
772 static memorystatus_internal_probabilities_t
*memorystatus_global_probabilities_table
= NULL
;
773 static size_t memorystatus_global_probabilities_size
= 0;
778 boolean_t memorystatus_freeze_enabled
= FALSE
;
779 int memorystatus_freeze_wakeup
= 0;
780 int memorystatus_freeze_jetsam_band
= 0; /* the jetsam band which will contain P_MEMSTAT_FROZEN processes */
782 lck_grp_attr_t
*freezer_lck_grp_attr
;
783 lck_grp_t
*freezer_lck_grp
;
784 static lck_mtx_t freezer_mutex
;
786 static inline boolean_t
memorystatus_can_freeze_processes(void);
787 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
788 static boolean_t
memorystatus_is_process_eligible_for_freeze(proc_t p
);
789 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
790 static boolean_t
memorystatus_freeze_thread_should_run(void);
792 void memorystatus_disable_freeze(void);
795 static unsigned int memorystatus_freeze_threshold
= 0;
797 static unsigned int memorystatus_freeze_pages_min
= 0;
798 static unsigned int memorystatus_freeze_pages_max
= 0;
800 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
802 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
803 static uint64_t memorystatus_freeze_budget_pages_remaining
= 0; //remaining # of pages that can be frozen to disk
804 static boolean_t memorystatus_freeze_degradation
= FALSE
; //protected by the freezer mutex. Signals we are in a degraded freeze mode.
806 static unsigned int memorystatus_max_frozen_demotions_daily
= 0;
807 static unsigned int memorystatus_thaw_count_demotion_threshold
= 0;
810 static uint64_t memorystatus_freeze_pageouts
= 0;
813 #define DEGRADED_WINDOW_MINS (30)
814 #define NORMAL_WINDOW_MINS (24 * 60)
816 static throttle_interval_t throttle_intervals
[] = {
817 { DEGRADED_WINDOW_MINS
, 1, 0, 0, { 0, 0 }},
818 { NORMAL_WINDOW_MINS
, 1, 0, 0, { 0, 0 }},
820 throttle_interval_t
*degraded_throttle_window
= &throttle_intervals
[0];
821 throttle_interval_t
*normal_throttle_window
= &throttle_intervals
[1];
823 extern uint64_t vm_swap_get_free_space(void);
824 extern boolean_t
vm_swap_max_budget(uint64_t *);
826 static void memorystatus_freeze_update_throttle(uint64_t *budget_pages_allowed
);
828 static uint64_t memorystatus_freezer_thread_next_run_ts
= 0;
830 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_frozen_count
, 0, "");
831 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_thaw_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_thaw_count
, 0, "");
832 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
833 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_budget_pages_remaining
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_freeze_budget_pages_remaining
, "");
835 #endif /* CONFIG_FREEZE */
839 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
841 #if DEVELOPMENT || DEBUG
843 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
846 memorystatus_debug_dump_bucket_locked(unsigned int bucket_index
)
850 int ledger_limit
= 0;
851 unsigned int b
= bucket_index
;
852 boolean_t traverse_all_buckets
= FALSE
;
854 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
855 traverse_all_buckets
= TRUE
;
858 traverse_all_buckets
= FALSE
;
863 * footprint reported in [pages / MB ]
864 * limits reported as:
865 * L-limit proc's Ledger limit
866 * C-limit proc's Cached limit, should match Ledger
867 * A-limit proc's Active limit
868 * IA-limit proc's Inactive limit
869 * F==Fatal, NF==NonFatal
872 printf("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64
);
873 printf("bucket [pid] [pages / MB] [state] [EP / RP] dirty deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
874 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
876 bytes
= get_task_phys_footprint(p
->task
);
877 task_get_phys_footprint_limit(p
->task
, &ledger_limit
);
878 printf("%2d [%5d] [%5lld /%3lldMB] 0x%-8x [%2d / %2d] 0x%-3x %10lld [%3d / %3d%s / %3d%s / %3d%s] %s\n",
880 (bytes
/ PAGE_SIZE_64
), /* task's footprint converted from bytes to pages */
881 (bytes
/ (1024ULL * 1024ULL)), /* task's footprint converted from bytes to MB */
882 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
884 p
->p_memstat_memlimit
,
885 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
886 p
->p_memstat_memlimit_active
,
887 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
888 p
->p_memstat_memlimit_inactive
,
889 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
890 (*p
->p_name
? p
->p_name
: "unknown"));
891 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
893 printf("memorystatus_debug_dump ***END***\n");
897 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
899 #pragma unused(oidp, arg2)
900 int bucket_index
= 0;
902 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
903 if (error
|| !req
->newptr
) {
906 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
907 if (error
|| !req
->newptr
) {
910 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
912 * All jetsam buckets will be dumped.
916 * Only a single bucket will be dumped.
921 memorystatus_debug_dump_bucket_locked(bucket_index
);
923 memorystatus_debug_dump_this_bucket
= bucket_index
;
928 * Debug aid to look at jetsam buckets and proc jetsam fields.
929 * Use this sysctl to act on a particular jetsam bucket.
930 * Writing the sysctl triggers the dump.
931 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
934 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_debug_dump_this_bucket
, CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_debug_dump_this_bucket
, 0, sysctl_memorystatus_debug_dump_bucket
, "I", "");
937 /* Debug aid to aid determination of limit */
940 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
942 #pragma unused(oidp, arg2)
945 int error
, enable
= 0;
946 boolean_t use_active
; /* use the active limit and active limit attributes */
949 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
950 if (error
|| !req
->newptr
) {
954 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
955 if (error
|| !req
->newptr
) {
959 if (!(enable
== 0 || enable
== 1)) {
965 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
967 use_active
= proc_jetsam_state_is_active_locked(p
);
970 if (use_active
== TRUE
) {
971 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
973 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
977 * Disabling limits does not touch the stored variants.
978 * Set the cached limit fields to system_wide defaults.
980 p
->p_memstat_memlimit
= -1;
981 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
986 * Enforce the cached limit by writing to the ledger.
988 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
990 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
993 memorystatus_highwater_enabled
= enable
;
1000 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
1002 #if VM_PRESSURE_EVENTS
1005 * This routine is used for targeted notifications regardless of system memory pressure
1006 * and regardless of whether or not the process has already been notified.
1007 * It bypasses and has no effect on the only-one-notification per soft-limit policy.
1009 * "memnote" is the current user.
1013 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
1015 #pragma unused(arg1, arg2)
1017 int error
= 0, pid
= 0;
1018 struct knote
*kn
= NULL
;
1019 boolean_t found_knote
= FALSE
;
1020 int fflags
= 0; /* filter flags for EVFILT_MEMORYSTATUS */
1023 error
= sysctl_handle_quad(oidp
, &value
, 0, req
);
1024 if (error
|| !req
->newptr
) {
1029 * Find the pid in the low 32 bits of value passed in.
1031 pid
= (int)(value
& 0xFFFFFFFF);
1034 * Find notification in the high 32 bits of the value passed in.
1036 fflags
= (int)((value
>> 32) & 0xFFFFFFFF);
1039 * For backwards compatibility, when no notification is
1040 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
1043 fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
1044 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
1048 * See event.h ... fflags for EVFILT_MEMORYSTATUS
1050 if (!((fflags
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) ||
1051 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) ||
1052 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) ||
1053 (fflags
== NOTE_MEMORYSTATUS_LOW_SWAP
) ||
1054 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) ||
1055 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) ||
1056 (((fflags
& NOTE_MEMORYSTATUS_MSL_STATUS
) != 0 &&
1057 ((fflags
& ~NOTE_MEMORYSTATUS_MSL_STATUS
) == 0))))) {
1058 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags
);
1064 * Forcibly send pid a memorystatus notification.
1067 memorystatus_klist_lock();
1069 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
1070 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
1071 pid_t knote_pid
= knote_proc
->p_pid
;
1073 if (knote_pid
== pid
) {
1075 * Forcibly send this pid a memorystatus notification.
1077 kn
->kn_fflags
= fflags
;
1083 KNOTE(&memorystatus_klist
, 0);
1084 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value
, fflags
, pid
);
1087 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value
, fflags
, pid
);
1091 memorystatus_klist_unlock();
1096 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_QUAD
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
1097 0, 0, &sysctl_memorystatus_vm_pressure_send
, "Q", "");
1099 #endif /* VM_PRESSURE_EVENTS */
1101 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
1104 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
1105 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
1106 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
1107 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_policy_more_free_offset_pages
, CTLFLAG_RW
, &memorystatus_policy_more_free_offset_pages
, 0, "");
1109 static unsigned int memorystatus_jetsam_panic_debug
= 0;
1110 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic
= 0;
1112 /* Diagnostic code */
1115 kJetsamDiagnosticModeNone
= 0,
1116 kJetsamDiagnosticModeAll
= 1,
1117 kJetsamDiagnosticModeStopAtFirstActive
= 2,
1118 kJetsamDiagnosticModeCount
1119 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
1121 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
1124 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1126 #pragma unused(arg1, arg2)
1128 const char *diagnosticStrings
[] = {
1129 "jetsam: diagnostic mode: resetting critical level.",
1130 "jetsam: diagnostic mode: will examine all processes",
1131 "jetsam: diagnostic mode: will stop at first active process"
1134 int error
, val
= jetsam_diagnostic_mode
;
1135 boolean_t changed
= FALSE
;
1137 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
1138 if (error
|| !req
->newptr
) {
1141 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
1142 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
1148 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
1149 jetsam_diagnostic_mode
= val
;
1151 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
1153 switch (jetsam_diagnostic_mode
) {
1154 case kJetsamDiagnosticModeNone
:
1155 /* Already cleared */
1157 case kJetsamDiagnosticModeAll
:
1158 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
1160 case kJetsamDiagnosticModeStopAtFirstActive
:
1161 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
1164 /* Already validated */
1168 memorystatus_update_levels_locked(FALSE
);
1175 printf("%s\n", diagnosticStrings
[val
]);
1181 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
| CTLFLAG_ANYBODY
,
1182 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
1184 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
1186 #if VM_PRESSURE_EVENTS
1188 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
1190 #endif /* VM_PRESSURE_EVENTS */
1192 #endif /* CONFIG_JETSAM */
1196 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_jetsam_band
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_jetsam_band
, 0, "");
1197 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
1198 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_degraded_mode
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_freeze_degradation
, 0, "");
1200 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
1202 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
1203 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
1205 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_refreeze_eligible_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_refreeze_eligible_count
, 0, "");
1206 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_processes_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_frozen_processes_max
, 0, "");
1209 * Max. shared-anonymous memory in MB that can be held by frozen processes in the high jetsam band.
1210 * "0" means no limit.
1211 * Default is 10% of system-wide task limit.
1214 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_shared_mb_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_frozen_shared_mb_max
, 0, "");
1215 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_shared_mb
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_frozen_shared_mb
, 0, "");
1217 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_shared_mb_per_process_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_shared_mb_per_process_max
, 0, "");
1218 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_private_shared_pages_ratio
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_private_shared_pages_ratio
, 0, "");
1220 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
1223 * max. # of frozen process demotions we will allow in our daily cycle.
1225 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_max_freeze_demotions_daily
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_max_frozen_demotions_daily
, 0, "");
1227 * min # of thaws needed by a process to protect it from getting demoted into the IDLE band.
1229 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_thaw_count_demotion_threshold
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_thaw_count_demotion_threshold
, 0, "");
1231 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
1232 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
1235 * When set to true, this keeps frozen processes in the compressor pool in memory, instead of swapping them out to disk.
1236 * Exposed via the sysctl kern.memorystatus_freeze_to_memory.
1238 boolean_t memorystatus_freeze_to_memory
= FALSE
;
1239 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_to_memory
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &memorystatus_freeze_to_memory
, 0, "");
1241 #define VM_PAGES_FOR_ALL_PROCS (2)
1243 * Manual trigger of freeze and thaw for dev / debug kernels only.
1246 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1248 #pragma unused(arg1, arg2)
1251 int freezer_error_code
= 0;
1253 if (memorystatus_freeze_enabled
== FALSE
) {
1254 printf("sysctl_freeze: Freeze is DISABLED\n");
1258 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1259 if (error
|| !req
->newptr
) {
1263 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1264 vm_pageout_anonymous_pages();
1269 lck_mtx_lock(&freezer_mutex
);
1273 uint32_t purgeable
, wired
, clean
, dirty
, shared
;
1274 uint32_t max_pages
= 0, state
= 0;
1276 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1278 * Freezer backed by the compressor and swap file(s)
1279 * will hold compressed data.
1281 * Set the sysctl kern.memorystatus_freeze_to_memory to true to keep compressed data from
1282 * being swapped out to disk. Note that this disables freezer swap support globally,
1283 * not just for the process being frozen.
1286 * We don't care about the global freezer budget or the process's (min/max) budget here.
1287 * The freeze sysctl is meant to force-freeze a process.
1289 * We also don't update any global or process stats on this path, so that the jetsam/ freeze
1290 * logic remains unaffected. The tasks we're performing here are: freeze the process, set the
1291 * P_MEMSTAT_FROZEN bit, and elevate the process to a higher band (if the freezer is active).
1293 max_pages
= memorystatus_freeze_pages_max
;
1296 * We only have the compressor without any swap.
1298 max_pages
= UINT32_MAX
- 1;
1302 state
= p
->p_memstat_state
;
1306 * The jetsam path also verifies that the process is a suspended App. We don't care about that here.
1307 * We simply ensure that jetsam is not already working on the process and that the process has not
1308 * explicitly disabled freezing.
1310 if (state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FREEZE_DISABLED
)) {
1311 printf("sysctl_freeze: p_memstat_state check failed, process is%s%s%s\n",
1312 (state
& P_MEMSTAT_TERMINATED
) ? " terminated" : "",
1313 (state
& P_MEMSTAT_LOCKED
) ? " locked" : "",
1314 (state
& P_MEMSTAT_FREEZE_DISABLED
) ? " unfreezable" : "");
1317 lck_mtx_unlock(&freezer_mutex
);
1321 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, &freezer_error_code
, FALSE
/* eval only */);
1325 if (freezer_error_code
== FREEZER_ERROR_EXCESS_SHARED_MEMORY
) {
1326 strlcpy(reason
, "too much shared memory", 128);
1329 if (freezer_error_code
== FREEZER_ERROR_LOW_PRIVATE_SHARED_RATIO
) {
1330 strlcpy(reason
, "low private-shared pages ratio", 128);
1333 if (freezer_error_code
== FREEZER_ERROR_NO_COMPRESSOR_SPACE
) {
1334 strlcpy(reason
, "no compressor space", 128);
1337 if (freezer_error_code
== FREEZER_ERROR_NO_SWAP_SPACE
) {
1338 strlcpy(reason
, "no swap space", 128);
1341 printf("sysctl_freeze: task_freeze failed: %s\n", reason
);
1343 if (error
== KERN_NO_SPACE
) {
1344 /* Make it easy to distinguish between failures due to low compressor/ swap space and other failures. */
1351 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == 0) {
1352 p
->p_memstat_state
|= P_MEMSTAT_FROZEN
;
1353 memorystatus_frozen_count
++;
1355 p
->p_memstat_frozen_count
++;
1360 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1362 * We elevate only if we are going to swap out the data.
1364 error
= memorystatus_update_inactive_jetsam_priority_band(pid
, MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
,
1365 memorystatus_freeze_jetsam_band
, TRUE
);
1368 printf("sysctl_freeze: Elevating frozen process to higher jetsam band failed with %d\n", error
);
1375 lck_mtx_unlock(&freezer_mutex
);
1378 printf("sysctl_freeze: Invalid process\n");
1382 lck_mtx_unlock(&freezer_mutex
);
1386 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
1387 0, 0, &sysctl_memorystatus_freeze
, "I", "");
1390 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1392 #pragma unused(arg1, arg2)
1397 if (memorystatus_freeze_enabled
== FALSE
) {
1401 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1402 if (error
|| !req
->newptr
) {
1406 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1407 do_fastwake_warmup_all();
1412 error
= task_thaw(p
->task
);
1418 * task_thaw() succeeded.
1420 * We increment memorystatus_frozen_count on the sysctl freeze path.
1421 * And so we need the P_MEMSTAT_FROZEN to decrement the frozen count
1422 * when this process exits.
1425 * p->p_memstat_state &= ~P_MEMSTAT_FROZEN;
1426 * proc_list_unlock();
1437 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
1438 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
1440 typedef struct _global_freezable_status
{
1441 boolean_t freeze_pages_threshold_crossed
;
1442 boolean_t freeze_eligible_procs_available
;
1443 boolean_t freeze_scheduled_in_future
;
1444 }global_freezable_status_t
;
1446 typedef struct _proc_freezable_status
{
1447 boolean_t freeze_has_memstat_state
;
1448 boolean_t freeze_has_pages_min
;
1449 int freeze_has_probability
;
1450 boolean_t freeze_attempted
;
1451 uint32_t p_memstat_state
;
1453 int p_freeze_error_code
;
1455 char p_name
[MAXCOMLEN
+ 1];
1456 }proc_freezable_status_t
;
1458 #define MAX_FREEZABLE_PROCESSES 100
1461 memorystatus_freezer_get_status(user_addr_t buffer
, size_t buffer_size
, int32_t *retval
)
1463 uint32_t proc_count
= 0, i
= 0;
1464 global_freezable_status_t
*list_head
;
1465 proc_freezable_status_t
*list_entry
;
1466 size_t list_size
= 0;
1468 memstat_bucket_t
*bucket
;
1469 uint32_t state
= 0, pages
= 0, entry_count
= 0;
1470 boolean_t try_freeze
= TRUE
;
1471 int error
= 0, probability_of_use
= 0;
1474 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
== FALSE
) {
1478 list_size
= sizeof(global_freezable_status_t
) + (sizeof(proc_freezable_status_t
) * MAX_FREEZABLE_PROCESSES
);
1480 if (buffer_size
< list_size
) {
1484 list_head
= (global_freezable_status_t
*)kalloc(list_size
);
1485 if (list_head
== NULL
) {
1489 memset(list_head
, 0, list_size
);
1491 list_size
= sizeof(global_freezable_status_t
);
1495 uint64_t curr_time
= mach_absolute_time();
1497 list_head
->freeze_pages_threshold_crossed
= (memorystatus_available_pages
< memorystatus_freeze_threshold
);
1498 list_head
->freeze_eligible_procs_available
= ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
);
1499 list_head
->freeze_scheduled_in_future
= (curr_time
< memorystatus_freezer_thread_next_run_ts
);
1501 list_entry
= (proc_freezable_status_t
*) ((uintptr_t)list_head
+ sizeof(global_freezable_status_t
));
1503 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
1505 entry_count
= (memorystatus_global_probabilities_size
/ sizeof(memorystatus_internal_probabilities_t
));
1507 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
1510 while ((proc_count
<= MAX_FREEZABLE_PROCESSES
) &&
1512 (list_size
< buffer_size
)) {
1513 if (isApp(p
) == FALSE
) {
1514 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
1519 strlcpy(list_entry
->p_name
, p
->p_name
, MAXCOMLEN
+ 1);
1521 list_entry
->p_pid
= p
->p_pid
;
1523 state
= p
->p_memstat_state
;
1525 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FREEZE_DISABLED
| P_MEMSTAT_FREEZE_IGNORE
)) ||
1526 !(state
& P_MEMSTAT_SUSPENDED
)) {
1527 try_freeze
= list_entry
->freeze_has_memstat_state
= FALSE
;
1529 try_freeze
= list_entry
->freeze_has_memstat_state
= TRUE
;
1532 list_entry
->p_memstat_state
= state
;
1534 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
);
1535 if (pages
< memorystatus_freeze_pages_min
) {
1536 try_freeze
= list_entry
->freeze_has_pages_min
= FALSE
;
1538 list_entry
->freeze_has_pages_min
= TRUE
;
1539 if (try_freeze
!= FALSE
) {
1544 list_entry
->p_pages
= pages
;
1548 for (j
= 0; j
< entry_count
; j
++) {
1549 if (strncmp(memorystatus_global_probabilities_table
[j
].proc_name
,
1551 MAXCOMLEN
+ 1) == 0) {
1552 probability_of_use
= memorystatus_global_probabilities_table
[j
].use_probability
;
1557 list_entry
->freeze_has_probability
= probability_of_use
;
1559 if (probability_of_use
&& try_freeze
!= FALSE
) {
1565 if (try_freeze
!= FALSE
) {
1568 list_entry
->freeze_has_probability
= -1;
1572 uint32_t purgeable
, wired
, clean
, dirty
, shared
;
1573 uint32_t max_pages
= 0;
1574 int freezer_error_code
= 0;
1576 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, &freezer_error_code
, TRUE
/* eval only */);
1579 list_entry
->p_freeze_error_code
= freezer_error_code
;
1582 list_entry
->freeze_attempted
= TRUE
;
1587 list_size
+= sizeof(proc_freezable_status_t
);
1589 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
1595 buffer_size
= list_size
;
1597 error
= copyout(list_head
, buffer
, buffer_size
);
1599 *retval
= buffer_size
;
1604 list_size
= sizeof(global_freezable_status_t
) + (sizeof(proc_freezable_status_t
) * MAX_FREEZABLE_PROCESSES
);
1605 kfree(list_head
, list_size
);
1607 MEMORYSTATUS_DEBUG(1, "memorystatus_freezer_get_status: returning %d (%lu - size)\n", error
, (unsigned long)*list_size
);
1613 memorystatus_freezer_control(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
)
1617 if (flags
== FREEZER_CONTROL_GET_STATUS
) {
1618 err
= memorystatus_freezer_get_status(buffer
, buffer_size
, retval
);
1624 #endif /* CONFIG_FREEZE */
1626 #endif /* DEVELOPMENT || DEBUG */
1628 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
1631 thread_t
*new_thread
);
1633 #if DEVELOPMENT || DEBUG
1636 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1638 #pragma unused(arg1, arg2)
1639 int error
= 0, pid
= 0;
1642 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1643 if (error
|| !req
->newptr
) {
1647 lck_mtx_lock(&disconnect_page_mappings_mutex
);
1650 vm_pageout_disconnect_all_pages();
1655 error
= task_disconnect_page_mappings(p
->task
);
1666 lck_mtx_unlock(&disconnect_page_mappings_mutex
);
1671 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_disconnect_page_mappings
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
1672 0, 0, &sysctl_memorystatus_disconnect_page_mappings
, "I", "");
1674 #endif /* DEVELOPMENT || DEBUG */
1678 * Picks the sorting routine for a given jetsam priority band.
1681 * bucket_index - jetsam priority band to be sorted.
1682 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1683 * Currently sort_order is only meaningful when handling
1691 memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
1693 int coal_sort_order
;
1696 * Verify the jetsam priority
1698 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1702 #if DEVELOPMENT || DEBUG
1703 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1704 coal_sort_order
= COALITION_SORT_DEFAULT
;
1706 coal_sort_order
= sort_order
; /* only used for testing scenarios */
1709 /* Verify default */
1710 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1711 coal_sort_order
= COALITION_SORT_DEFAULT
;
1719 if (memstat_bucket
[bucket_index
].count
== 0) {
1724 switch (bucket_index
) {
1725 case JETSAM_PRIORITY_FOREGROUND
:
1726 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
1728 * Fall back to per process sorting when zero coalitions are found.
1730 memorystatus_sort_by_largest_process_locked(bucket_index
);
1734 memorystatus_sort_by_largest_process_locked(bucket_index
);
1743 * Sort processes by size for a single jetsam bucket.
1747 memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
1749 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
1750 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
1751 uint32_t pages
= 0, max_pages
= 0;
1752 memstat_bucket_t
*current_bucket
;
1754 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1758 current_bucket
= &memstat_bucket
[bucket_index
];
1760 p
= TAILQ_FIRST(¤t_bucket
->list
);
1763 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
);
1768 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
1769 /* traversing list until we find next largest process */
1771 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
);
1772 if (pages
> max_pages
) {
1778 if (prev_max_proc
!= max_proc
) {
1779 /* found a larger process, place it in the list */
1780 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1781 if (insert_after_proc
== NULL
) {
1782 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1784 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1786 prev_max_proc
= max_proc
;
1789 insert_after_proc
= max_proc
;
1791 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1796 memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
)
1798 memstat_bucket_t
*current_bucket
;
1801 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1805 current_bucket
= &memstat_bucket
[*bucket_index
];
1806 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1807 if (!next_p
&& search
) {
1808 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1809 current_bucket
= &memstat_bucket
[*bucket_index
];
1810 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1818 memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
)
1820 memstat_bucket_t
*current_bucket
;
1823 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1827 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1828 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1829 current_bucket
= &memstat_bucket
[*bucket_index
];
1830 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1837 * Structure to hold state for a jetsam thread.
1838 * Typically there should be a single jetsam thread
1839 * unless parallel jetsam is enabled.
1841 struct jetsam_thread_state
{
1842 boolean_t inited
; /* if the thread is initialized */
1843 int memorystatus_wakeup
; /* wake channel */
1844 int index
; /* jetsam thread index */
1845 thread_t thread
; /* jetsam thread pointer */
1848 /* Maximum number of jetsam threads allowed */
1849 #define JETSAM_THREADS_LIMIT 3
1851 /* Number of active jetsam threads */
1852 _Atomic
int active_jetsam_threads
= 1;
1854 /* Number of maximum jetsam threads configured */
1855 int max_jetsam_threads
= JETSAM_THREADS_LIMIT
;
1858 * Global switch for enabling fast jetsam. Fast jetsam is
1859 * hooked up via the system_override() system call. It has the
1860 * following effects:
1861 * - Raise the jetsam threshold ("clear-the-deck")
1862 * - Enabled parallel jetsam on eligible devices
1864 int fast_jetsam_enabled
= 0;
1866 /* Routine to find the jetsam state structure for the current jetsam thread */
1867 static inline struct jetsam_thread_state
*
1868 jetsam_current_thread(void)
1870 for (int thr_id
= 0; thr_id
< max_jetsam_threads
; thr_id
++) {
1871 if (jetsam_threads
[thr_id
].thread
== current_thread()) {
1872 return &(jetsam_threads
[thr_id
]);
1875 panic("jetsam_current_thread() is being called from a non-jetsam thread\n");
1876 /* Contol should not reach here */
1881 __private_extern__
void
1882 memorystatus_init(void)
1884 kern_return_t result
;
1888 memorystatus_freeze_jetsam_band
= JETSAM_PRIORITY_UI_SUPPORT
;
1889 memorystatus_frozen_processes_max
= FREEZE_PROCESSES_MAX
;
1890 memorystatus_frozen_shared_mb_max
= ((MAX_FROZEN_SHARED_MB_PERCENT
* max_task_footprint_mb
) / 100); /* 10% of the system wide task limit */
1891 memorystatus_freeze_shared_mb_per_process_max
= (memorystatus_frozen_shared_mb_max
/ 4);
1892 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1893 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1894 memorystatus_max_frozen_demotions_daily
= MAX_FROZEN_PROCESS_DEMOTIONS
;
1895 memorystatus_thaw_count_demotion_threshold
= MIN_THAW_DEMOTION_THRESHOLD
;
1898 #if DEVELOPMENT || DEBUG
1899 disconnect_page_mappings_lck_grp_attr
= lck_grp_attr_alloc_init();
1900 disconnect_page_mappings_lck_grp
= lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr
);
1902 lck_mtx_init(&disconnect_page_mappings_mutex
, disconnect_page_mappings_lck_grp
, NULL
);
1904 if (kill_on_no_paging_space
== TRUE
) {
1905 max_kill_priority
= JETSAM_PRIORITY_MAX
;
1911 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1912 TAILQ_INIT(&memstat_bucket
[i
].list
);
1913 memstat_bucket
[i
].count
= 0;
1915 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1918 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
1919 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
1921 /* Apply overrides */
1922 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1923 if (delta_percentage
== 0) {
1924 delta_percentage
= 5;
1926 assert(delta_percentage
< 100);
1927 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1928 assert(critical_threshold_percentage
< 100);
1929 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1930 assert(idle_offset_percentage
< 100);
1931 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1932 assert(pressure_threshold_percentage
< 100);
1933 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1934 assert(freeze_threshold_percentage
< 100);
1936 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy
,
1937 sizeof(jetsam_aging_policy
))) {
1938 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy
,
1939 sizeof(jetsam_aging_policy
))) {
1940 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1944 if (jetsam_aging_policy
> kJetsamAgingPolicyMax
) {
1945 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1948 switch (jetsam_aging_policy
) {
1949 case kJetsamAgingPolicyNone
:
1950 system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
1951 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1954 case kJetsamAgingPolicyLegacy
:
1956 * Legacy behavior where some daemons get a 10s protection once
1957 * AND only before the first clean->dirty->clean transition before
1958 * going into IDLE band.
1960 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1961 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1964 case kJetsamAgingPolicySysProcsReclaimedFirst
:
1965 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1966 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1969 case kJetsamAgingPolicyAppsReclaimedFirst
:
1970 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1971 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1979 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1980 * band and must be below it in priority. This is so that we don't have to make
1981 * our 'aging' code worry about a mix of processes, some of which need to age
1982 * and some others that need to stay elevated in the jetsam bands.
1984 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> system_procs_aging_band
);
1985 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> applications_aging_band
);
1987 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1988 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
))) {
1989 /* ...no boot-arg, so check the device tree */
1990 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1993 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1994 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1995 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1996 memorystatus_policy_more_free_offset_pages
= (policy_more_free_offset_percentage
/ delta_percentage
) * memorystatus_delta
;
1998 /* Jetsam Loop Detection */
1999 if (max_mem
<= (512 * 1024 * 1024)) {
2000 /* 512 MB devices */
2001 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
2003 /* 1GB and larger devices */
2004 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
2007 memorystatus_jld_enabled
= TRUE
;
2009 /* No contention at this point */
2010 memorystatus_update_levels_locked(FALSE
);
2012 #endif /* CONFIG_JETSAM */
2014 memorystatus_jetsam_snapshot_max
= maxproc
;
2016 memorystatus_jetsam_snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
2017 (sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
2019 memorystatus_jetsam_snapshot
=
2020 (memorystatus_jetsam_snapshot_t
*)kalloc(memorystatus_jetsam_snapshot_size
);
2021 if (!memorystatus_jetsam_snapshot
) {
2022 panic("Could not allocate memorystatus_jetsam_snapshot");
2025 memorystatus_jetsam_snapshot_copy
=
2026 (memorystatus_jetsam_snapshot_t
*)kalloc(memorystatus_jetsam_snapshot_size
);
2027 if (!memorystatus_jetsam_snapshot_copy
) {
2028 panic("Could not allocate memorystatus_jetsam_snapshot_copy");
2031 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
2033 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
2036 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
2039 /* Check the boot-arg to see if fast jetsam is allowed */
2040 if (!PE_parse_boot_argn("fast_jetsam_enabled", &fast_jetsam_enabled
, sizeof(fast_jetsam_enabled
))) {
2041 fast_jetsam_enabled
= 0;
2044 /* Check the boot-arg to configure the maximum number of jetsam threads */
2045 if (!PE_parse_boot_argn("max_jetsam_threads", &max_jetsam_threads
, sizeof(max_jetsam_threads
))) {
2046 max_jetsam_threads
= JETSAM_THREADS_LIMIT
;
2049 /* Restrict the maximum number of jetsam threads to JETSAM_THREADS_LIMIT */
2050 if (max_jetsam_threads
> JETSAM_THREADS_LIMIT
) {
2051 max_jetsam_threads
= JETSAM_THREADS_LIMIT
;
2054 /* For low CPU systems disable fast jetsam mechanism */
2055 if (vm_pageout_state
.vm_restricted_to_single_processor
== TRUE
) {
2056 max_jetsam_threads
= 1;
2057 fast_jetsam_enabled
= 0;
2060 /* Initialize the jetsam_threads state array */
2061 jetsam_threads
= kalloc(sizeof(struct jetsam_thread_state
) * max_jetsam_threads
);
2063 /* Initialize all the jetsam threads */
2064 for (i
= 0; i
< max_jetsam_threads
; i
++) {
2065 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &jetsam_threads
[i
].thread
);
2066 if (result
== KERN_SUCCESS
) {
2067 jetsam_threads
[i
].inited
= FALSE
;
2068 jetsam_threads
[i
].index
= i
;
2069 thread_deallocate(jetsam_threads
[i
].thread
);
2071 panic("Could not create memorystatus_thread %d", i
);
2076 /* Centralised for the purposes of allowing panic-on-jetsam */
2078 vm_run_compactor(void);
2081 * The jetsam no frills kill call
2082 * Return: 0 on success
2083 * error code on failure (EINVAL...)
2086 jetsam_do_kill(proc_t p
, int jetsam_flags
, os_reason_t jetsam_reason
)
2089 error
= exit_with_reason(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
, jetsam_reason
);
2094 * Wrapper for processes exiting with memorystatus details
2097 memorystatus_do_kill(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
)
2100 __unused pid_t victim_pid
= p
->p_pid
;
2102 KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
2103 victim_pid
, cause
, vm_page_free_count
, 0, 0);
2105 DTRACE_MEMORYSTATUS3(memorystatus_do_kill
, proc_t
, p
, os_reason_t
, jetsam_reason
, uint32_t, cause
);
2106 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
2107 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
2108 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
2111 #pragma unused(cause)
2114 if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
2115 printf("memorystatus: killing process %d [%s] in high band %s (%d) - memorystatus_available_pages: %llu\n", p
->p_pid
,
2116 (*p
->p_name
? p
->p_name
: "unknown"),
2117 memorystatus_priority_band_name(p
->p_memstat_effectivepriority
), p
->p_memstat_effectivepriority
,
2118 (uint64_t)memorystatus_available_pages
);
2122 * The jetsam_reason (os_reason_t) has enough information about the kill cause.
2123 * We don't really need jetsam_flags anymore, so it's okay that not all possible kill causes have been mapped.
2125 int jetsam_flags
= P_LTERM_JETSAM
;
2127 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
2128 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
2129 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
2130 case kMemorystatusKilledVMCompressorThrashing
:
2131 case kMemorystatusKilledVMCompressorSpaceShortage
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
2132 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
2133 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
2134 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
2136 error
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
2138 KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
2139 victim_pid
, cause
, vm_page_free_count
, error
, 0);
2151 memorystatus_check_levels_locked(void)
2155 memorystatus_update_levels_locked(TRUE
);
2156 #else /* CONFIG_JETSAM */
2158 * Nothing to do here currently since we update
2159 * memorystatus_available_pages in vm_pressure_response.
2161 #endif /* CONFIG_JETSAM */
2165 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
2166 * For an application: that means no longer in the FG band
2167 * For a daemon: that means no longer in its 'requested' jetsam priority band
2171 memorystatus_update_inactive_jetsam_priority_band(pid_t pid
, uint32_t op_flags
, int jetsam_prio
, boolean_t effective_now
)
2174 boolean_t enable
= FALSE
;
2177 if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
) {
2179 } else if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
) {
2187 if ((enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) ||
2188 (!enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == 0))) {
2190 * No change in state.
2196 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
2197 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2199 if (effective_now
) {
2200 if (p
->p_memstat_effectivepriority
< jetsam_prio
) {
2201 if (memorystatus_highwater_enabled
) {
2203 * Process is about to transition from
2204 * inactive --> active
2205 * assign active state
2208 boolean_t use_active
= TRUE
;
2209 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2210 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
2212 memorystatus_update_priority_locked(p
, jetsam_prio
, FALSE
, FALSE
);
2215 if (isProcessInAgingBands(p
)) {
2216 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2220 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
2221 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2223 if (effective_now
) {
2224 if (p
->p_memstat_effectivepriority
== jetsam_prio
) {
2225 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2228 if (isProcessInAgingBands(p
)) {
2229 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2246 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
2249 uint64_t current_time
= 0, idle_delay_time
= 0;
2250 int demote_prio_band
= 0;
2251 memstat_bucket_t
*demotion_bucket
;
2253 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
2255 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
2257 current_time
= mach_absolute_time();
2261 demote_prio_band
= JETSAM_PRIORITY_IDLE
+ 1;
2263 for (; demote_prio_band
< JETSAM_PRIORITY_MAX
; demote_prio_band
++) {
2264 if (demote_prio_band
!= system_procs_aging_band
&& demote_prio_band
!= applications_aging_band
) {
2268 demotion_bucket
= &memstat_bucket
[demote_prio_band
];
2269 p
= TAILQ_FIRST(&demotion_bucket
->list
);
2272 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
2274 assert(p
->p_memstat_idledeadline
);
2276 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2278 if (current_time
>= p
->p_memstat_idledeadline
) {
2279 if ((isSysProc(p
) &&
2280 ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
| P_DIRTY_IS_DIRTY
)) != P_DIRTY_IDLE_EXIT_ENABLED
)) || /* system proc marked dirty*/
2281 task_has_assertions((struct task
*)(p
->task
))) { /* has outstanding assertions which might indicate outstanding work too */
2282 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
2284 p
->p_memstat_idledeadline
+= idle_delay_time
;
2285 p
= TAILQ_NEXT(p
, p_memstat_list
);
2287 proc_t next_proc
= NULL
;
2289 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
2290 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2292 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false, true);
2298 // No further candidates
2304 memorystatus_reschedule_idle_demotion_locked();
2308 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
2312 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
2314 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
2315 boolean_t present_in_apps_aging_bucket
= FALSE
;
2316 uint64_t idle_delay_time
= 0;
2318 if (jetsam_aging_policy
== kJetsamAgingPolicyNone
) {
2322 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
2324 * This process isn't going to be making the trip to the lower bands.
2329 if (isProcessInAgingBands(p
)) {
2330 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
2331 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) != P_DIRTY_AGING_IN_PROGRESS
);
2334 if (isSysProc(p
) && system_procs_aging_band
) {
2335 present_in_sysprocs_aging_bucket
= TRUE
;
2336 } else if (isApp(p
) && applications_aging_band
) {
2337 present_in_apps_aging_bucket
= TRUE
;
2341 assert(!present_in_sysprocs_aging_bucket
);
2342 assert(!present_in_apps_aging_bucket
);
2344 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",
2345 p
->p_pid
, p
->p_memstat_dirty
, set_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
2348 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
2351 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
2354 p
->p_memstat_dirty
|= P_DIRTY_AGING_IN_PROGRESS
;
2355 p
->p_memstat_idledeadline
= mach_absolute_time() + idle_delay_time
;
2358 assert(p
->p_memstat_idledeadline
);
2360 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== FALSE
) {
2361 memorystatus_scheduled_idle_demotions_sysprocs
++;
2362 } else if (isApp(p
) && present_in_apps_aging_bucket
== FALSE
) {
2363 memorystatus_scheduled_idle_demotions_apps
++;
2368 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
2370 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
2371 boolean_t present_in_apps_aging_bucket
= FALSE
;
2373 if (!system_procs_aging_band
&& !applications_aging_band
) {
2377 if ((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0) {
2381 if (isProcessInAgingBands(p
)) {
2382 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
2383 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == P_DIRTY_AGING_IN_PROGRESS
);
2386 if (isSysProc(p
) && system_procs_aging_band
) {
2387 assert(p
->p_memstat_effectivepriority
== system_procs_aging_band
);
2388 assert(p
->p_memstat_idledeadline
);
2389 present_in_sysprocs_aging_bucket
= TRUE
;
2390 } else if (isApp(p
) && applications_aging_band
) {
2391 assert(p
->p_memstat_effectivepriority
== applications_aging_band
);
2392 assert(p
->p_memstat_idledeadline
);
2393 present_in_apps_aging_bucket
= TRUE
;
2397 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
2398 p
->p_pid
, clear_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
2402 p
->p_memstat_idledeadline
= 0;
2403 p
->p_memstat_dirty
&= ~P_DIRTY_AGING_IN_PROGRESS
;
2406 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== TRUE
) {
2407 memorystatus_scheduled_idle_demotions_sysprocs
--;
2408 assert(memorystatus_scheduled_idle_demotions_sysprocs
>= 0);
2409 } else if (isApp(p
) && present_in_apps_aging_bucket
== TRUE
) {
2410 memorystatus_scheduled_idle_demotions_apps
--;
2411 assert(memorystatus_scheduled_idle_demotions_apps
>= 0);
2414 assert((memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
) >= 0);
2418 memorystatus_reschedule_idle_demotion_locked(void)
2420 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
)) {
2421 if (memstat_idle_demotion_deadline
) {
2422 /* Transitioned 1->0, so cancel next call */
2423 thread_call_cancel(memorystatus_idle_demotion_call
);
2424 memstat_idle_demotion_deadline
= 0;
2427 memstat_bucket_t
*demotion_bucket
;
2428 proc_t p
= NULL
, p1
= NULL
, p2
= NULL
;
2430 if (system_procs_aging_band
) {
2431 demotion_bucket
= &memstat_bucket
[system_procs_aging_band
];
2432 p1
= TAILQ_FIRST(&demotion_bucket
->list
);
2437 if (applications_aging_band
) {
2438 demotion_bucket
= &memstat_bucket
[applications_aging_band
];
2439 p2
= TAILQ_FIRST(&demotion_bucket
->list
);
2442 p
= (p1
->p_memstat_idledeadline
> p2
->p_memstat_idledeadline
) ? p2
: p1
;
2444 p
= (p1
== NULL
) ? p2
: p1
;
2451 assert(p
&& p
->p_memstat_idledeadline
);
2452 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
) {
2453 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
2454 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
2465 memorystatus_add(proc_t p
, boolean_t locked
)
2467 memstat_bucket_t
*bucket
;
2469 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
2475 DTRACE_MEMORYSTATUS2(memorystatus_add
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
);
2477 /* Processes marked internal do not have priority tracked */
2478 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2482 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2484 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2485 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
- 1);
2486 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2487 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
- 1);
2488 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2490 * Entering the idle band.
2491 * Record idle start time.
2493 p
->p_memstat_idle_start
= mach_absolute_time();
2496 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
2499 memorystatus_list_count
++;
2501 memorystatus_check_levels_locked();
2513 * Moves a process from one jetsam bucket to another.
2514 * which changes the LRU position of the process.
2516 * Monitors transition between buckets and if necessary
2517 * will update cached memory limits accordingly.
2519 * skip_demotion_check:
2520 * - if the 'jetsam aging policy' is NOT 'legacy':
2521 * When this flag is TRUE, it means we are going
2522 * to age the ripe processes out of the aging bands and into the
2523 * IDLE band and apply their inactive memory limits.
2525 * - if the 'jetsam aging policy' is 'legacy':
2526 * When this flag is TRUE, it might mean the above aging mechanism
2528 * It might be that we have a process that has used up its 'idle deferral'
2529 * stay that is given to it once per lifetime. And in this case, the process
2530 * won't be going through any aging codepaths. But we still need to apply
2531 * the right inactive limits and so we explicitly set this to TRUE if the
2532 * new priority for the process is the IDLE band.
2535 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
)
2537 memstat_bucket_t
*old_bucket
, *new_bucket
;
2539 assert(priority
< MEMSTAT_BUCKET_COUNT
);
2541 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2542 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2546 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2547 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, head_insert
? "head" : "tail");
2549 DTRACE_MEMORYSTATUS3(memorystatus_update_priority
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
, int, priority
);
2551 #if DEVELOPMENT || DEBUG
2552 if (priority
== JETSAM_PRIORITY_IDLE
&& /* if the process is on its way into the IDLE band */
2553 skip_demotion_check
== FALSE
&& /* and it isn't via the path that will set the INACTIVE memlimits */
2554 (p
->p_memstat_dirty
& P_DIRTY_TRACK
) && /* and it has 'DIRTY' tracking enabled */
2555 ((p
->p_memstat_memlimit
!= p
->p_memstat_memlimit_inactive
) || /* and we notice that the current limit isn't the right value (inactive) */
2556 ((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) */
2557 panic("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 */
2559 #endif /* DEVELOPMENT || DEBUG */
2561 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2563 if (skip_demotion_check
== FALSE
) {
2566 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2567 * the processes from the aging bands and balancing the demotion counts.
2568 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2571 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
2573 * 2 types of processes can use the non-standard elevated inactive band:
2574 * - Frozen processes that always land in memorystatus_freeze_jetsam_band
2576 * - processes that specifically opt-in to the elevated inactive support e.g. docked processes.
2579 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
2580 if (priority
<= memorystatus_freeze_jetsam_band
) {
2581 priority
= memorystatus_freeze_jetsam_band
;
2584 #endif /* CONFIG_FREEZE */
2586 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
2587 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2590 assert(!(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2592 } else if (isApp(p
)) {
2594 * Check to see if the application is being lowered in jetsam priority. If so, and:
2595 * - it has an 'elevated inactive jetsam band' attribute, then put it in the appropriate band.
2596 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2599 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
2601 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
2602 if (priority
<= memorystatus_freeze_jetsam_band
) {
2603 priority
= memorystatus_freeze_jetsam_band
;
2606 #endif /* CONFIG_FREEZE */
2608 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
2609 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2613 if (applications_aging_band
) {
2614 if (p
->p_memstat_effectivepriority
== applications_aging_band
) {
2615 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions_apps
+ 1));
2618 if ((jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) && (priority
<= applications_aging_band
)) {
2619 assert(!(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2620 priority
= applications_aging_band
;
2621 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2628 if ((system_procs_aging_band
&& (priority
== system_procs_aging_band
)) || (applications_aging_band
&& (priority
== applications_aging_band
))) {
2629 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2632 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
2633 old_bucket
->count
--;
2635 new_bucket
= &memstat_bucket
[priority
];
2637 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
2639 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
2641 new_bucket
->count
++;
2643 if (memorystatus_highwater_enabled
) {
2645 boolean_t use_active
;
2648 * If cached limit data is updated, then the limits
2649 * will be enforced by writing to the ledgers.
2651 boolean_t ledger_update_needed
= TRUE
;
2654 * Here, we must update the cached memory limit if the task
2655 * is transitioning between:
2656 * active <--> inactive
2659 * dirty <--> clean is ignored
2661 * We bypass non-idle processes that have opted into dirty tracking because
2662 * a move between buckets does not imply a transition between the
2663 * dirty <--> clean state.
2666 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2667 if (skip_demotion_check
== TRUE
&& priority
== JETSAM_PRIORITY_IDLE
) {
2668 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2671 ledger_update_needed
= FALSE
;
2673 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
2675 * inactive --> active
2677 * assign active state
2679 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2681 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
2683 * active --> inactive
2685 * assign inactive state
2687 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2691 * The transition between jetsam priority buckets apparently did
2692 * not affect active/inactive state.
2693 * This is not unusual... especially during startup when
2694 * processes are getting established in their respective bands.
2696 ledger_update_needed
= FALSE
;
2700 * Enforce the new limits by writing to the ledger
2702 if (ledger_update_needed
) {
2703 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
2705 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2706 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2707 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
2708 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2713 * Record idle start or idle delta.
2715 if (p
->p_memstat_effectivepriority
== priority
) {
2717 * This process is not transitioning between
2718 * jetsam priority buckets. Do nothing.
2720 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2723 * Transitioning out of the idle priority bucket.
2724 * Record idle delta.
2726 assert(p
->p_memstat_idle_start
!= 0);
2727 now
= mach_absolute_time();
2728 if (now
> p
->p_memstat_idle_start
) {
2729 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2733 * About to become active and so memory footprint could change.
2734 * So mark it eligible for freeze-considerations next time around.
2736 if (p
->p_memstat_state
& P_MEMSTAT_FREEZE_IGNORE
) {
2737 p
->p_memstat_state
&= ~P_MEMSTAT_FREEZE_IGNORE
;
2739 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
2741 * Transitioning into the idle priority bucket.
2742 * Record idle start.
2744 p
->p_memstat_idle_start
= mach_absolute_time();
2747 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CHANGE_PRIORITY
), p
->p_pid
, priority
, p
->p_memstat_effectivepriority
, 0, 0);
2749 p
->p_memstat_effectivepriority
= priority
;
2751 #if CONFIG_SECLUDED_MEMORY
2752 if (secluded_for_apps
&&
2753 task_could_use_secluded_mem(p
->task
)) {
2754 task_set_can_use_secluded_mem(
2756 (priority
>= JETSAM_PRIORITY_FOREGROUND
));
2758 #endif /* CONFIG_SECLUDED_MEMORY */
2760 memorystatus_check_levels_locked();
2765 * Description: Update the jetsam priority and memory limit attributes for a given process.
2768 * p init this process's jetsam information.
2769 * priority The jetsam priority band
2770 * user_data user specific data, unused by the kernel
2771 * effective guards against race if process's update already occurred
2772 * update_memlimit When true we know this is the init step via the posix_spawn path.
2774 * memlimit_active Value in megabytes; The monitored footprint level while the
2775 * process is active. Exceeding it may result in termination
2776 * based on it's associated fatal flag.
2778 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2779 * this describes whether or not it should be immediately fatal.
2781 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2782 * process is inactive. Exceeding it may result in termination
2783 * based on it's associated fatal flag.
2785 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2786 * this describes whether or not it should be immediatly fatal.
2788 * Returns: 0 Success
2793 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
2794 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
2795 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
)
2798 boolean_t head_insert
= false;
2800 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
);
2802 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
2804 if (priority
== -1) {
2805 /* Use as shorthand for default priority */
2806 priority
= JETSAM_PRIORITY_DEFAULT
;
2807 } else if ((priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
2808 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2809 priority
= JETSAM_PRIORITY_IDLE
;
2810 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
2811 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2812 priority
= JETSAM_PRIORITY_IDLE
;
2814 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
2822 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2824 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
2827 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
2831 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
2833 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2840 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
2841 p
->p_memstat_userdata
= user_data
;
2842 p
->p_memstat_requestedpriority
= priority
;
2844 if (update_memlimit
) {
2846 boolean_t use_active
;
2849 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2850 * Forked processes do not come through this path, so no ledger limits exist.
2851 * (That's why forked processes can consume unlimited memory.)
2854 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2855 p
->p_pid
, priority
, p
->p_memstat_dirty
,
2856 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2857 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2859 if (memlimit_active
<= 0) {
2861 * This process will have a system_wide task limit when active.
2862 * System_wide task limit is always fatal.
2863 * It's quite common to see non-fatal flag passed in here.
2864 * It's not an error, we just ignore it.
2868 * For backward compatibility with some unexplained launchd behavior,
2869 * we allow a zero sized limit. But we still enforce system_wide limit
2870 * when written to the ledgers.
2873 if (memlimit_active
< 0) {
2874 memlimit_active
= -1; /* enforces system_wide task limit */
2876 memlimit_active_is_fatal
= TRUE
;
2879 if (memlimit_inactive
<= 0) {
2881 * This process will have a system_wide task limit when inactive.
2882 * System_wide task limit is always fatal.
2885 memlimit_inactive
= -1;
2886 memlimit_inactive_is_fatal
= TRUE
;
2890 * Initialize the active limit variants for this process.
2892 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
2895 * Initialize the inactive limit variants for this process.
2897 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
2900 * Initialize the cached limits for target process.
2901 * When the target process is dirty tracked, it's typically
2902 * in a clean state. Non dirty tracked processes are
2903 * typically active (Foreground or above).
2904 * But just in case, we don't make assumptions...
2907 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2908 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2911 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2916 * Enforce the cached limit by writing to the ledger.
2918 if (memorystatus_highwater_enabled
) {
2920 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, use_active
, is_fatal
);
2922 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2923 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2924 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
2925 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2930 * We can't add to the aging bands buckets here.
2931 * But, we could be removing it from those buckets.
2932 * Check and take appropriate steps if so.
2935 if (isProcessInAgingBands(p
)) {
2936 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2937 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2939 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
&& priority
== JETSAM_PRIORITY_IDLE
) {
2941 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2942 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2943 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2944 * is any other aging policy, then we don't need to worry because all processes
2945 * will go through the aging bands and then the demotion thread will take care to
2946 * move them into the IDLE band and apply the required limits.
2948 memorystatus_update_priority_locked(p
, priority
, head_insert
, TRUE
);
2952 memorystatus_update_priority_locked(p
, priority
, head_insert
, FALSE
);
2958 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
2964 memorystatus_remove(proc_t p
, boolean_t locked
)
2967 memstat_bucket_t
*bucket
;
2968 boolean_t reschedule
= FALSE
;
2970 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
2976 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2978 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2980 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2981 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
);
2983 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2984 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
);
2992 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2993 uint64_t now
= mach_absolute_time();
2994 if (now
> p
->p_memstat_idle_start
) {
2995 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2999 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
3002 memorystatus_list_count
--;
3004 /* If awaiting demotion to the idle band, clean up */
3006 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3007 memorystatus_reschedule_idle_demotion_locked();
3010 memorystatus_check_levels_locked();
3013 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
3014 if (p
->p_memstat_state
& P_MEMSTAT_REFREEZE_ELIGIBLE
) {
3015 p
->p_memstat_state
&= ~P_MEMSTAT_REFREEZE_ELIGIBLE
;
3016 memorystatus_refreeze_eligible_count
--;
3019 memorystatus_frozen_count
--;
3020 memorystatus_frozen_shared_mb
-= p
->p_memstat_freeze_sharedanon_pages
;
3021 p
->p_memstat_freeze_sharedanon_pages
= 0;
3024 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3025 memorystatus_suspended_count
--;
3043 * Validate dirty tracking flags with process state.
3049 * The proc_list_lock is held by the caller.
3053 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
)
3055 /* See that the process isn't marked for termination */
3056 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
3060 /* Idle exit requires that process be tracked */
3061 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
3062 !(pcontrol
& PROC_DIRTY_TRACK
)) {
3066 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
3067 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
3068 !(pcontrol
& PROC_DIRTY_TRACK
)) {
3072 /* Only one type of DEFER behavior is allowed.*/
3073 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
3074 (pcontrol
& PROC_DIRTY_DEFER_ALWAYS
)) {
3078 /* Deferral is only relevant if idle exit is specified */
3079 if (((pcontrol
& PROC_DIRTY_DEFER
) ||
3080 (pcontrol
& PROC_DIRTY_DEFER_ALWAYS
)) &&
3081 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
3089 memorystatus_update_idle_priority_locked(proc_t p
)
3093 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
3095 assert(isSysProc(p
));
3097 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
| P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3098 priority
= (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) ? system_procs_aging_band
: JETSAM_PRIORITY_IDLE
;
3100 priority
= p
->p_memstat_requestedpriority
;
3103 if (priority
!= p
->p_memstat_effectivepriority
) {
3104 if ((jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) &&
3105 (priority
== JETSAM_PRIORITY_IDLE
)) {
3107 * This process is on its way into the IDLE band. The system is
3108 * using 'legacy' jetsam aging policy. That means, this process
3109 * has already used up its idle-deferral aging time that is given
3110 * once per its lifetime. So we need to set the INACTIVE limits
3111 * explicitly because it won't be going through the demotion paths
3112 * that take care to apply the limits appropriately.
3115 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
3117 * This process has the 'elevated inactive jetsam band' attribute.
3118 * So, there will be no trip to IDLE after all.
3119 * Instead, we pin the process in the elevated band,
3120 * where its ACTIVE limits will apply.
3123 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
3126 memorystatus_update_priority_locked(p
, priority
, false, true);
3128 memorystatus_update_priority_locked(p
, priority
, false, false);
3134 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
3135 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
3136 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
3137 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
3139 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
3140 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
3141 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
3142 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
3143 * band. The deferral can be cleared early by clearing the appropriate flag.
3145 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
3146 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
3147 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
3151 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
)
3153 unsigned int old_dirty
;
3154 boolean_t reschedule
= FALSE
;
3155 boolean_t already_deferred
= FALSE
;
3156 boolean_t defer_now
= FALSE
;
3159 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
3160 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
3164 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
3166 * Process is on its way out.
3172 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3177 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
3182 old_dirty
= p
->p_memstat_dirty
;
3184 /* These bits are cumulative, as per <rdar://problem/11159924> */
3185 if (pcontrol
& PROC_DIRTY_TRACK
) {
3186 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
3189 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
3190 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
3193 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
3194 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
3197 if (old_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
3198 already_deferred
= TRUE
;
3202 /* This can be set and cleared exactly once. */
3203 if (pcontrol
& (PROC_DIRTY_DEFER
| PROC_DIRTY_DEFER_ALWAYS
)) {
3204 if ((pcontrol
& (PROC_DIRTY_DEFER
)) &&
3205 !(old_dirty
& P_DIRTY_DEFER
)) {
3206 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
3209 if ((pcontrol
& (PROC_DIRTY_DEFER_ALWAYS
)) &&
3210 !(old_dirty
& P_DIRTY_DEFER_ALWAYS
)) {
3211 p
->p_memstat_dirty
|= P_DIRTY_DEFER_ALWAYS
;
3217 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
3218 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
3219 defer_now
? "Y" : "N",
3220 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
3223 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
3224 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
3225 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3226 if (defer_now
&& !already_deferred
) {
3228 * Request to defer a clean process that's idle-exit enabled
3229 * and not already in the jetsam deferred band. Most likely a
3232 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
3234 } else if (!defer_now
) {
3236 * The process isn't asking for the 'aging' facility.
3237 * Could be that it is:
3240 if (already_deferred
) {
3242 * already in the aging bands. Traditionally,
3243 * some processes have tried to use this to
3244 * opt out of the 'aging' facility.
3247 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3250 * agnostic to the 'aging' facility. In that case,
3251 * we'll go ahead and opt it in because this is likely
3252 * a new launch (clean process, dirty tracking enabled)
3255 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
3263 * We are trying to operate on a dirty process. Dirty processes have to
3264 * be removed from the deferred band. The question is do we reset the
3265 * deferred state or not?
3267 * This could be a legal request like:
3268 * - this process had opted into the 'aging' band
3269 * - but it's now dirty and requests to opt out.
3270 * In this case, we remove the process from the band and reset its
3271 * state too. It'll opt back in properly when needed.
3273 * OR, this request could be a user-space bug. E.g.:
3274 * - this process had opted into the 'aging' band when clean
3275 * - and, then issues another request to again put it into the band except
3276 * this time the process is dirty.
3277 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
3278 * the deferred band with its state intact. So our request below is no-op.
3279 * But we do it here anyways for coverage.
3281 * memorystatus_update_idle_priority_locked()
3282 * single-mindedly treats a dirty process as "cannot be in the aging band".
3285 if (!defer_now
&& already_deferred
) {
3286 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3289 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
3291 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
3296 memorystatus_update_idle_priority_locked(p
);
3299 memorystatus_reschedule_idle_demotion_locked();
3311 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
)
3314 boolean_t kill
= false;
3315 boolean_t reschedule
= FALSE
;
3316 boolean_t was_dirty
= FALSE
;
3317 boolean_t now_dirty
= FALSE
;
3319 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
3320 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
3324 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
3326 * Process is on its way out.
3332 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3337 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3341 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
3342 /* Dirty tracking not enabled */
3344 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
3346 * Process is set to be terminated and we're attempting to mark it dirty.
3347 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
3351 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
3352 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
3353 /* Mark the process as having been dirtied at some point */
3354 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
3355 memorystatus_dirty_count
++;
3357 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
3358 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
3359 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
3360 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3362 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
3363 /* Kill previously terminated processes if set clean */
3366 p
->p_memstat_dirty
&= ~flag
;
3367 memorystatus_dirty_count
--;
3379 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3383 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
3384 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
3385 /* Manage idle exit deferral, if applied */
3386 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3388 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
3389 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
3390 * P_DIRTY_DEFER: one-time protection window given at launch
3391 * P_DIRTY_DEFER_ALWAYS: protection window given for every dirty->clean transition. Like non-legacy mode.
3393 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
3394 * in that band on it's way to IDLE.
3397 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3399 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
3401 * The process will move from its aging band to its higher requested
3404 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
3406 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
3410 * Process is back from "dirty" to "clean".
3413 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) {
3414 if (((p
->p_memstat_dirty
& P_DIRTY_DEFER_ALWAYS
) == FALSE
) &&
3415 (mach_absolute_time() >= p
->p_memstat_idledeadline
)) {
3417 * The process' hasn't enrolled in the "always defer after dirty"
3418 * mode and its deadline has expired. It currently
3419 * does not reside in any of the aging buckets.
3421 * It's on its way to the JETSAM_PRIORITY_IDLE
3422 * bucket via memorystatus_update_idle_priority_locked()
3425 * So all we need to do is reset all the state on the
3426 * process that's related to the aging bucket i.e.
3427 * the AGING_IN_PROGRESS flag and the timer deadline.
3430 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3434 * Process enrolled in "always stop in deferral band after dirty" OR
3435 * it still has some protection window left and so
3436 * we just re-arm the timer without modifying any
3437 * state on the process iff it still wants into that band.
3440 if (p
->p_memstat_dirty
& P_DIRTY_DEFER_ALWAYS
) {
3441 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
3443 } else if (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
3444 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
3449 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
3455 memorystatus_update_idle_priority_locked(p
);
3457 if (memorystatus_highwater_enabled
) {
3458 boolean_t ledger_update_needed
= TRUE
;
3459 boolean_t use_active
;
3462 * We are in this path because this process transitioned between
3463 * dirty <--> clean state. Update the cached memory limits.
3466 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
3468 * process is pinned in elevated band
3472 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
3474 ledger_update_needed
= TRUE
;
3477 * process is clean...but if it has opted into pressured-exit
3478 * we don't apply the INACTIVE limit till the process has aged
3479 * out and is entering the IDLE band.
3480 * See memorystatus_update_priority_locked() for that.
3483 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3484 ledger_update_needed
= FALSE
;
3486 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
3488 ledger_update_needed
= TRUE
;
3493 * Enforce the new limits by writing to the ledger.
3495 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
3496 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
3497 * We aren't traversing the jetsam bucket list here, so we should be safe.
3498 * See rdar://21394491.
3501 if (ledger_update_needed
&& proc_ref_locked(p
) == p
) {
3503 if (p
->p_memstat_memlimit
> 0) {
3504 ledger_limit
= p
->p_memstat_memlimit
;
3509 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, use_active
, is_fatal
);
3511 proc_rele_locked(p
);
3513 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
3514 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
3515 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
3516 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
3520 /* If the deferral state changed, reschedule the demotion timer */
3522 memorystatus_reschedule_idle_demotion_locked();
3527 if (proc_ref_locked(p
) == p
) {
3529 psignal(p
, SIGKILL
);
3531 proc_rele_locked(p
);
3542 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
)
3546 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
3548 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
3552 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
3554 * Process is on its way out.
3560 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3565 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
3566 /* Dirty tracking not enabled */
3571 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
| PROC_DIRTY_DEFER_ALWAYS
)) == 0) {
3576 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
3577 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
3580 /* This can be set and cleared exactly once. */
3581 if (pcontrol
& (PROC_DIRTY_DEFER
| PROC_DIRTY_DEFER_ALWAYS
)) {
3582 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
3583 p
->p_memstat_dirty
&= ~(P_DIRTY_DEFER
);
3586 if (p
->p_memstat_dirty
& P_DIRTY_DEFER_ALWAYS
) {
3587 p
->p_memstat_dirty
&= ~(P_DIRTY_DEFER_ALWAYS
);
3590 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3591 memorystatus_update_idle_priority_locked(p
);
3592 memorystatus_reschedule_idle_demotion_locked();
3603 memorystatus_dirty_get(proc_t p
)
3609 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3610 ret
|= PROC_DIRTY_TRACKED
;
3611 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3612 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
3614 if (p
->p_memstat_dirty
& P_DIRTY
) {
3615 ret
|= PROC_DIRTY_IS_DIRTY
;
3617 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
3618 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
3628 memorystatus_on_terminate(proc_t p
)
3634 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3636 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
| P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
3637 /* Clean; mark as terminated and issue SIGKILL */
3640 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3650 memorystatus_on_suspend(proc_t p
)
3654 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
);
3658 memorystatus_suspended_count
++;
3660 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
3665 memorystatus_on_resume(proc_t p
)
3675 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
3678 * Now that we don't _thaw_ a process completely,
3679 * resuming it (and having some on-demand swapins)
3680 * shouldn't preclude it from being counted as frozen.
3682 * memorystatus_frozen_count--;
3684 * We preserve the P_MEMSTAT_FROZEN state since the process
3685 * could have state on disk AND so will deserve some protection
3686 * in the jetsam bands.
3688 if ((p
->p_memstat_state
& P_MEMSTAT_REFREEZE_ELIGIBLE
) == 0) {
3689 p
->p_memstat_state
|= P_MEMSTAT_REFREEZE_ELIGIBLE
;
3690 memorystatus_refreeze_eligible_count
++;
3692 p
->p_memstat_thaw_count
++;
3694 memorystatus_thaw_count
++;
3697 memorystatus_suspended_count
--;
3703 * P_MEMSTAT_FROZEN will remain unchanged. This used to be:
3704 * p->p_memstat_state &= ~(P_MEMSTAT_SUSPENDED | P_MEMSTAT_FROZEN);
3706 p
->p_memstat_state
&= ~P_MEMSTAT_SUSPENDED
;
3712 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
3713 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3719 memorystatus_on_inactivity(proc_t p
)
3723 /* Wake the freeze thread */
3724 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
3729 * The proc_list_lock is held by the caller.
3732 memorystatus_build_state(proc_t p
)
3734 uint32_t snapshot_state
= 0;
3737 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3738 snapshot_state
|= kMemorystatusSuspended
;
3740 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
3741 snapshot_state
|= kMemorystatusFrozen
;
3743 if (p
->p_memstat_state
& P_MEMSTAT_REFREEZE_ELIGIBLE
) {
3744 snapshot_state
|= kMemorystatusWasThawed
;
3748 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3749 snapshot_state
|= kMemorystatusTracked
;
3751 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3752 snapshot_state
|= kMemorystatusSupportsIdleExit
;
3754 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3755 snapshot_state
|= kMemorystatusDirty
;
3758 return snapshot_state
;
3762 kill_idle_exit_proc(void)
3764 proc_t p
, victim_p
= PROC_NULL
;
3765 uint64_t current_time
;
3766 boolean_t killed
= FALSE
;
3768 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3770 /* Pick next idle exit victim. */
3771 current_time
= mach_absolute_time();
3773 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_IDLE_EXIT
);
3774 if (jetsam_reason
== OS_REASON_NULL
) {
3775 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3780 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
3782 /* No need to look beyond the idle band */
3783 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
3787 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
| P_DIRTY_IS_DIRTY
| P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
3788 if (current_time
>= p
->p_memstat_idledeadline
) {
3789 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3790 victim_p
= proc_ref_locked(p
);
3795 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
3801 printf("memorystatus: killing_idle_process pid %d [%s]\n", victim_p
->p_pid
, (*victim_p
->p_name
? victim_p
->p_name
: "unknown"));
3802 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
, jetsam_reason
);
3803 proc_rele(victim_p
);
3805 os_reason_free(jetsam_reason
);
3812 memorystatus_thread_wake(void)
3815 int active_thr
= atomic_load(&active_jetsam_threads
);
3817 /* Wakeup all the jetsam threads */
3818 for (thr_id
= 0; thr_id
< active_thr
; thr_id
++) {
3819 thread_wakeup((event_t
)&jetsam_threads
[thr_id
].memorystatus_wakeup
);
3826 memorystatus_thread_pool_max()
3828 /* Increase the jetsam thread pool to max_jetsam_threads */
3829 int max_threads
= max_jetsam_threads
;
3830 printf("Expanding memorystatus pool to %d!\n", max_threads
);
3831 atomic_store(&active_jetsam_threads
, max_threads
);
3835 memorystatus_thread_pool_default()
3837 /* Restore the jetsam thread pool to a single thread */
3838 printf("Reverting memorystatus pool back to 1\n");
3839 atomic_store(&active_jetsam_threads
, 1);
3842 #endif /* CONFIG_JETSAM */
3844 extern void vm_pressure_response(void);
3847 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
3849 struct jetsam_thread_state
*jetsam_thread
= jetsam_current_thread();
3852 assert_wait_timeout(&jetsam_thread
->memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, NSEC_PER_MSEC
);
3854 assert_wait(&jetsam_thread
->memorystatus_wakeup
, THREAD_UNINT
);
3857 return thread_block(continuation
);
3861 memorystatus_avail_pages_below_pressure(void)
3865 * Instead of CONFIG_EMBEDDED for these *avail_pages* routines, we should
3866 * key off of the system having dynamic swap support. With full swap support,
3867 * the system shouldn't really need to worry about various page thresholds.
3869 return memorystatus_available_pages
<= memorystatus_available_pages_pressure
;
3870 #else /* CONFIG_EMBEDDED */
3872 #endif /* CONFIG_EMBEDDED */
3876 memorystatus_avail_pages_below_critical(void)
3879 return memorystatus_available_pages
<= memorystatus_available_pages_critical
;
3880 #else /* CONFIG_EMBEDDED */
3882 #endif /* CONFIG_EMBEDDED */
3886 memorystatus_post_snapshot(int32_t priority
, uint32_t cause
)
3889 #pragma unused(cause)
3891 * Don't generate logs for steady-state idle-exit kills,
3892 * unless it is overridden for debug or by the device
3896 return (priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
;
3898 #else /* CONFIG_EMBEDDED */
3900 * Don't generate logs for steady-state idle-exit kills,
3902 * - it is overridden for debug or by the device
3905 * - the kill causes are important i.e. not kMemorystatusKilledIdleExit
3908 boolean_t snapshot_eligible_kill_cause
= (is_reason_thrashing(cause
) || is_reason_zone_map_exhaustion(cause
));
3909 return (priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
|| snapshot_eligible_kill_cause
;
3910 #endif /* CONFIG_EMBEDDED */
3914 memorystatus_action_needed(void)
3917 return is_reason_thrashing(kill_under_pressure_cause
) ||
3918 is_reason_zone_map_exhaustion(kill_under_pressure_cause
) ||
3919 memorystatus_available_pages
<= memorystatus_available_pages_pressure
;
3920 #else /* CONFIG_EMBEDDED */
3921 return is_reason_thrashing(kill_under_pressure_cause
) ||
3922 is_reason_zone_map_exhaustion(kill_under_pressure_cause
);
3923 #endif /* CONFIG_EMBEDDED */
3927 extern void vm_swap_consider_defragmenting(int);
3930 * This routine will _jetsam_ all frozen processes
3931 * and reclaim the swap space immediately.
3933 * So freeze has to be DISABLED when we call this routine.
3937 memorystatus_disable_freeze(void)
3939 memstat_bucket_t
*bucket
;
3940 int bucket_count
= 0, retries
= 0;
3941 boolean_t retval
= FALSE
, killed
= FALSE
;
3942 uint32_t errors
= 0, errors_over_prev_iteration
= 0;
3943 os_reason_t jetsam_reason
= 0;
3944 unsigned int band
= 0;
3945 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
3947 assert(memorystatus_freeze_enabled
== FALSE
);
3949 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_DISK_SPACE_SHORTAGE
);
3950 if (jetsam_reason
== OS_REASON_NULL
) {
3951 printf("memorystatus_disable_freeze: failed to allocate jetsam reason\n");
3955 * Let's relocate all frozen processes into band 8. Demoted frozen processes
3956 * are sitting in band 0 currently and it's possible to have a frozen process
3957 * in the FG band being actively used. We don't reset its frozen state when
3958 * it is resumed because it has state on disk.
3960 * We choose to do this relocation rather than implement a new 'kill frozen'
3961 * process function for these reasons:
3962 * - duplication of code: too many kill functions exist and we need to rework them better.
3963 * - disk-space-shortage kills are rare
3964 * - not having the 'real' jetsam band at time of the this frozen kill won't preclude us
3965 * from answering any imp. questions re. jetsam policy/effectiveness.
3967 * This is essentially what memorystatus_update_inactive_jetsam_priority_band() does while
3968 * avoiding the application of memory limits.
3974 band
= JETSAM_PRIORITY_IDLE
;
3978 next_p
= memorystatus_get_first_proc_locked(&band
, TRUE
);
3981 next_p
= memorystatus_get_next_proc_locked(&band
, p
, TRUE
);
3983 if (p
->p_memstat_effectivepriority
> JETSAM_PRIORITY_FOREGROUND
) {
3987 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == FALSE
) {
3991 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
3992 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
3995 if (p
->p_memstat_effectivepriority
== memorystatus_freeze_jetsam_band
) {
4000 * We explicitly add this flag here so the process looks like a normal
4001 * frozen process i.e. P_MEMSTAT_FROZEN and P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND.
4002 * We don't bother with assigning the 'active' memory
4003 * limits at this point because we are going to be killing it soon below.
4005 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
4006 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
4008 memorystatus_update_priority_locked(p
, memorystatus_freeze_jetsam_band
, FALSE
, TRUE
);
4011 bucket
= &memstat_bucket
[memorystatus_freeze_jetsam_band
];
4012 bucket_count
= bucket
->count
;
4016 * Bucket count is already stale at this point. But, we don't expect
4017 * freezing to continue since we have already disabled the freeze functionality.
4018 * However, an existing freeze might be in progress. So we might miss that process
4019 * in the first go-around. We hope to catch it in the next.
4022 errors_over_prev_iteration
= 0;
4023 while (bucket_count
) {
4027 * memorystatus_kill_elevated_process() drops a reference,
4028 * so take another one so we can continue to use this exit reason
4029 * even after it returns.
4032 os_reason_ref(jetsam_reason
);
4033 retval
= memorystatus_kill_elevated_process(
4034 kMemorystatusKilledDiskSpaceShortage
,
4036 memorystatus_freeze_jetsam_band
,
4037 0, /* the iteration of aggressive jetsam..ignored here */
4041 printf("memorystatus_disable_freeze: memorystatus_kill_elevated_process returned %d error(s)\n", errors
);
4042 errors_over_prev_iteration
+= errors
;
4048 * No frozen processes left to kill.
4058 if (memorystatus_frozen_count
) {
4060 * A frozen process snuck in and so
4061 * go back around to kill it. That
4062 * process may have been resumed and
4063 * put into the FG band too. So we
4064 * have to do the relocation again.
4066 assert(memorystatus_freeze_enabled
== FALSE
);
4073 #if DEVELOPMENT || DEBUG
4074 panic("memorystatus_disable_freeze: Failed to kill all frozen processes, memorystatus_frozen_count = %d, errors = %d",
4075 memorystatus_frozen_count
, errors_over_prev_iteration
);
4076 #endif /* DEVELOPMENT || DEBUG */
4080 os_reason_free(jetsam_reason
);
4083 vm_swap_consider_defragmenting(VM_SWAP_FLAGS_FORCE_DEFRAG
| VM_SWAP_FLAGS_FORCE_RECLAIM
);
4086 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
4087 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
4088 uint64_t timestamp_now
= mach_absolute_time();
4089 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
4090 memorystatus_jetsam_snapshot
->js_gencount
++;
4091 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
4092 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
4094 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
4097 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
4107 #endif /* CONFIG_FREEZE */
4110 memorystatus_act_on_hiwat_processes(uint32_t *errors
, uint32_t *hwm_kill
, boolean_t
*post_snapshot
, __unused boolean_t
*is_critical
)
4112 boolean_t purged
= FALSE
;
4113 boolean_t killed
= memorystatus_kill_hiwat_proc(errors
, &purged
);
4116 *hwm_kill
= *hwm_kill
+ 1;
4117 *post_snapshot
= TRUE
;
4120 if (purged
== FALSE
) {
4121 /* couldn't purge and couldn't kill */
4122 memorystatus_hwm_candidates
= FALSE
;
4127 /* No highwater processes to kill. Continue or stop for now? */
4128 if (!is_reason_thrashing(kill_under_pressure_cause
) &&
4129 !is_reason_zone_map_exhaustion(kill_under_pressure_cause
) &&
4130 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
4132 * We are _not_ out of pressure but we are above the critical threshold and there's:
4133 * - no compressor thrashing
4134 * - enough zone memory
4135 * - no more HWM processes left.
4136 * For now, don't kill any other processes.
4139 if (*hwm_kill
== 0) {
4140 memorystatus_thread_wasted_wakeup
++;
4143 *is_critical
= FALSE
;
4147 #endif /* CONFIG_JETSAM */
4153 memorystatus_act_aggressive(uint32_t cause
, os_reason_t jetsam_reason
, int *jld_idle_kills
, boolean_t
*corpse_list_purged
, boolean_t
*post_snapshot
)
4155 if (memorystatus_jld_enabled
== TRUE
) {
4157 uint32_t errors
= 0;
4159 /* Jetsam Loop Detection - locals */
4160 memstat_bucket_t
*bucket
;
4161 int jld_bucket_count
= 0;
4162 struct timeval jld_now_tstamp
= {0, 0};
4163 uint64_t jld_now_msecs
= 0;
4164 int elevated_bucket_count
= 0;
4166 /* Jetsam Loop Detection - statics */
4167 static uint64_t jld_timestamp_msecs
= 0;
4168 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
4169 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
4170 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
4172 * Jetsam Loop Detection: attempt to detect
4173 * rapid daemon relaunches in the lower bands.
4176 microuptime(&jld_now_tstamp
);
4179 * Ignore usecs in this calculation.
4180 * msecs granularity is close enough.
4182 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
4185 switch (jetsam_aging_policy
) {
4186 case kJetsamAgingPolicyLegacy
:
4187 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
4188 jld_bucket_count
= bucket
->count
;
4189 bucket
= &memstat_bucket
[JETSAM_PRIORITY_AGING_BAND1
];
4190 jld_bucket_count
+= bucket
->count
;
4192 case kJetsamAgingPolicySysProcsReclaimedFirst
:
4193 case kJetsamAgingPolicyAppsReclaimedFirst
:
4194 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
4195 jld_bucket_count
= bucket
->count
;
4196 bucket
= &memstat_bucket
[system_procs_aging_band
];
4197 jld_bucket_count
+= bucket
->count
;
4198 bucket
= &memstat_bucket
[applications_aging_band
];
4199 jld_bucket_count
+= bucket
->count
;
4201 case kJetsamAgingPolicyNone
:
4203 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
4204 jld_bucket_count
= bucket
->count
;
4208 bucket
= &memstat_bucket
[JETSAM_PRIORITY_ELEVATED_INACTIVE
];
4209 elevated_bucket_count
= bucket
->count
;
4214 * memorystatus_jld_eval_period_msecs is a tunable
4215 * memorystatus_jld_eval_aggressive_count is a tunable
4216 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
4218 if ((jld_bucket_count
== 0) ||
4219 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
4221 * Refresh evaluation parameters
4223 jld_timestamp_msecs
= jld_now_msecs
;
4224 jld_idle_kill_candidates
= jld_bucket_count
;
4225 *jld_idle_kills
= 0;
4226 jld_eval_aggressive_count
= 0;
4227 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
4230 if (*jld_idle_kills
> jld_idle_kill_candidates
) {
4231 jld_eval_aggressive_count
++;
4233 #if DEVELOPMENT || DEBUG
4234 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
4235 jld_eval_aggressive_count
,
4236 jld_timestamp_msecs
,
4238 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
4239 jld_eval_aggressive_count
,
4240 jld_idle_kill_candidates
,
4242 #endif /* DEVELOPMENT || DEBUG */
4244 if ((jld_eval_aggressive_count
== memorystatus_jld_eval_aggressive_count
) &&
4245 (total_corpses_count() > 0) && (*corpse_list_purged
== FALSE
)) {
4247 * If we reach this aggressive cycle, corpses might be causing memory pressure.
4248 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
4249 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
4251 task_purge_all_corpses();
4252 *corpse_list_purged
= TRUE
;
4253 } else if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
4255 * Bump up the jetsam priority limit (eg: the bucket index)
4256 * Enforce bucket index sanity.
4258 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
4259 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
4261 * Do nothing. Stick with the default level.
4264 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
4268 /* Visit elevated processes first */
4269 while (elevated_bucket_count
) {
4270 elevated_bucket_count
--;
4273 * memorystatus_kill_elevated_process() drops a reference,
4274 * so take another one so we can continue to use this exit reason
4275 * even after it returns.
4278 os_reason_ref(jetsam_reason
);
4279 killed
= memorystatus_kill_elevated_process(
4282 JETSAM_PRIORITY_ELEVATED_INACTIVE
,
4283 jld_eval_aggressive_count
,
4287 *post_snapshot
= TRUE
;
4288 if (memorystatus_avail_pages_below_pressure()) {
4290 * Still under pressure.
4291 * Find another pinned processes.
4299 * No pinned processes left to kill.
4300 * Abandon elevated band.
4307 * memorystatus_kill_top_process_aggressive() allocates its own
4308 * jetsam_reason so the kMemorystatusKilledProcThrashing cause
4309 * is consistent throughout the aggressive march.
4311 killed
= memorystatus_kill_top_process_aggressive(
4312 kMemorystatusKilledProcThrashing
,
4313 jld_eval_aggressive_count
,
4314 jld_priority_band_max
,
4318 /* Always generate logs after aggressive kill */
4319 *post_snapshot
= TRUE
;
4320 *jld_idle_kills
= 0;
4333 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
4335 boolean_t post_snapshot
= FALSE
;
4336 uint32_t errors
= 0;
4337 uint32_t hwm_kill
= 0;
4338 boolean_t sort_flag
= TRUE
;
4339 boolean_t corpse_list_purged
= FALSE
;
4340 int jld_idle_kills
= 0;
4341 struct jetsam_thread_state
*jetsam_thread
= jetsam_current_thread();
4343 if (jetsam_thread
->inited
== FALSE
) {
4345 * It's the first time the thread has run, so just mark the thread as privileged and block.
4346 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
4350 thread_wire(host_priv_self(), current_thread(), TRUE
);
4351 snprintf(name
, 32, "VM_memorystatus_%d", jetsam_thread
->index
+ 1);
4353 if (jetsam_thread
->index
== 0) {
4354 if (vm_pageout_state
.vm_restricted_to_single_processor
== TRUE
) {
4355 thread_vm_bind_group_add();
4358 thread_set_thread_name(current_thread(), name
);
4359 jetsam_thread
->inited
= TRUE
;
4360 memorystatus_thread_block(0, memorystatus_thread
);
4363 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
4364 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
, 0);
4367 * Jetsam aware version.
4369 * The VM pressure notification thread is working it's way through clients in parallel.
4371 * So, while the pressure notification thread is targeting processes in order of
4372 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
4373 * any processes that have exceeded their highwater mark.
4375 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
4376 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
4378 while (memorystatus_action_needed()) {
4382 uint64_t jetsam_reason_code
= JETSAM_REASON_INVALID
;
4383 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4385 cause
= kill_under_pressure_cause
;
4387 case kMemorystatusKilledFCThrashing
:
4388 jetsam_reason_code
= JETSAM_REASON_MEMORY_FCTHRASHING
;
4390 case kMemorystatusKilledVMCompressorThrashing
:
4391 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING
;
4393 case kMemorystatusKilledVMCompressorSpaceShortage
:
4394 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE
;
4396 case kMemorystatusKilledZoneMapExhaustion
:
4397 jetsam_reason_code
= JETSAM_REASON_ZONE_MAP_EXHAUSTION
;
4399 case kMemorystatusKilledVMPageShortage
:
4402 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMPAGESHORTAGE
;
4403 cause
= kMemorystatusKilledVMPageShortage
;
4408 boolean_t is_critical
= TRUE
;
4409 if (memorystatus_act_on_hiwat_processes(&errors
, &hwm_kill
, &post_snapshot
, &is_critical
)) {
4410 if (is_critical
== FALSE
) {
4412 * For now, don't kill any other processes.
4420 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, jetsam_reason_code
);
4421 if (jetsam_reason
== OS_REASON_NULL
) {
4422 printf("memorystatus_thread: failed to allocate jetsam reason\n");
4425 if (memorystatus_act_aggressive(cause
, jetsam_reason
, &jld_idle_kills
, &corpse_list_purged
, &post_snapshot
)) {
4430 * memorystatus_kill_top_process() drops a reference,
4431 * so take another one so we can continue to use this exit reason
4432 * even after it returns
4434 os_reason_ref(jetsam_reason
);
4437 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, jetsam_reason
, &priority
, &errors
);
4441 if (memorystatus_post_snapshot(priority
, cause
) == TRUE
) {
4442 post_snapshot
= TRUE
;
4445 /* Jetsam Loop Detection */
4446 if (memorystatus_jld_enabled
== TRUE
) {
4447 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
4451 * We've reached into bands beyond idle deferred.
4452 * We make no attempt to monitor them
4457 if ((priority
>= JETSAM_PRIORITY_UI_SUPPORT
) && (total_corpses_count() > 0) && (corpse_list_purged
== FALSE
)) {
4459 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
4460 * then we attempt to relieve pressure by purging corpse memory.
4462 task_purge_all_corpses();
4463 corpse_list_purged
= TRUE
;
4468 if (memorystatus_avail_pages_below_critical()) {
4470 * Still under pressure and unable to kill a process - purge corpse memory
4472 if (total_corpses_count() > 0) {
4473 task_purge_all_corpses();
4474 corpse_list_purged
= TRUE
;
4477 if (memorystatus_avail_pages_below_critical()) {
4479 * Still under pressure and unable to kill a process - panic
4481 panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)memorystatus_available_pages
);
4488 * We do not want to over-kill when thrashing has been detected.
4489 * To avoid that, we reset the flag here and notify the
4492 if (is_reason_thrashing(kill_under_pressure_cause
)) {
4493 kill_under_pressure_cause
= 0;
4495 vm_thrashing_jetsam_done();
4496 #endif /* CONFIG_JETSAM */
4497 } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause
)) {
4498 kill_under_pressure_cause
= 0;
4501 os_reason_free(jetsam_reason
);
4504 kill_under_pressure_cause
= 0;
4507 memorystatus_clear_errors();
4510 if (post_snapshot
) {
4512 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
4513 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
4514 uint64_t timestamp_now
= mach_absolute_time();
4515 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
4516 memorystatus_jetsam_snapshot
->js_gencount
++;
4517 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
4518 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
4520 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
4523 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
4531 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
4532 memorystatus_available_pages
, 0, 0, 0, 0);
4534 memorystatus_thread_block(0, memorystatus_thread
);
4539 * when an idle-exitable proc was killed
4541 * when there are no more idle-exitable procs found
4542 * when the attempt to kill an idle-exitable proc failed
4545 memorystatus_idle_exit_from_VM(void)
4548 * This routine should no longer be needed since we are
4549 * now using jetsam bands on all platforms and so will deal
4550 * with IDLE processes within the memorystatus thread itself.
4552 * But we still use it because we observed that macos systems
4553 * started heavy compression/swapping with a bunch of
4554 * idle-exitable processes alive and doing nothing. We decided
4555 * to rather kill those processes than start swapping earlier.
4558 return kill_idle_exit_proc();
4562 * Callback invoked when allowable physical memory footprint exceeded
4563 * (dirty pages + IOKit mappings)
4565 * This is invoked for both advisory, non-fatal per-task high watermarks,
4566 * as well as the fatal task memory limits.
4569 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
4571 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4573 proc_t p
= current_proc();
4575 #if VM_PRESSURE_EVENTS
4576 if (warning
== TRUE
) {
4578 * This is a warning path which implies that the current process is close, but has
4579 * not yet exceeded its per-process memory limit.
4581 if (memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, FALSE
/* not exceeded */) != TRUE
) {
4582 /* Print warning, since it's possible that task has not registered for pressure notifications */
4583 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
);
4587 #endif /* VM_PRESSURE_EVENTS */
4589 if (memlimit_is_fatal
) {
4591 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
4592 * has violated either the system-wide per-task memory limit OR its own task limit.
4594 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_PERPROCESSLIMIT
);
4595 if (jetsam_reason
== NULL
) {
4596 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
4597 } else if (corpse_for_fatal_memkill
!= 0 && proc_send_synchronous_EXC_RESOURCE(p
) == FALSE
) {
4598 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
4599 jetsam_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
4602 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
, jetsam_reason
) != TRUE
) {
4603 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
4607 * HWM offender exists. Done without locks or synchronization.
4608 * See comment near its declaration for more details.
4610 memorystatus_hwm_candidates
= TRUE
;
4612 #if VM_PRESSURE_EVENTS
4614 * The current process is not in the warning path.
4615 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
4616 * Failure to send note is ignored here.
4618 (void)memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, TRUE
/* exceeded */);
4620 #endif /* VM_PRESSURE_EVENTS */
4625 memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
4627 proc_t p
= current_proc();
4630 * The limit violation is logged here, but only once per process per limit.
4631 * Soft memory limit is a non-fatal high-water-mark
4632 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
4635 os_log_with_startup_serial(OS_LOG_DEFAULT
, "EXC_RESOURCE -> %s[%d] exceeded mem limit: %s%s %d MB (%s)\n",
4636 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, (memlimit_is_active
? "Active" : "Inactive"),
4637 (memlimit_is_fatal
? "Hard" : "Soft"), max_footprint_mb
,
4638 (memlimit_is_fatal
? "fatal" : "non-fatal"));
4646 * Evaluates process state to determine which limit
4647 * should be applied (active vs. inactive limit).
4649 * Processes that have the 'elevated inactive jetsam band' attribute
4650 * are first evaluated based on their current priority band.
4651 * presently elevated ==> active
4653 * Processes that opt into dirty tracking are evaluated
4654 * based on clean vs dirty state.
4656 * clean ==> inactive
4658 * Process that do not opt into dirty tracking are
4659 * evalulated based on priority level.
4660 * Foreground or above ==> active
4661 * Below Foreground ==> inactive
4663 * Return: TRUE if active
4668 proc_jetsam_state_is_active_locked(proc_t p
)
4670 if ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) &&
4671 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
)) {
4673 * process has the 'elevated inactive jetsam band' attribute
4674 * and process is present in the elevated band
4675 * implies active state
4678 } else if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
4680 * process has opted into dirty tracking
4681 * active state is based on dirty vs. clean
4683 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
4686 * implies active state
4692 * implies inactive state
4696 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
4698 * process is Foreground or higher
4699 * implies active state
4704 * process found below Foreground
4705 * implies inactive state
4712 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
)
4716 uint32_t errors
= 0;
4718 if (victim_pid
== -1) {
4719 /* No pid, so kill first process */
4720 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, jetsam_reason
, NULL
, &errors
);
4722 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
4726 memorystatus_clear_errors();
4730 /* Fire off snapshot notification */
4732 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
4733 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
4734 uint64_t timestamp_now
= mach_absolute_time();
4735 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
4736 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
4737 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
4739 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
4742 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
4754 * Jetsam a specific process.
4757 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
)
4761 uint64_t killtime
= 0;
4763 clock_usec_t tv_usec
;
4766 /* TODO - add a victim queue and push this into the main jetsam thread */
4768 p
= proc_find(victim_pid
);
4770 os_reason_free(jetsam_reason
);
4776 if (memorystatus_jetsam_snapshot_count
== 0) {
4777 memorystatus_init_jetsam_snapshot_locked(NULL
, 0);
4780 killtime
= mach_absolute_time();
4781 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4782 tv_msec
= tv_usec
/ 1000;
4784 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4788 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: killing_specific_process pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
4789 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "unknown"),
4790 memorystatus_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, (uint64_t)memorystatus_available_pages
);
4792 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4800 * Toggle the P_MEMSTAT_TERMINATED state.
4801 * Takes the proc_list_lock.
4804 proc_memstat_terminated(proc_t p
, boolean_t set
)
4806 #if DEVELOPMENT || DEBUG
4810 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4812 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4817 #pragma unused(p, set)
4821 #endif /* DEVELOPMENT || DEBUG */
4828 * This is invoked when cpulimits have been exceeded while in fatal mode.
4829 * The jetsam_flags do not apply as those are for memory related kills.
4830 * We call this routine so that the offending process is killed with
4831 * a non-zero exit status.
4834 jetsam_on_ledger_cpulimit_exceeded(void)
4837 int jetsam_flags
= 0; /* make it obvious */
4838 proc_t p
= current_proc();
4839 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4841 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
4842 p
->p_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"));
4844 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_CPULIMIT
);
4845 if (jetsam_reason
== OS_REASON_NULL
) {
4846 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
4849 retval
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
4852 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
4856 #endif /* CONFIG_JETSAM */
4859 memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
)
4864 *count
= get_task_memory_region_count(task
);
4868 #define MEMORYSTATUS_VM_MAP_FORK_ALLOWED 0x100000000
4869 #define MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED 0x200000000
4871 #if DEVELOPMENT || DEBUG
4874 * Sysctl only used to test memorystatus_allowed_vm_map_fork() path.
4875 * set a new pidwatch value
4877 * get the current pidwatch value
4879 * The pidwatch_val starts out with a PID to watch for in the map_fork path.
4881 * - OR'd with MEMORYSTATUS_VM_MAP_FORK_ALLOWED if we allow the map_fork.
4882 * - OR'd with MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED if we disallow the map_fork.
4883 * - set to -1ull if the map_fork() is aborted for other reasons.
4886 uint64_t memorystatus_vm_map_fork_pidwatch_val
= 0;
4888 static int sysctl_memorystatus_vm_map_fork_pidwatch SYSCTL_HANDLER_ARGS
{
4889 #pragma unused(oidp, arg1, arg2)
4891 uint64_t new_value
= 0;
4892 uint64_t old_value
= 0;
4896 * The pid is held in the low 32 bits.
4897 * The 'allowed' flags are in the upper 32 bits.
4899 old_value
= memorystatus_vm_map_fork_pidwatch_val
;
4901 error
= sysctl_io_number(req
, old_value
, sizeof(old_value
), &new_value
, NULL
);
4903 if (error
|| !req
->newptr
) {
4905 * No new value passed in.
4911 * A new pid was passed in via req->newptr.
4912 * Ignore any attempt to set the higher order bits.
4914 memorystatus_vm_map_fork_pidwatch_val
= new_value
& 0xFFFFFFFF;
4915 printf("memorystatus: pidwatch old_value = 0x%llx, new_value = 0x%llx \n", old_value
, new_value
);
4920 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_map_fork_pidwatch
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
4921 0, 0, sysctl_memorystatus_vm_map_fork_pidwatch
, "Q", "get/set pid watched for in vm_map_fork");
4925 * Record if a watched process fails to qualify for a vm_map_fork().
4928 memorystatus_abort_vm_map_fork(task_t task
)
4930 if (memorystatus_vm_map_fork_pidwatch_val
!= 0) {
4931 proc_t p
= get_bsdtask_info(task
);
4932 if (p
!= NULL
&& memorystatus_vm_map_fork_pidwatch_val
== (uint64_t)p
->p_pid
) {
4933 memorystatus_vm_map_fork_pidwatch_val
= -1ull;
4939 set_vm_map_fork_pidwatch(task_t task
, uint64_t x
)
4941 if (memorystatus_vm_map_fork_pidwatch_val
!= 0) {
4942 proc_t p
= get_bsdtask_info(task
);
4943 if (p
&& (memorystatus_vm_map_fork_pidwatch_val
== (uint64_t)p
->p_pid
)) {
4944 memorystatus_vm_map_fork_pidwatch_val
|= x
;
4949 #else /* DEVELOPMENT || DEBUG */
4953 set_vm_map_fork_pidwatch(task_t task
, uint64_t x
)
4955 #pragma unused(task)
4959 #endif /* DEVELOPMENT || DEBUG */
4962 * Called during EXC_RESOURCE handling when a process exceeds a soft
4963 * memory limit. This is the corpse fork path and here we decide if
4964 * vm_map_fork will be allowed when creating the corpse.
4965 * The task being considered is suspended.
4967 * By default, a vm_map_fork is allowed to proceed.
4969 * A few simple policy assumptions:
4970 * Desktop platform is not considered in this path.
4971 * The vm_map_fork is always allowed.
4973 * If the device has a zero system-wide task limit,
4974 * then the vm_map_fork is allowed.
4976 * And if a process's memory footprint calculates less
4977 * than or equal to half of the system-wide task limit,
4978 * then the vm_map_fork is allowed. This calculation
4979 * is based on the assumption that a process can
4980 * munch memory up to the system-wide task limit.
4983 memorystatus_allowed_vm_map_fork(task_t task
)
4985 boolean_t is_allowed
= TRUE
; /* default */
4989 uint64_t footprint_in_bytes
;
4990 uint64_t max_allowed_bytes
;
4992 if (max_task_footprint_mb
== 0) {
4993 set_vm_map_fork_pidwatch(task
, MEMORYSTATUS_VM_MAP_FORK_ALLOWED
);
4997 footprint_in_bytes
= get_task_phys_footprint(task
);
5000 * Maximum is 1/4 of the system-wide task limit.
5002 max_allowed_bytes
= ((uint64_t)max_task_footprint_mb
* 1024 * 1024) >> 2;
5004 if (footprint_in_bytes
> max_allowed_bytes
) {
5005 printf("memorystatus disallowed vm_map_fork %lld %lld\n", footprint_in_bytes
, max_allowed_bytes
);
5006 set_vm_map_fork_pidwatch(task
, MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED
);
5009 #endif /* CONFIG_EMBEDDED */
5011 set_vm_map_fork_pidwatch(task
, MEMORYSTATUS_VM_MAP_FORK_ALLOWED
);
5016 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
5023 pages
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
5024 assert(((uint32_t)pages
) == pages
);
5025 *footprint
= (uint32_t)pages
;
5027 if (max_footprint_lifetime
) {
5028 pages
= (get_task_phys_footprint_lifetime_max(task
) / PAGE_SIZE_64
);
5029 assert(((uint32_t)pages
) == pages
);
5030 *max_footprint_lifetime
= (uint32_t)pages
;
5032 if (purgeable_pages
) {
5033 pages
= (get_task_purgeable_size(task
) / PAGE_SIZE_64
);
5034 assert(((uint32_t)pages
) == pages
);
5035 *purgeable_pages
= (uint32_t)pages
;
5040 memorystatus_get_task_phys_footprint_page_counts(task_t task
,
5041 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
5042 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
5043 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
5044 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
)
5048 if (internal_pages
) {
5049 *internal_pages
= (get_task_internal(task
) / PAGE_SIZE_64
);
5052 if (internal_compressed_pages
) {
5053 *internal_compressed_pages
= (get_task_internal_compressed(task
) / PAGE_SIZE_64
);
5056 if (purgeable_nonvolatile_pages
) {
5057 *purgeable_nonvolatile_pages
= (get_task_purgeable_nonvolatile(task
) / PAGE_SIZE_64
);
5060 if (purgeable_nonvolatile_compressed_pages
) {
5061 *purgeable_nonvolatile_compressed_pages
= (get_task_purgeable_nonvolatile_compressed(task
) / PAGE_SIZE_64
);
5064 if (alternate_accounting_pages
) {
5065 *alternate_accounting_pages
= (get_task_alternate_accounting(task
) / PAGE_SIZE_64
);
5068 if (alternate_accounting_compressed_pages
) {
5069 *alternate_accounting_compressed_pages
= (get_task_alternate_accounting_compressed(task
) / PAGE_SIZE_64
);
5072 if (iokit_mapped_pages
) {
5073 *iokit_mapped_pages
= (get_task_iokit_mapped(task
) / PAGE_SIZE_64
);
5076 if (page_table_pages
) {
5077 *page_table_pages
= (get_task_page_table(task
) / PAGE_SIZE_64
);
5082 * This routine only acts on the global jetsam event snapshot.
5083 * Updating the process's entry can race when the memorystatus_thread
5084 * has chosen to kill a process that is racing to exit on another core.
5087 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
)
5089 memorystatus_jetsam_snapshot_entry_t
*entry
= NULL
;
5090 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
5091 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
5095 LCK_MTX_ASSERT(proc_list_mlock
, LCK_MTX_ASSERT_OWNED
);
5097 if (memorystatus_jetsam_snapshot_count
== 0) {
5099 * No active snapshot.
5106 * Sanity check as this routine should only be called
5107 * from a jetsam kill path.
5109 assert(kill_cause
!= 0 && killtime
!= 0);
5111 snapshot
= memorystatus_jetsam_snapshot
;
5112 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
5114 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
5115 if (snapshot_list
[i
].pid
== p
->p_pid
) {
5116 entry
= &snapshot_list
[i
];
5118 if (entry
->killed
|| entry
->jse_killtime
) {
5120 * We apparently raced on the exit path
5121 * for this process, as it's snapshot entry
5122 * has already recorded a kill.
5124 assert(entry
->killed
&& entry
->jse_killtime
);
5129 * Update the entry we just found in the snapshot.
5132 entry
->killed
= kill_cause
;
5133 entry
->jse_killtime
= killtime
;
5134 entry
->jse_gencount
= snapshot
->js_gencount
;
5135 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
;
5137 entry
->jse_thaw_count
= p
->p_memstat_thaw_count
;
5138 #else /* CONFIG_FREEZE */
5139 entry
->jse_thaw_count
= 0;
5140 #endif /* CONFIG_FREEZE */
5143 * If a process has moved between bands since snapshot was
5144 * initialized, then likely these fields changed too.
5146 if (entry
->priority
!= p
->p_memstat_effectivepriority
) {
5147 strlcpy(entry
->name
, p
->p_name
, sizeof(entry
->name
));
5148 entry
->priority
= p
->p_memstat_effectivepriority
;
5149 entry
->state
= memorystatus_build_state(p
);
5150 entry
->user_data
= p
->p_memstat_userdata
;
5151 entry
->fds
= p
->p_fd
->fd_nfiles
;
5155 * Always update the page counts on a kill.
5159 uint32_t max_pages_lifetime
= 0;
5160 uint32_t purgeable_pages
= 0;
5162 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages_lifetime
, &purgeable_pages
);
5163 entry
->pages
= (uint64_t)pages
;
5164 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
5165 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
5167 uint64_t internal_pages
= 0;
5168 uint64_t internal_compressed_pages
= 0;
5169 uint64_t purgeable_nonvolatile_pages
= 0;
5170 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
5171 uint64_t alternate_accounting_pages
= 0;
5172 uint64_t alternate_accounting_compressed_pages
= 0;
5173 uint64_t iokit_mapped_pages
= 0;
5174 uint64_t page_table_pages
= 0;
5176 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
5177 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
5178 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
5179 &iokit_mapped_pages
, &page_table_pages
);
5181 entry
->jse_internal_pages
= internal_pages
;
5182 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
5183 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
5184 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
5185 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
5186 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
5187 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
5188 entry
->jse_page_table_pages
= page_table_pages
;
5190 uint64_t region_count
= 0;
5191 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
5192 entry
->jse_memory_region_count
= region_count
;
5198 if (entry
== NULL
) {
5200 * The entry was not found in the snapshot, so the process must have
5201 * launched after the snapshot was initialized.
5202 * Let's try to append the new entry.
5204 if (memorystatus_jetsam_snapshot_count
< memorystatus_jetsam_snapshot_max
) {
5206 * A populated snapshot buffer exists
5207 * and there is room to init a new entry.
5209 assert(memorystatus_jetsam_snapshot_count
== snapshot
->entry_count
);
5211 unsigned int next
= memorystatus_jetsam_snapshot_count
;
5213 if (memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[next
], (snapshot
->js_gencount
)) == TRUE
) {
5214 entry
= &snapshot_list
[next
];
5215 entry
->killed
= kill_cause
;
5216 entry
->jse_killtime
= killtime
;
5218 snapshot
->entry_count
= ++next
;
5219 memorystatus_jetsam_snapshot_count
= next
;
5221 if (memorystatus_jetsam_snapshot_count
>= memorystatus_jetsam_snapshot_max
) {
5223 * We just used the last slot in the snapshot buffer.
5224 * We only want to log it once... so we do it here
5225 * when we notice we've hit the max.
5227 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
5228 memorystatus_jetsam_snapshot_count
);
5235 if (entry
== NULL
) {
5237 * If we reach here, the snapshot buffer could not be updated.
5238 * Most likely, the buffer is full, in which case we would have
5239 * logged a warning in the previous call.
5241 * For now, we will stop appending snapshot entries.
5242 * When the buffer is consumed, the snapshot state will reset.
5245 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
5246 p
->p_pid
, p
->p_memstat_effectivepriority
, memorystatus_jetsam_snapshot_count
);
5254 memorystatus_pages_update(unsigned int pages_avail
)
5256 memorystatus_available_pages
= pages_avail
;
5258 #if VM_PRESSURE_EVENTS
5260 * Since memorystatus_available_pages changes, we should
5261 * re-evaluate the pressure levels on the system and
5262 * check if we need to wake the pressure thread.
5263 * We also update memorystatus_level in that routine.
5265 vm_pressure_response();
5267 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
5268 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
5269 memorystatus_thread_wake();
5274 * We can't grab the freezer_mutex here even though that synchronization would be correct to inspect
5275 * the # of frozen processes and wakeup the freezer thread. Reason being that we come here into this
5276 * code with (possibly) the page-queue locks held and preemption disabled. So trying to grab a mutex here
5277 * will result in the "mutex with preemption disabled" panic.
5280 if (memorystatus_freeze_thread_should_run() == TRUE
) {
5282 * The freezer thread is usually woken up by some user-space call i.e. pid_hibernate(any process).
5283 * That trigger isn't invoked often enough and so we are enabling this explicit wakeup here.
5285 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5286 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
5289 #endif /* CONFIG_FREEZE */
5291 #else /* VM_PRESSURE_EVENTS */
5293 boolean_t critical
, delta
;
5295 if (!memorystatus_delta
) {
5299 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
5300 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
5301 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
5303 if (critical
|| delta
) {
5304 unsigned int total_pages
;
5306 total_pages
= (unsigned int) atop_64(max_mem
);
5307 #if CONFIG_SECLUDED_MEMORY
5308 total_pages
-= vm_page_secluded_count
;
5309 #endif /* CONFIG_SECLUDED_MEMORY */
5310 memorystatus_level
= memorystatus_available_pages
* 100 / total_pages
;
5311 memorystatus_thread_wake();
5313 #endif /* VM_PRESSURE_EVENTS */
5315 #endif /* CONFIG_JETSAM */
5318 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
)
5321 clock_usec_t tv_usec
;
5323 uint32_t max_pages_lifetime
= 0;
5324 uint32_t purgeable_pages
= 0;
5325 uint64_t internal_pages
= 0;
5326 uint64_t internal_compressed_pages
= 0;
5327 uint64_t purgeable_nonvolatile_pages
= 0;
5328 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
5329 uint64_t alternate_accounting_pages
= 0;
5330 uint64_t alternate_accounting_compressed_pages
= 0;
5331 uint64_t iokit_mapped_pages
= 0;
5332 uint64_t page_table_pages
= 0;
5333 uint64_t region_count
= 0;
5334 uint64_t cids
[COALITION_NUM_TYPES
];
5336 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
5338 entry
->pid
= p
->p_pid
;
5339 strlcpy(&entry
->name
[0], p
->p_name
, sizeof(entry
->name
));
5340 entry
->priority
= p
->p_memstat_effectivepriority
;
5342 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages_lifetime
, &purgeable_pages
);
5343 entry
->pages
= (uint64_t)pages
;
5344 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
5345 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
5347 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
5348 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
5349 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
5350 &iokit_mapped_pages
, &page_table_pages
);
5352 entry
->jse_internal_pages
= internal_pages
;
5353 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
5354 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
5355 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
5356 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
5357 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
5358 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
5359 entry
->jse_page_table_pages
= page_table_pages
;
5361 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
5362 entry
->jse_memory_region_count
= region_count
;
5364 entry
->state
= memorystatus_build_state(p
);
5365 entry
->user_data
= p
->p_memstat_userdata
;
5366 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
5367 entry
->fds
= p
->p_fd
->fd_nfiles
;
5369 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
5370 entry
->cpu_time
.tv_sec
= (int64_t)tv_sec
;
5371 entry
->cpu_time
.tv_usec
= (int64_t)tv_usec
;
5373 assert(p
->p_stats
!= NULL
);
5374 entry
->jse_starttime
= p
->p_stats
->ps_start
; /* abstime process started */
5375 entry
->jse_killtime
= 0; /* abstime jetsam chose to kill process */
5376 entry
->killed
= 0; /* the jetsam kill cause */
5377 entry
->jse_gencount
= gencount
; /* indicates a pass through jetsam thread, when process was targeted to be killed */
5379 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
; /* Most recent timespan spent in idle-band */
5382 entry
->jse_thaw_count
= p
->p_memstat_thaw_count
;
5383 #else /* CONFIG_FREEZE */
5384 entry
->jse_thaw_count
= 0;
5385 #endif /* CONFIG_FREEZE */
5387 proc_coalitionids(p
, cids
);
5388 entry
->jse_coalition_jetsam_id
= cids
[COALITION_TYPE_JETSAM
];
5394 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
5396 kern_return_t kr
= KERN_SUCCESS
;
5397 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
5398 vm_statistics64_data_t vm_stat
;
5400 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
)) != KERN_SUCCESS
) {
5401 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
5402 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
5404 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
5405 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
5406 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
5407 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
5408 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
5409 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
5411 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
5412 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
5413 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
5414 snapshot
->stats
.compressions
= vm_stat
.compressions
;
5415 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
5416 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
5417 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
5420 get_zone_map_size(&snapshot
->stats
.zone_map_size
, &snapshot
->stats
.zone_map_capacity
);
5421 get_largest_zone_info(snapshot
->stats
.largest_zone_name
, sizeof(snapshot
->stats
.largest_zone_name
),
5422 &snapshot
->stats
.largest_zone_size
);
5426 * Collect vm statistics at boot.
5427 * Called only once (see kern_exec.c)
5428 * Data can be consumed at any time.
5431 memorystatus_init_at_boot_snapshot()
5433 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
5434 memorystatus_at_boot_snapshot
.entry_count
= 0;
5435 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
5436 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
5440 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
5443 unsigned int b
= 0, i
= 0;
5445 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
5446 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
5447 unsigned int snapshot_max
= 0;
5449 LCK_MTX_ASSERT(proc_list_mlock
, LCK_MTX_ASSERT_OWNED
);
5453 * This is an on_demand snapshot
5455 snapshot
= od_snapshot
;
5456 snapshot_list
= od_snapshot
->entries
;
5457 snapshot_max
= ods_list_count
;
5460 * This is a jetsam event snapshot
5462 snapshot
= memorystatus_jetsam_snapshot
;
5463 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
5464 snapshot_max
= memorystatus_jetsam_snapshot_max
;
5468 * Init the snapshot header information
5470 memorystatus_init_snapshot_vmstats(snapshot
);
5471 snapshot
->snapshot_time
= mach_absolute_time();
5472 snapshot
->notification_time
= 0;
5473 snapshot
->js_gencount
= 0;
5475 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
5478 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
5480 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
], snapshot
->js_gencount
)) {
5484 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",
5486 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],
5487 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]);
5489 if (++i
== snapshot_max
) {
5494 snapshot
->entry_count
= i
;
5497 /* update the system buffer count */
5498 memorystatus_jetsam_snapshot_count
= i
;
5502 #if DEVELOPMENT || DEBUG
5506 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
)
5509 memorystatus_jetsam_panic_options_t debug
;
5511 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
5515 ret
= copyin(buffer
, &debug
, buffer_size
);
5520 /* Panic bits match kMemorystatusKilled* enum */
5521 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
5523 /* Copyout new value */
5524 debug
.data
= memorystatus_jetsam_panic_debug
;
5525 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
5529 #endif /* CONFIG_JETSAM */
5532 * Triggers a sort_order on a specified jetsam priority band.
5533 * This is for testing only, used to force a path through the sort
5537 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
)
5541 unsigned int bucket_index
= 0;
5543 if (priority
== -1) {
5544 /* Use as shorthand for default priority */
5545 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
5547 bucket_index
= (unsigned int)priority
;
5550 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
5555 #endif /* DEVELOPMENT || DEBUG */
5558 * Prepare the process to be killed (set state, update snapshot) and kill it.
5560 static uint64_t memorystatus_purge_before_jetsam_success
= 0;
5563 memorystatus_kill_proc(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
, boolean_t
*killed
)
5566 uint32_t aPid_ep
= 0;
5568 uint64_t killtime
= 0;
5570 clock_usec_t tv_usec
;
5572 boolean_t retval
= FALSE
;
5573 uint64_t num_pages_purged
= 0;
5576 aPid_ep
= p
->p_memstat_effectivepriority
;
5578 if (cause
!= kMemorystatusKilledVnodes
&& cause
!= kMemorystatusKilledZoneMapExhaustion
) {
5580 * Genuine memory pressure and not other (vnode/zone) resource exhaustion.
5582 boolean_t success
= FALSE
;
5584 networking_memstatus_callout(p
, cause
);
5585 num_pages_purged
= vm_purgeable_purge_task_owned(p
->task
);
5587 if (num_pages_purged
) {
5589 * We actually purged something and so let's
5590 * check if we need to continue with the kill.
5592 if (cause
== kMemorystatusKilledHiwat
) {
5593 uint64_t footprint_in_bytes
= get_task_phys_footprint(p
->task
);
5594 uint64_t memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
5595 success
= (footprint_in_bytes
<= memlimit_in_bytes
);
5597 success
= (memorystatus_avail_pages_below_pressure() == FALSE
);
5601 memorystatus_purge_before_jetsam_success
++;
5603 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: purged %llu pages from pid %d [%s] and avoided %s\n",
5604 num_pages_purged
, aPid
, (*p
->p_name
? p
->p_name
: "unknown"), memorystatus_kill_cause_name
[cause
]);
5613 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5614 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5615 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing",
5616 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5617 (footprint_in_bytes
/ (1024ULL * 1024ULL)), /* converted bytes to MB */
5618 p
->p_memstat_memlimit
);
5619 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5621 killtime
= mach_absolute_time();
5622 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5623 tv_msec
= tv_usec
/ 1000;
5625 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5626 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5627 if (cause
== kMemorystatusKilledHiwat
) {
5628 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] for diagnosis - memorystatus_available_pages: %d\n",
5629 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_available_pages
);
5631 int activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
5632 if (activeProcess
) {
5633 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memorystatus_available_pages: %d\n",
5634 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_available_pages
);
5636 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
5637 jetsam_diagnostic_suspended_one_active_proc
= 1;
5638 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
5644 /* This diagnostic code is going away soon. Ignore the kMemorystatusInvalid cause here. */
5645 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusInvalid
, killtime
);
5648 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
5651 task_suspend(p
->task
);
5655 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5658 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5661 char kill_reason_string
[128];
5663 if (cause
== kMemorystatusKilledHiwat
) {
5664 strlcpy(kill_reason_string
, "killing_highwater_process", 128);
5666 if (aPid_ep
== JETSAM_PRIORITY_IDLE
) {
5667 strlcpy(kill_reason_string
, "killing_idle_process", 128);
5669 strlcpy(kill_reason_string
, "killing_top_process", 128);
5673 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: %s pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
5674 (unsigned long)tv_sec
, tv_msec
, kill_reason_string
,
5675 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5676 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
5679 * memorystatus_do_kill drops a reference, so take another one so we can
5680 * continue to use this exit reason even after memorystatus_do_kill()
5683 os_reason_ref(jetsam_reason
);
5685 retval
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5694 * Jetsam the first process in the queue.
5697 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
,
5698 int32_t *priority
, uint32_t *errors
)
5701 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5702 boolean_t new_snapshot
= FALSE
, force_new_snapshot
= FALSE
, killed
= FALSE
, freed_mem
= FALSE
;
5705 int32_t local_max_kill_prio
= JETSAM_PRIORITY_IDLE
;
5707 #ifndef CONFIG_FREEZE
5711 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5712 memorystatus_available_pages
, 0, 0, 0, 0);
5716 if (sort_flag
== TRUE
) {
5717 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
5720 local_max_kill_prio
= max_kill_priority
;
5722 force_new_snapshot
= FALSE
;
5724 #else /* CONFIG_JETSAM */
5726 if (sort_flag
== TRUE
) {
5727 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_IDLE
, JETSAM_SORT_DEFAULT
);
5731 * On macos, we currently only have 2 reasons to be here:
5733 * kMemorystatusKilledZoneMapExhaustion
5735 * kMemorystatusKilledVMCompressorSpaceShortage
5737 * If we are here because of kMemorystatusKilledZoneMapExhaustion, we will consider
5738 * any and all processes as eligible kill candidates since we need to avoid a panic.
5740 * Since this function can be called async. it is harder to toggle the max_kill_priority
5741 * value before and after a call. And so we use this local variable to set the upper band
5742 * on the eligible kill bands.
5744 if (cause
== kMemorystatusKilledZoneMapExhaustion
) {
5745 local_max_kill_prio
= JETSAM_PRIORITY_MAX
;
5747 local_max_kill_prio
= max_kill_priority
;
5751 * And, because we are here under extreme circumstances, we force a snapshot even for
5754 force_new_snapshot
= TRUE
;
5756 #endif /* CONFIG_JETSAM */
5760 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5761 while (next_p
&& (next_p
->p_memstat_effectivepriority
<= local_max_kill_prio
)) {
5762 #if DEVELOPMENT || DEBUG
5763 int procSuspendedForDiagnosis
;
5764 #endif /* DEVELOPMENT || DEBUG */
5767 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5769 #if DEVELOPMENT || DEBUG
5770 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
5771 #endif /* DEVELOPMENT || DEBUG */
5774 aPid_ep
= p
->p_memstat_effectivepriority
;
5776 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5777 continue; /* with lock held */
5780 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5781 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
5782 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
5785 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5787 if (cause
== kMemorystatusKilledVnodes
) {
5789 * If the system runs out of vnodes, we systematically jetsam
5790 * processes in hopes of stumbling onto a vnode gain that helps
5791 * the system recover. The process that happens to trigger
5792 * this path has no known relationship to the vnode shortage.
5793 * Deadlock avoidance: attempt to safeguard the caller.
5796 if (p
== current_proc()) {
5797 /* do not jetsam the current process */
5804 boolean_t reclaim_proc
= !(p
->p_memstat_state
& P_MEMSTAT_LOCKED
);
5805 if (any
|| reclaim_proc
) {
5816 if (proc_ref_locked(p
) == p
) {
5818 * Mark as terminated so that if exit1() indicates success, but the process (for example)
5819 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
5820 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
5821 * acquisition of the proc lock.
5823 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5826 * We need to restart the search again because
5827 * proc_ref_locked _can_ drop the proc_list lock
5828 * and we could have lost our stored next_p via
5829 * an exit() on another core.
5832 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5837 * Capture a snapshot if none exists and:
5838 * - we are forcing a new snapshot creation, either because:
5839 * - on a particular platform we need these snapshots every time, OR
5840 * - a boot-arg/embedded device tree property has been set.
5841 * - priority was not requested (this is something other than an ambient kill)
5842 * - the priority was requested *and* the targeted process is not at idle priority
5844 if ((memorystatus_jetsam_snapshot_count
== 0) &&
5845 (force_new_snapshot
|| memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (aPid_ep
!= JETSAM_PRIORITY_IDLE
))))) {
5846 memorystatus_init_jetsam_snapshot_locked(NULL
, 0);
5847 new_snapshot
= TRUE
;
5852 freed_mem
= memorystatus_kill_proc(p
, cause
, jetsam_reason
, &killed
); /* purged and/or killed 'p' */
5857 *priority
= aPid_ep
;
5862 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5870 * Failure - first unwind the state,
5871 * then fall through to restart the search.
5874 proc_rele_locked(p
);
5875 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5876 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5880 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5887 os_reason_free(jetsam_reason
);
5889 /* Clear snapshot if freshly captured and no target was found */
5890 if (new_snapshot
&& !killed
) {
5892 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5896 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5897 memorystatus_available_pages
, killed
? aPid
: 0, 0, 0, 0);
5903 * Jetsam aggressively
5906 memorystatus_kill_top_process_aggressive(uint32_t cause
, int aggr_count
,
5907 int32_t priority_max
, uint32_t *errors
)
5910 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5911 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5914 int32_t aPid_ep
= 0;
5915 unsigned int memorystatus_level_snapshot
= 0;
5916 uint64_t killtime
= 0;
5918 clock_usec_t tv_usec
;
5920 os_reason_t jetsam_reason
= OS_REASON_NULL
;
5922 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5923 memorystatus_available_pages
, priority_max
, 0, 0, 0);
5925 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
5927 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, cause
);
5928 if (jetsam_reason
== OS_REASON_NULL
) {
5929 printf("memorystatus_kill_top_process_aggressive: failed to allocate exit reason\n");
5934 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5936 #if DEVELOPMENT || DEBUG
5938 int procSuspendedForDiagnosis
;
5939 #endif /* DEVELOPMENT || DEBUG */
5941 if (((next_p
->p_listflag
& P_LIST_EXITED
) != 0) ||
5942 ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
)) {
5944 * We have raced with next_p running on another core.
5945 * It may be exiting or it may have moved to a different
5946 * jetsam priority band. This means we have lost our
5947 * place in line while traversing the jetsam list. We
5948 * attempt to recover by rewinding to the beginning of the band
5949 * we were already traversing. By doing this, we do not guarantee
5950 * that no process escapes this aggressive march, but we can make
5951 * skipping an entire range of processes less likely. (PR-21069019)
5954 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding band %d, %s(%d) moved or exiting.\n",
5955 aggr_count
, i
, (*next_p
->p_name
? next_p
->p_name
: "unknown"), next_p
->p_pid
);
5957 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5962 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5964 if (p
->p_memstat_effectivepriority
> priority_max
) {
5966 * Bail out of this killing spree if we have
5967 * reached beyond the priority_max jetsam band.
5968 * That is, we kill up to and through the
5969 * priority_max jetsam band.
5975 #if DEVELOPMENT || DEBUG
5976 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
5977 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
5978 #endif /* DEVELOPMENT || DEBUG */
5981 aPid_ep
= p
->p_memstat_effectivepriority
;
5983 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5987 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5988 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
5989 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
5992 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5995 * Capture a snapshot if none exists.
5997 if (memorystatus_jetsam_snapshot_count
== 0) {
5998 memorystatus_init_jetsam_snapshot_locked(NULL
, 0);
5999 new_snapshot
= TRUE
;
6003 * Mark as terminated so that if exit1() indicates success, but the process (for example)
6004 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
6005 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
6006 * acquisition of the proc lock.
6008 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
6010 killtime
= mach_absolute_time();
6011 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
6012 tv_msec
= tv_usec
/ 1000;
6014 /* Shift queue, update stats */
6015 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
6018 * In order to kill the target process, we will drop the proc_list_lock.
6019 * To guaranteee that p and next_p don't disappear out from under the lock,
6020 * we must take a ref on both.
6021 * If we cannot get a reference, then it's likely we've raced with
6022 * that process exiting on another core.
6024 if (proc_ref_locked(p
) == p
) {
6026 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
6030 * We must have raced with next_p exiting on another core.
6031 * Recover by getting the next eligible process in the band.
6034 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
6035 aggr_count
, next_p
->p_pid
, (*next_p
->p_name
? next_p
->p_name
: "(unknown)"));
6038 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
6043 printf("%lu.%03d memorystatus: %s%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
6044 (unsigned long)tv_sec
, tv_msec
,
6045 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "killing_idle_process_aggressive" : "killing_top_process_aggressive"),
6046 aggr_count
, aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
6047 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
6049 memorystatus_level_snapshot
= memorystatus_level
;
6052 * memorystatus_do_kill() drops a reference, so take another one so we can
6053 * continue to use this exit reason even after memorystatus_do_kill()
6056 os_reason_ref(jetsam_reason
);
6057 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
6067 * Continue the killing spree.
6071 proc_rele_locked(next_p
);
6074 if (aPid_ep
== JETSAM_PRIORITY_FOREGROUND
&& memorystatus_aggressive_jetsam_lenient
== TRUE
) {
6075 if (memorystatus_level
> memorystatus_level_snapshot
&& ((memorystatus_level
- memorystatus_level_snapshot
) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD
)) {
6076 #if DEVELOPMENT || DEBUG
6077 printf("Disabling Lenient mode after one-time deployment.\n");
6078 #endif /* DEVELOPMENT || DEBUG */
6079 memorystatus_aggressive_jetsam_lenient
= FALSE
;
6088 * Failure - first unwind the state,
6089 * then fall through to restart the search.
6092 proc_rele_locked(p
);
6094 proc_rele_locked(next_p
);
6096 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
6097 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
6103 * Failure - restart the search at the beginning of
6104 * the band we were already traversing.
6106 * We might have raced with "p" exiting on another core, resulting in no
6107 * ref on "p". Or, we may have failed to kill "p".
6109 * Either way, we fall thru to here, leaving the proc in the
6110 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
6112 * And, we hold the the proc_list_lock at this point.
6115 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6121 os_reason_free(jetsam_reason
);
6123 /* Clear snapshot if freshly captured and no target was found */
6124 if (new_snapshot
&& (kill_count
== 0)) {
6126 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
6130 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
6131 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
6133 if (kill_count
> 0) {
6141 memorystatus_kill_hiwat_proc(uint32_t *errors
, boolean_t
*purged
)
6144 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
6145 boolean_t new_snapshot
= FALSE
, killed
= FALSE
, freed_mem
= FALSE
;
6148 os_reason_t jetsam_reason
= OS_REASON_NULL
;
6149 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
6150 memorystatus_available_pages
, 0, 0, 0, 0);
6152 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_HIGHWATER
);
6153 if (jetsam_reason
== OS_REASON_NULL
) {
6154 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
6159 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6161 uint64_t footprint_in_bytes
= 0;
6162 uint64_t memlimit_in_bytes
= 0;
6166 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6169 aPid_ep
= p
->p_memstat_effectivepriority
;
6171 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
6175 /* skip if no limit set */
6176 if (p
->p_memstat_memlimit
<= 0) {
6180 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
6181 memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
6182 skip
= (footprint_in_bytes
<= memlimit_in_bytes
);
6184 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
6185 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
6186 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
6190 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
6194 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
6205 if (memorystatus_jetsam_snapshot_count
== 0) {
6206 memorystatus_init_jetsam_snapshot_locked(NULL
, 0);
6207 new_snapshot
= TRUE
;
6210 if (proc_ref_locked(p
) == p
) {
6212 * Mark as terminated so that if exit1() indicates success, but the process (for example)
6213 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
6214 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
6215 * acquisition of the proc lock.
6217 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
6222 * We need to restart the search again because
6223 * proc_ref_locked _can_ drop the proc_list lock
6224 * and we could have lost our stored next_p via
6225 * an exit() on another core.
6228 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6232 freed_mem
= memorystatus_kill_proc(p
, kMemorystatusKilledHiwat
, jetsam_reason
, &killed
); /* purged and/or killed 'p' */
6236 if (killed
== FALSE
) {
6237 /* purged 'p'..don't reset HWM candidate count */
6241 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
6248 * Failure - first unwind the state,
6249 * then fall through to restart the search.
6252 proc_rele_locked(p
);
6253 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
6254 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
6258 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6265 os_reason_free(jetsam_reason
);
6267 /* Clear snapshot if freshly captured and no target was found */
6268 if (new_snapshot
&& !killed
) {
6270 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
6274 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
6275 memorystatus_available_pages
, killed
? aPid
: 0, 0, 0, 0);
6281 * Jetsam a process pinned in the elevated band.
6283 * Return: true -- at least one pinned process was jetsammed
6284 * false -- no pinned process was jetsammed
6287 memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, unsigned int band
, int aggr_count
, uint32_t *errors
)
6290 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
6291 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
6294 uint64_t killtime
= 0;
6296 clock_usec_t tv_usec
;
6300 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
6301 memorystatus_available_pages
, 0, 0, 0, 0);
6304 boolean_t consider_frozen_only
= FALSE
;
6306 if (band
== (unsigned int) memorystatus_freeze_jetsam_band
) {
6307 consider_frozen_only
= TRUE
;
6309 #endif /* CONFIG_FREEZE */
6313 next_p
= memorystatus_get_first_proc_locked(&band
, FALSE
);
6316 next_p
= memorystatus_get_next_proc_locked(&band
, p
, FALSE
);
6319 aPid_ep
= p
->p_memstat_effectivepriority
;
6322 * Only pick a process pinned in this elevated band
6324 if (!(p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
6328 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
6333 if (consider_frozen_only
&& !(p
->p_memstat_state
& P_MEMSTAT_FROZEN
)) {
6337 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
6340 #endif /* CONFIG_FREEZE */
6342 #if DEVELOPMENT || DEBUG
6343 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
6345 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
6346 memorystatus_available_pages
);
6347 #endif /* DEVELOPMENT || DEBUG */
6349 if (memorystatus_jetsam_snapshot_count
== 0) {
6350 memorystatus_init_jetsam_snapshot_locked(NULL
, 0);
6351 new_snapshot
= TRUE
;
6354 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
6356 killtime
= mach_absolute_time();
6357 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
6358 tv_msec
= tv_usec
/ 1000;
6360 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
6362 if (proc_ref_locked(p
) == p
) {
6365 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: killing_top_process_elevated%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
6366 (unsigned long)tv_sec
, tv_msec
,
6368 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
6369 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
6372 * memorystatus_do_kill drops a reference, so take another one so we can
6373 * continue to use this exit reason even after memorystatus_do_kill()
6376 os_reason_ref(jetsam_reason
);
6377 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
6387 * Failure - first unwind the state,
6388 * then fall through to restart the search.
6391 proc_rele_locked(p
);
6392 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
6393 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
6398 * Failure - restart the search.
6400 * We might have raced with "p" exiting on another core, resulting in no
6401 * ref on "p". Or, we may have failed to kill "p".
6403 * Either way, we fall thru to here, leaving the proc in the
6404 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
6406 * And, we hold the the proc_list_lock at this point.
6409 next_p
= memorystatus_get_first_proc_locked(&band
, FALSE
);
6415 os_reason_free(jetsam_reason
);
6417 /* Clear snapshot if freshly captured and no target was found */
6418 if (new_snapshot
&& (kill_count
== 0)) {
6420 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
6424 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
6425 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
6431 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
)
6434 * TODO: allow a general async path
6436 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
6437 * add the appropriate exit reason code mapping.
6439 if ((victim_pid
!= -1) ||
6440 (cause
!= kMemorystatusKilledVMPageShortage
&&
6441 cause
!= kMemorystatusKilledVMCompressorThrashing
&&
6442 cause
!= kMemorystatusKilledVMCompressorSpaceShortage
&&
6443 cause
!= kMemorystatusKilledFCThrashing
&&
6444 cause
!= kMemorystatusKilledZoneMapExhaustion
)) {
6448 kill_under_pressure_cause
= cause
;
6449 memorystatus_thread_wake();
6454 memorystatus_kill_on_VM_compressor_space_shortage(boolean_t async
)
6457 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMCompressorSpaceShortage
);
6459 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE
);
6460 if (jetsam_reason
== OS_REASON_NULL
) {
6461 printf("memorystatus_kill_on_VM_compressor_space_shortage -- sync: failed to allocate jetsam reason\n");
6464 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMCompressorSpaceShortage
, jetsam_reason
);
6470 memorystatus_kill_on_VM_compressor_thrashing(boolean_t async
)
6473 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMCompressorThrashing
);
6475 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING
);
6476 if (jetsam_reason
== OS_REASON_NULL
) {
6477 printf("memorystatus_kill_on_VM_compressor_thrashing -- sync: failed to allocate jetsam reason\n");
6480 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMCompressorThrashing
, jetsam_reason
);
6485 memorystatus_kill_on_VM_page_shortage(boolean_t async
)
6488 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
6490 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMPAGESHORTAGE
);
6491 if (jetsam_reason
== OS_REASON_NULL
) {
6492 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
6495 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
, jetsam_reason
);
6500 memorystatus_kill_on_FC_thrashing(boolean_t async
)
6503 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
6505 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_FCTHRASHING
);
6506 if (jetsam_reason
== OS_REASON_NULL
) {
6507 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
6510 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
, jetsam_reason
);
6515 memorystatus_kill_on_vnode_limit(void)
6517 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_VNODE
);
6518 if (jetsam_reason
== OS_REASON_NULL
) {
6519 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
6522 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
, jetsam_reason
);
6525 #endif /* CONFIG_JETSAM */
6528 memorystatus_kill_on_zone_map_exhaustion(pid_t pid
)
6530 boolean_t res
= FALSE
;
6532 res
= memorystatus_kill_process_async(-1, kMemorystatusKilledZoneMapExhaustion
);
6534 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_ZONE_MAP_EXHAUSTION
);
6535 if (jetsam_reason
== OS_REASON_NULL
) {
6536 printf("memorystatus_kill_on_zone_map_exhaustion: failed to allocate jetsam reason\n");
6539 res
= memorystatus_kill_process_sync(pid
, kMemorystatusKilledZoneMapExhaustion
, jetsam_reason
);
6546 __private_extern__
void
6547 memorystatus_freeze_init(void)
6549 kern_return_t result
;
6552 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
6553 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
6555 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
6558 * This is just the default value if the underlying
6559 * storage device doesn't have any specific budget.
6560 * We check with the storage layer in memorystatus_freeze_update_throttle()
6561 * before we start our freezing the first time.
6563 memorystatus_freeze_budget_pages_remaining
= (memorystatus_freeze_daily_mb_max
* 1024 * 1024) / PAGE_SIZE
;
6565 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
6566 if (result
== KERN_SUCCESS
) {
6567 proc_set_thread_policy(thread
, TASK_POLICY_INTERNAL
, TASK_POLICY_IO
, THROTTLE_LEVEL_COMPRESSOR_TIER2
);
6568 proc_set_thread_policy(thread
, TASK_POLICY_INTERNAL
, TASK_POLICY_PASSIVE_IO
, TASK_POLICY_ENABLE
);
6569 thread_set_thread_name(thread
, "VM_freezer");
6571 thread_deallocate(thread
);
6573 panic("Could not create memorystatus_freeze_thread");
6578 memorystatus_is_process_eligible_for_freeze(proc_t p
)
6581 * Called with proc_list_lock held.
6584 LCK_MTX_ASSERT(proc_list_mlock
, LCK_MTX_ASSERT_OWNED
);
6586 boolean_t should_freeze
= FALSE
;
6587 uint32_t state
= 0, entry_count
= 0, pages
= 0, i
= 0;
6588 int probability_of_use
= 0;
6590 if (isApp(p
) == FALSE
) {
6594 state
= p
->p_memstat_state
;
6596 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FREEZE_DISABLED
| P_MEMSTAT_FREEZE_IGNORE
)) ||
6597 !(state
& P_MEMSTAT_SUSPENDED
)) {
6601 /* Only freeze processes meeting our minimum resident page criteria */
6602 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
);
6603 if (pages
< memorystatus_freeze_pages_min
) {
6607 entry_count
= (memorystatus_global_probabilities_size
/ sizeof(memorystatus_internal_probabilities_t
));
6610 for (i
= 0; i
< entry_count
; i
++) {
6611 if (strncmp(memorystatus_global_probabilities_table
[i
].proc_name
,
6613 MAXCOMLEN
+ 1) == 0) {
6614 probability_of_use
= memorystatus_global_probabilities_table
[i
].use_probability
;
6619 if (probability_of_use
== 0) {
6624 should_freeze
= TRUE
;
6626 return should_freeze
;
6630 * Synchronously freeze the passed proc. Called with a reference to the proc held.
6632 * Doesn't deal with re-freezing because this is called on a specific process and
6633 * not by the freezer thread. If that changes, we'll have to teach it about
6634 * refreezing a frozen process.
6636 * Returns EINVAL or the value returned by task_freeze().
6639 memorystatus_freeze_process_sync(proc_t p
)
6643 boolean_t memorystatus_freeze_swap_low
= FALSE
;
6644 int freezer_error_code
= 0;
6646 lck_mtx_lock(&freezer_mutex
);
6649 printf("memorystatus_freeze_process_sync: Invalid process\n");
6653 if (memorystatus_freeze_enabled
== FALSE
) {
6654 printf("memorystatus_freeze_process_sync: Freezing is DISABLED\n");
6658 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
6659 printf("memorystatus_freeze_process_sync: Low compressor and/or low swap space...skipping freeze\n");
6663 memorystatus_freeze_update_throttle(&memorystatus_freeze_budget_pages_remaining
);
6664 if (!memorystatus_freeze_budget_pages_remaining
) {
6665 printf("memorystatus_freeze_process_sync: exit with NO available budget\n");
6672 uint32_t purgeable
, wired
, clean
, dirty
, shared
;
6673 uint32_t max_pages
, i
;
6677 /* Ensure the process is eligible for freezing */
6678 if (memorystatus_is_process_eligible_for_freeze(p
) == FALSE
) {
6683 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
6684 max_pages
= MIN(memorystatus_freeze_pages_max
, memorystatus_freeze_budget_pages_remaining
);
6687 * We only have the compressor without any swap.
6689 max_pages
= UINT32_MAX
- 1;
6692 /* Mark as locked temporarily to avoid kill */
6693 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
6696 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
6697 memorystatus_available_pages
, 0, 0, 0, 0);
6699 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, &freezer_error_code
, FALSE
/* eval only */);
6701 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
6702 memorystatus_available_pages
, aPid
, 0, 0, 0);
6704 DTRACE_MEMORYSTATUS6(memorystatus_freeze
, proc_t
, p
, unsigned int, memorystatus_available_pages
, boolean_t
, purgeable
, unsigned int, wired
, uint32_t, clean
, uint32_t, dirty
);
6706 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
6707 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
6708 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
6709 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
6713 if (ret
== KERN_SUCCESS
) {
6714 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: freezing (specific) pid %d [%s]...done",
6715 aPid
, (*p
->p_name
? p
->p_name
: "unknown"));
6717 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
6719 p
->p_memstat_freeze_sharedanon_pages
+= shared
;
6721 memorystatus_frozen_shared_mb
+= shared
;
6723 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == 0) {
6724 p
->p_memstat_state
|= P_MEMSTAT_FROZEN
;
6725 memorystatus_frozen_count
++;
6728 p
->p_memstat_frozen_count
++;
6731 * Still keeping the P_MEMSTAT_LOCKED bit till we are actually done elevating this frozen process
6732 * to its higher jetsam band.
6736 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
6738 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
6739 ret
= memorystatus_update_inactive_jetsam_priority_band(p
->p_pid
, MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
,
6740 memorystatus_freeze_jetsam_band
, TRUE
);
6743 printf("Elevating the frozen process failed with %d\n", ret
);
6751 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
6752 throttle_intervals
[i
].pageouts
+= dirty
;
6758 memorystatus_freeze_pageouts
+= dirty
;
6760 if (memorystatus_frozen_count
== (memorystatus_frozen_processes_max
- 1)) {
6762 * Add some eviction logic here? At some point should we
6763 * jetsam a process to get back its swap space so that we
6764 * can freeze a more eligible process at this moment in time?
6769 if (freezer_error_code
== FREEZER_ERROR_EXCESS_SHARED_MEMORY
) {
6770 strlcpy(reason
, "too much shared memory", 128);
6773 if (freezer_error_code
== FREEZER_ERROR_LOW_PRIVATE_SHARED_RATIO
) {
6774 strlcpy(reason
, "low private-shared pages ratio", 128);
6777 if (freezer_error_code
== FREEZER_ERROR_NO_COMPRESSOR_SPACE
) {
6778 strlcpy(reason
, "no compressor space", 128);
6781 if (freezer_error_code
== FREEZER_ERROR_NO_SWAP_SPACE
) {
6782 strlcpy(reason
, "no swap space", 128);
6785 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: freezing (specific) pid %d [%s]...skipped (%s)",
6786 aPid
, (*p
->p_name
? p
->p_name
: "unknown"), reason
);
6787 p
->p_memstat_state
|= P_MEMSTAT_FREEZE_IGNORE
;
6790 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
6795 lck_mtx_unlock(&freezer_mutex
);
6801 memorystatus_freeze_top_process(void)
6805 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
6807 unsigned int band
= JETSAM_PRIORITY_IDLE
;
6808 boolean_t refreeze_processes
= FALSE
;
6812 if (memorystatus_frozen_count
>= memorystatus_frozen_processes_max
) {
6814 * Freezer is already full but we are here and so let's
6815 * try to refreeze any processes we might have thawed
6816 * in the past and push out their compressed state out.
6818 refreeze_processes
= TRUE
;
6819 band
= (unsigned int) memorystatus_freeze_jetsam_band
;
6824 next_p
= memorystatus_get_first_proc_locked(&band
, FALSE
);
6827 uint32_t purgeable
, wired
, clean
, dirty
, shared
;
6828 uint32_t max_pages
= 0;
6829 int freezer_error_code
= 0;
6832 next_p
= memorystatus_get_next_proc_locked(&band
, p
, FALSE
);
6836 if (p
->p_memstat_effectivepriority
!= (int32_t) band
) {
6838 * We shouldn't be freezing processes outside the
6844 /* Ensure the process is eligible for (re-)freezing */
6845 if (refreeze_processes
) {
6847 * Has to have been frozen once before.
6849 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == FALSE
) {
6854 * Has to have been resumed once before.
6856 if ((p
->p_memstat_state
& P_MEMSTAT_REFREEZE_ELIGIBLE
) == FALSE
) {
6861 * Not currently being looked at for something.
6863 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
6868 * We are going to try and refreeze and so re-evaluate
6869 * the process. We don't want to double count the shared
6870 * memory. So deduct the old snapshot here.
6872 memorystatus_frozen_shared_mb
-= p
->p_memstat_freeze_sharedanon_pages
;
6873 p
->p_memstat_freeze_sharedanon_pages
= 0;
6875 p
->p_memstat_state
&= ~P_MEMSTAT_REFREEZE_ELIGIBLE
;
6876 memorystatus_refreeze_eligible_count
--;
6878 if (memorystatus_is_process_eligible_for_freeze(p
) == FALSE
) {
6879 continue; // with lock held
6883 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
6885 * Freezer backed by the compressor and swap file(s)
6886 * will hold compressed data.
6889 max_pages
= MIN(memorystatus_freeze_pages_max
, memorystatus_freeze_budget_pages_remaining
);
6892 * We only have the compressor pool.
6894 max_pages
= UINT32_MAX
- 1;
6897 /* Mark as locked temporarily to avoid kill */
6898 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
6900 p
= proc_ref_locked(p
);
6907 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
6908 memorystatus_available_pages
, 0, 0, 0, 0);
6910 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, &freezer_error_code
, FALSE
/* eval only */);
6912 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
6913 memorystatus_available_pages
, aPid
, 0, 0, 0);
6915 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
6916 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
6917 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
6918 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
6923 if (KERN_SUCCESS
== kr
) {
6924 if (refreeze_processes
) {
6925 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: Refreezing (general) pid %d [%s]...done",
6926 aPid
, (*p
->p_name
? p
->p_name
: "unknown"));
6928 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: freezing (general) pid %d [%s]...done",
6929 aPid
, (*p
->p_name
? p
->p_name
: "unknown"));
6932 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
6934 p
->p_memstat_freeze_sharedanon_pages
+= shared
;
6936 memorystatus_frozen_shared_mb
+= shared
;
6938 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == 0) {
6939 p
->p_memstat_state
|= P_MEMSTAT_FROZEN
;
6940 memorystatus_frozen_count
++;
6943 p
->p_memstat_frozen_count
++;
6946 * Still keeping the P_MEMSTAT_LOCKED bit till we are actually done elevating this frozen process
6947 * to its higher jetsam band.
6951 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
6953 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
6954 ret
= memorystatus_update_inactive_jetsam_priority_band(p
->p_pid
, MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
, memorystatus_freeze_jetsam_band
, TRUE
);
6957 printf("Elevating the frozen process failed with %d\n", ret
);
6965 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
6966 throttle_intervals
[i
].pageouts
+= dirty
;
6972 memorystatus_freeze_pageouts
+= dirty
;
6974 if (memorystatus_frozen_count
== (memorystatus_frozen_processes_max
- 1)) {
6976 * Add some eviction logic here? At some point should we
6977 * jetsam a process to get back its swap space so that we
6978 * can freeze a more eligible process at this moment in time?
6982 /* Return KERN_SUCCESS */
6985 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
6986 proc_rele_locked(p
);
6989 * We froze a process successfully. We can stop now
6990 * and see if that helped.
6995 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
6997 if (refreeze_processes
== TRUE
) {
6998 if ((freezer_error_code
== FREEZER_ERROR_EXCESS_SHARED_MEMORY
) ||
6999 (freezer_error_code
== FREEZER_ERROR_LOW_PRIVATE_SHARED_RATIO
)) {
7001 * Keeping this prior-frozen process in this high band when
7002 * we failed to re-freeze it due to bad shared memory usage
7003 * could cause excessive pressure on the lower bands.
7004 * We need to demote it for now. It'll get re-evaluated next
7005 * time because we don't set the P_MEMSTAT_FREEZE_IGNORE
7009 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
7010 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7011 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, TRUE
, TRUE
);
7014 p
->p_memstat_state
|= P_MEMSTAT_FREEZE_IGNORE
;
7017 proc_rele_locked(p
);
7020 if (freezer_error_code
== FREEZER_ERROR_EXCESS_SHARED_MEMORY
) {
7021 strlcpy(reason
, "too much shared memory", 128);
7024 if (freezer_error_code
== FREEZER_ERROR_LOW_PRIVATE_SHARED_RATIO
) {
7025 strlcpy(reason
, "low private-shared pages ratio", 128);
7028 if (freezer_error_code
== FREEZER_ERROR_NO_COMPRESSOR_SPACE
) {
7029 strlcpy(reason
, "no compressor space", 128);
7032 if (freezer_error_code
== FREEZER_ERROR_NO_SWAP_SPACE
) {
7033 strlcpy(reason
, "no swap space", 128);
7036 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: freezing (general) pid %d [%s]...skipped (%s)",
7037 aPid
, (*p
->p_name
? p
->p_name
: "unknown"), reason
);
7039 if (vm_compressor_low_on_space() || vm_swap_low_on_space()) {
7046 (memorystatus_refreeze_eligible_count
>= MIN_THAW_REFREEZE_THRESHOLD
) &&
7047 (refreeze_processes
== FALSE
)) {
7049 * We failed to freeze a process from the IDLE
7050 * band AND we have some thawed processes
7051 * AND haven't tried refreezing as yet.
7052 * Let's try and re-freeze processes in the
7053 * frozen band that have been resumed in the past
7054 * and so have brought in state from disk.
7057 band
= (unsigned int) memorystatus_freeze_jetsam_band
;
7059 refreeze_processes
= TRUE
;
7061 goto freeze_process
;
7069 static inline boolean_t
7070 memorystatus_can_freeze_processes(void)
7076 if (memorystatus_suspended_count
) {
7077 memorystatus_freeze_suspended_threshold
= MIN(memorystatus_freeze_suspended_threshold
, FREEZE_SUSPENDED_THRESHOLD_DEFAULT
);
7079 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
7094 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
7096 boolean_t can_freeze
= TRUE
;
7098 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
7099 * after boot, and is generally is a no-op once we've reached steady state. */
7100 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
7104 /* Check minimum suspended process threshold. */
7105 if (!memorystatus_can_freeze_processes()) {
7108 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT
);
7110 if (!VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
7112 * In-core compressor used for freezing WITHOUT on-disk swap support.
7114 if (vm_compressor_low_on_space()) {
7115 if (*memorystatus_freeze_swap_low
) {
7116 *memorystatus_freeze_swap_low
= TRUE
;
7121 if (*memorystatus_freeze_swap_low
) {
7122 *memorystatus_freeze_swap_low
= FALSE
;
7129 * Freezing WITH on-disk swap support.
7131 * In-core compressor fronts the swap.
7133 if (vm_swap_low_on_space()) {
7134 if (*memorystatus_freeze_swap_low
) {
7135 *memorystatus_freeze_swap_low
= TRUE
;
7146 * This function evaluates if the currently frozen processes deserve
7147 * to stay in the higher jetsam band. If the # of thaws of a process
7148 * is below our threshold, then we will demote that process into the IDLE
7149 * band and put it at the head. We don't immediately kill the process here
7150 * because it already has state on disk and so it might be worth giving
7151 * it another shot at getting thawed/resumed and used.
7154 memorystatus_demote_frozen_processes(void)
7156 unsigned int band
= (unsigned int) memorystatus_freeze_jetsam_band
;
7157 unsigned int demoted_proc_count
= 0;
7158 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
7162 if (memorystatus_freeze_enabled
== FALSE
) {
7164 * Freeze has been disabled likely to
7165 * reclaim swap space. So don't change
7166 * any state on the frozen processes.
7172 next_p
= memorystatus_get_first_proc_locked(&band
, FALSE
);
7175 next_p
= memorystatus_get_next_proc_locked(&band
, p
, FALSE
);
7177 if ((p
->p_memstat_state
& P_MEMSTAT_FROZEN
) == FALSE
) {
7181 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
7185 if (p
->p_memstat_thaw_count
< memorystatus_thaw_count_demotion_threshold
) {
7186 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
7187 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7189 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, TRUE
, TRUE
);
7190 #if DEVELOPMENT || DEBUG
7191 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus_demote_frozen_process pid %d [%s]",
7192 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"));
7193 #endif /* DEVELOPMENT || DEBUG */
7196 * The freezer thread will consider this a normal app to be frozen
7197 * because it is in the IDLE band. So we don't need the
7198 * P_MEMSTAT_REFREEZE_ELIGIBLE state here. Also, if it gets resumed
7199 * we'll correctly count it as eligible for re-freeze again.
7201 * We don't drop the frozen count because this process still has
7202 * state on disk. So there's a chance it gets resumed and then it
7203 * should land in the higher jetsam band. For that it needs to
7204 * remain marked frozen.
7206 if (p
->p_memstat_state
& P_MEMSTAT_REFREEZE_ELIGIBLE
) {
7207 p
->p_memstat_state
&= ~P_MEMSTAT_REFREEZE_ELIGIBLE
;
7208 memorystatus_refreeze_eligible_count
--;
7211 demoted_proc_count
++;
7214 if (demoted_proc_count
== memorystatus_max_frozen_demotions_daily
) {
7219 memorystatus_thaw_count
= 0;
7225 * This function will do 4 things:
7227 * 1) check to see if we are currently in a degraded freezer mode, and if so:
7228 * - check to see if our window has expired and we should exit this mode, OR,
7229 * - return a budget based on the degraded throttle window's max. pageouts vs current pageouts.
7231 * 2) check to see if we are in a NEW normal window and update the normal throttle window's params.
7233 * 3) check what the current normal window allows for a budget.
7235 * 4) calculate the current rate of pageouts for DEGRADED_WINDOW_MINS duration. If that rate is below
7236 * what we would normally expect, then we are running low on our daily budget and need to enter
7237 * degraded perf. mode.
7241 memorystatus_freeze_update_throttle(uint64_t *budget_pages_allowed
)
7247 unsigned int freeze_daily_pageouts_max
= 0;
7249 #if DEVELOPMENT || DEBUG
7250 if (!memorystatus_freeze_throttle_enabled
) {
7252 * No throttling...we can use the full budget everytime.
7254 *budget_pages_allowed
= UINT64_MAX
;
7259 clock_get_system_nanotime(&sec
, &nsec
);
7263 struct throttle_interval_t
*interval
= NULL
;
7265 if (memorystatus_freeze_degradation
== TRUE
) {
7266 interval
= degraded_throttle_window
;
7268 if (CMP_MACH_TIMESPEC(&ts
, &interval
->ts
) >= 0) {
7269 memorystatus_freeze_degradation
= FALSE
;
7270 interval
->pageouts
= 0;
7271 interval
->max_pageouts
= 0;
7273 *budget_pages_allowed
= interval
->max_pageouts
- interval
->pageouts
;
7277 interval
= normal_throttle_window
;
7279 if (CMP_MACH_TIMESPEC(&ts
, &interval
->ts
) >= 0) {
7281 * New throttle window.
7282 * Rollover any unused budget.
7283 * Also ask the storage layer what the new budget needs to be.
7285 uint64_t freeze_daily_budget
= 0;
7286 unsigned int daily_budget_pageouts
= 0;
7288 if (vm_swap_max_budget(&freeze_daily_budget
)) {
7289 memorystatus_freeze_daily_mb_max
= (freeze_daily_budget
/ (1024 * 1024));
7290 os_log_with_startup_serial(OS_LOG_DEFAULT
, "memorystatus: memorystatus_freeze_daily_mb_max set to %dMB\n", memorystatus_freeze_daily_mb_max
);
7293 freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
7295 daily_budget_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / NORMAL_WINDOW_MINS
));
7296 interval
->max_pageouts
= (interval
->max_pageouts
- interval
->pageouts
) + daily_budget_pageouts
;
7298 interval
->ts
.tv_sec
= interval
->mins
* 60;
7299 interval
->ts
.tv_nsec
= 0;
7300 ADD_MACH_TIMESPEC(&interval
->ts
, &ts
);
7301 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
7302 if (interval
->pageouts
> interval
->max_pageouts
) {
7303 interval
->pageouts
-= interval
->max_pageouts
;
7305 interval
->pageouts
= 0;
7307 *budget_pages_allowed
= interval
->max_pageouts
;
7309 memorystatus_demote_frozen_processes();
7312 * Current throttle window.
7313 * Deny freezing if we have no budget left.
7314 * Try graceful degradation if we are within 25% of:
7315 * - the daily budget, and
7316 * - the current budget left is below our normal budget expectations.
7319 #if DEVELOPMENT || DEBUG
7321 * This can only happen in the INTERNAL configs because we allow modifying the daily budget for testing.
7324 if (freeze_daily_pageouts_max
> interval
->max_pageouts
) {
7326 * We just bumped the daily budget. Re-evaluate our normal window params.
7328 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / NORMAL_WINDOW_MINS
));
7329 memorystatus_freeze_degradation
= FALSE
; //we'll re-evaluate this below...
7331 #endif /* DEVELOPMENT || DEBUG */
7333 if (memorystatus_freeze_degradation
== FALSE
) {
7334 if (interval
->pageouts
>= interval
->max_pageouts
) {
7335 *budget_pages_allowed
= 0;
7337 int budget_left
= interval
->max_pageouts
- interval
->pageouts
;
7338 int budget_threshold
= (freeze_daily_pageouts_max
* FREEZE_DEGRADATION_BUDGET_THRESHOLD
) / 100;
7340 mach_timespec_t time_left
= {0, 0};
7342 time_left
.tv_sec
= interval
->ts
.tv_sec
;
7343 time_left
.tv_nsec
= 0;
7345 SUB_MACH_TIMESPEC(&time_left
, &ts
);
7347 if (budget_left
<= budget_threshold
) {
7349 * For the current normal window, calculate how much we would pageout in a DEGRADED_WINDOW_MINS duration.
7350 * And also calculate what we would pageout for the same DEGRADED_WINDOW_MINS duration if we had the full
7351 * daily pageout budget.
7354 unsigned int current_budget_rate_allowed
= ((budget_left
/ time_left
.tv_sec
) / 60) * DEGRADED_WINDOW_MINS
;
7355 unsigned int normal_budget_rate_allowed
= (freeze_daily_pageouts_max
/ NORMAL_WINDOW_MINS
) * DEGRADED_WINDOW_MINS
;
7358 * The current rate of pageouts is below what we would expect for
7359 * the normal rate i.e. we have below normal budget left and so...
7362 if (current_budget_rate_allowed
< normal_budget_rate_allowed
) {
7363 memorystatus_freeze_degradation
= TRUE
;
7364 degraded_throttle_window
->max_pageouts
= current_budget_rate_allowed
;
7365 degraded_throttle_window
->pageouts
= 0;
7368 * Switch over to the degraded throttle window so the budget
7369 * doled out is based on that window.
7371 interval
= degraded_throttle_window
;
7375 *budget_pages_allowed
= interval
->max_pageouts
- interval
->pageouts
;
7380 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
7381 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
7382 interval
->throttle
? "on" : "off");
7386 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
7388 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
7390 lck_mtx_lock(&freezer_mutex
);
7392 if (memorystatus_freeze_enabled
) {
7393 if ((memorystatus_frozen_count
< memorystatus_frozen_processes_max
) ||
7394 (memorystatus_refreeze_eligible_count
>= MIN_THAW_REFREEZE_THRESHOLD
)) {
7395 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
7396 /* Only freeze if we've not exceeded our pageout budgets.*/
7397 memorystatus_freeze_update_throttle(&memorystatus_freeze_budget_pages_remaining
);
7399 if (memorystatus_freeze_budget_pages_remaining
) {
7400 memorystatus_freeze_top_process();
7407 * We use memorystatus_apps_idle_delay_time because if/when we adopt aging for applications,
7408 * it'll tie neatly into running the freezer once we age an application.
7410 * Till then, it serves as a good interval that can be tuned via a sysctl too.
7412 memorystatus_freezer_thread_next_run_ts
= mach_absolute_time() + memorystatus_apps_idle_delay_time
;
7414 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
7415 lck_mtx_unlock(&freezer_mutex
);
7417 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
7421 memorystatus_freeze_thread_should_run(void)
7424 * No freezer_mutex held here...see why near call-site
7425 * within memorystatus_pages_update().
7428 boolean_t should_run
= FALSE
;
7430 if (memorystatus_freeze_enabled
== FALSE
) {
7434 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
7438 if ((memorystatus_frozen_count
>= memorystatus_frozen_processes_max
) &&
7439 (memorystatus_refreeze_eligible_count
< MIN_THAW_REFREEZE_THRESHOLD
)) {
7443 if (memorystatus_frozen_shared_mb_max
&& (memorystatus_frozen_shared_mb
>= memorystatus_frozen_shared_mb_max
)) {
7447 uint64_t curr_time
= mach_absolute_time();
7449 if (curr_time
< memorystatus_freezer_thread_next_run_ts
) {
7460 sysctl_memorystatus_do_fastwake_warmup_all SYSCTL_HANDLER_ARGS
7462 #pragma unused(oidp, req, arg1, arg2)
7464 /* Need to be root or have entitlement */
7465 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
7469 if (memorystatus_freeze_enabled
== FALSE
) {
7473 do_fastwake_warmup_all();
7478 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_do_fastwake_warmup_all
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
7479 0, 0, &sysctl_memorystatus_do_fastwake_warmup_all
, "I", "");
7481 #endif /* CONFIG_FREEZE */
7483 #if VM_PRESSURE_EVENTS
7485 #if CONFIG_MEMORYSTATUS
7488 memorystatus_send_note(int event_code
, void *data
, size_t data_length
)
7491 struct kev_msg ev_msg
;
7493 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7494 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
7495 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
7497 ev_msg
.event_code
= event_code
;
7499 ev_msg
.dv
[0].data_length
= data_length
;
7500 ev_msg
.dv
[0].data_ptr
= data
;
7501 ev_msg
.dv
[1].data_length
= 0;
7503 ret
= kev_post_msg(&ev_msg
);
7505 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
7512 memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t limit_exceeded
)
7514 boolean_t ret
= FALSE
;
7515 boolean_t found_knote
= FALSE
;
7516 struct knote
*kn
= NULL
;
7517 int send_knote_count
= 0;
7520 * See comment in sysctl_memorystatus_vm_pressure_send.
7523 memorystatus_klist_lock();
7525 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
7526 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
7527 pid_t knote_pid
= knote_proc
->p_pid
;
7529 if (knote_pid
== pid
) {
7531 * By setting the "fflags" here, we are forcing
7532 * a process to deal with the case where it's
7533 * bumping up into its memory limits. If we don't
7534 * do this here, we will end up depending on the
7535 * system pressure snapshot evaluation in
7536 * filt_memorystatus().
7540 if (!limit_exceeded
) {
7542 * Intentionally set either the unambiguous limit warning,
7543 * the system-wide critical or the system-wide warning
7547 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
7548 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7551 } else if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
7552 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
7555 } else if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
7556 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
7562 * Send this notification when a process has exceeded a soft limit.
7564 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
7565 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
7570 #else /* CONFIG_EMBEDDED */
7571 if (!limit_exceeded
) {
7573 * Processes on desktop are not expecting to handle a system-wide
7574 * critical or system-wide warning notification from this path.
7575 * Intentionally set only the unambiguous limit warning here.
7577 * If the limit is soft, however, limit this to one notification per
7578 * active/inactive limit (per each registered listener).
7581 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
7585 * Restrict proc_limit_warn notifications when
7586 * non-fatal (soft) limit is at play.
7589 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
7591 * Mark this knote for delivery.
7593 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7595 * And suppress it from future notifications.
7597 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
7601 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
7603 * Mark this knote for delivery.
7605 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7607 * And suppress it from future notifications.
7609 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
7615 * No restriction on proc_limit_warn notifications when
7616 * fatal (hard) limit is at play.
7618 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7624 * Send this notification when a process has exceeded a soft limit,
7627 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
7631 * Restrict critical notifications for soft limits.
7635 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
7637 * Suppress future proc_limit_critical notifications
7638 * for the active soft limit.
7640 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
7641 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
7645 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
7647 * Suppress future proc_limit_critical_notifications
7648 * for the inactive soft limit.
7650 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
7651 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
7657 * We should never be trying to send a critical notification for
7658 * a hard limit... the process would be killed before it could be
7661 panic("Caught sending pid %d a critical warning for a fatal limit.\n", pid
);
7665 #endif /* CONFIG_EMBEDDED */
7670 if (send_knote_count
> 0) {
7671 KNOTE(&memorystatus_klist
, 0);
7676 memorystatus_klist_unlock();
7682 * Can only be set by the current task on itself.
7685 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
7687 boolean_t set_privilege
= FALSE
;
7689 * Need an entitlement check here?
7691 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
7692 set_privilege
= TRUE
;
7693 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
7694 set_privilege
= FALSE
;
7699 return task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
);
7703 memorystatus_send_pressure_note(pid_t pid
)
7705 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
7706 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
7710 memorystatus_send_low_swap_note(void)
7712 struct knote
*kn
= NULL
;
7714 memorystatus_klist_lock();
7715 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
7716 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
7717 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
7718 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
7719 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
7720 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
7721 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
7726 memorystatus_klist_unlock();
7730 memorystatus_bg_pressure_eligible(proc_t p
)
7732 boolean_t eligible
= FALSE
;
7736 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
7738 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
7739 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
7743 if (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC
) {
7745 * IDLE and IDLE_DEFERRED bands contain processes
7746 * that have dropped memory to be under their inactive
7747 * memory limits. And so they can't really give back
7759 memorystatus_is_foreground_locked(proc_t p
)
7761 return (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
7762 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
);
7766 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
7767 * to access the p_memstat_dirty field.
7770 memorystatus_proc_flags_unsafe(void * v
, boolean_t
*is_dirty
, boolean_t
*is_dirty_tracked
, boolean_t
*allow_idle_exit
)
7774 *is_dirty_tracked
= FALSE
;
7775 *allow_idle_exit
= FALSE
;
7777 proc_t p
= (proc_t
)v
;
7778 *is_dirty
= (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) != 0;
7779 *is_dirty_tracked
= (p
->p_memstat_dirty
& P_DIRTY_TRACK
) != 0;
7780 *allow_idle_exit
= (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) != 0;
7784 #endif /* CONFIG_MEMORYSTATUS */
7787 * Trigger levels to test the mechanism.
7788 * Can be used via a sysctl.
7790 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
7791 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
7792 #define TEST_PURGEABLE_TRIGGER_ONE 3
7793 #define TEST_PURGEABLE_TRIGGER_ALL 4
7794 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
7795 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
7797 boolean_t memorystatus_manual_testing_on
= FALSE
;
7798 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
7800 extern struct knote
*
7801 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
7804 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
7807 #define VM_PRESSURE_DEBUG(cond, format, ...) \
7809 if (cond) { printf(format, ##__VA_ARGS__); } \
7812 #define VM_PRESSURE_DEBUG(cond, format, ...)
7815 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
7818 memorystatus_on_pageout_scan_end(void)
7826 * knote_pressure_level - to check if the knote is registered for this notification level.
7828 * task - task whose bits we'll be modifying
7830 * pressure_level_to_clear - if the task has been notified of this past level, clear that notification bit so that if/when we revert to that level, the task will be notified again.
7832 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
7837 is_knote_registered_modify_task_pressure_bits(struct knote
*kn_max
, int knote_pressure_level
, task_t task
, vm_pressure_level_t pressure_level_to_clear
, vm_pressure_level_t pressure_level_to_set
)
7839 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
7840 if (pressure_level_to_clear
&& task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
7841 task_clear_has_been_notified(task
, pressure_level_to_clear
);
7844 task_mark_has_been_notified(task
, pressure_level_to_set
);
7852 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
)
7854 struct knote
*kn
= NULL
;
7856 memorystatus_klist_lock();
7857 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
7858 proc_t p
= PROC_NULL
;
7859 struct task
* t
= TASK_NULL
;
7861 p
= knote_get_kq(kn
)->kq_p
;
7863 if (p
!= proc_ref_locked(p
)) {
7870 t
= (struct task
*)(p
->task
);
7872 task_clear_has_been_notified(t
, pressure_level_to_clear
);
7877 memorystatus_klist_unlock();
7880 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
7883 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
);
7886 * Used by the vm_pressure_thread which is
7887 * signalled from within vm_pageout_scan().
7889 static void vm_dispatch_memory_pressure(void);
7890 void consider_vm_pressure_events(void);
7893 consider_vm_pressure_events(void)
7895 vm_dispatch_memory_pressure();
7898 vm_dispatch_memory_pressure(void)
7900 memorystatus_update_vm_pressure(FALSE
);
7903 extern vm_pressure_level_t
7904 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
7907 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
)
7909 struct knote
*kn
= NULL
, *kn_max
= NULL
;
7910 uint64_t resident_max
= 0; /* MB */
7911 struct timeval curr_tstamp
= {0, 0};
7912 int elapsed_msecs
= 0;
7913 int selected_task_importance
= 0;
7914 static int pressure_snapshot
= -1;
7915 boolean_t pressure_increase
= FALSE
;
7917 if (pressure_snapshot
== -1) {
7921 pressure_snapshot
= level
;
7922 pressure_increase
= TRUE
;
7924 if (level
&& (level
>= pressure_snapshot
)) {
7925 pressure_increase
= TRUE
;
7927 pressure_increase
= FALSE
;
7930 pressure_snapshot
= level
;
7933 if (pressure_increase
== TRUE
) {
7935 * We'll start by considering the largest
7936 * unimportant task in our list.
7938 selected_task_importance
= INT_MAX
;
7941 * We'll start by considering the largest
7942 * important task in our list.
7944 selected_task_importance
= 0;
7947 microuptime(&curr_tstamp
);
7949 SLIST_FOREACH(kn
, candidate_list
, kn_selnext
) {
7950 uint64_t resident_size
= 0; /* MB */
7951 proc_t p
= PROC_NULL
;
7952 struct task
* t
= TASK_NULL
;
7953 int curr_task_importance
= 0;
7954 boolean_t consider_knote
= FALSE
;
7955 boolean_t privileged_listener
= FALSE
;
7957 p
= knote_get_kq(kn
)->kq_p
;
7959 if (p
!= proc_ref_locked(p
)) {
7966 #if CONFIG_MEMORYSTATUS
7967 if (target_foreground_process
== TRUE
&& !memorystatus_is_foreground_locked(p
)) {
7969 * Skip process not marked foreground.
7974 #endif /* CONFIG_MEMORYSTATUS */
7976 t
= (struct task
*)(p
->task
);
7978 timevalsub(&curr_tstamp
, &p
->vm_pressure_last_notify_tstamp
);
7979 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
7981 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(level
);
7983 if ((kn
->kn_sfflags
& dispatch_level
) == 0) {
7988 #if CONFIG_MEMORYSTATUS
7989 if (target_foreground_process
== FALSE
&& !memorystatus_bg_pressure_eligible(p
)) {
7990 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p
->p_pid
);
7994 #endif /* CONFIG_MEMORYSTATUS */
7997 curr_task_importance
= p
->p_memstat_effectivepriority
;
7998 #else /* CONFIG_EMBEDDED */
7999 curr_task_importance
= task_importance_estimate(t
);
8000 #endif /* CONFIG_EMBEDDED */
8003 * Privileged listeners are only considered in the multi-level pressure scheme
8004 * AND only if the pressure is increasing.
8007 if (task_has_been_notified(t
, level
) == FALSE
) {
8009 * Is this a privileged listener?
8011 if (task_low_mem_privileged_listener(t
, FALSE
, &privileged_listener
) == 0) {
8012 if (privileged_listener
) {
8022 } else if (level
== 0) {
8024 * Task wasn't notified when the pressure was increasing and so
8025 * no need to notify it that the pressure is decreasing.
8027 if ((task_has_been_notified(t
, kVMPressureWarning
) == FALSE
) && (task_has_been_notified(t
, kVMPressureCritical
) == FALSE
)) {
8034 * We don't want a small process to block large processes from
8035 * being notified again. <rdar://problem/7955532>
8037 resident_size
= (get_task_phys_footprint(t
)) / (1024 * 1024ULL); /* MB */
8039 if (resident_size
>= vm_pressure_task_footprint_min
) {
8042 * Warning or Critical Pressure.
8044 if (pressure_increase
) {
8045 if ((curr_task_importance
< selected_task_importance
) ||
8046 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
8048 * We have found a candidate process which is:
8049 * a) at a lower importance than the current selected process
8051 * b) has importance equal to that of the current selected process but is larger
8054 consider_knote
= TRUE
;
8057 if ((curr_task_importance
> selected_task_importance
) ||
8058 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
8060 * We have found a candidate process which is:
8061 * a) at a higher importance than the current selected process
8063 * b) has importance equal to that of the current selected process but is larger
8066 consider_knote
= TRUE
;
8069 } else if (level
== 0) {
8071 * Pressure back to normal.
8073 if ((curr_task_importance
> selected_task_importance
) ||
8074 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
8075 consider_knote
= TRUE
;
8079 if (consider_knote
) {
8080 resident_max
= resident_size
;
8082 selected_task_importance
= curr_task_importance
;
8083 consider_knote
= FALSE
; /* reset for the next candidate */
8086 /* There was no candidate with enough resident memory to scavenge */
8087 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p
->p_pid
, resident_size
);
8094 VM_DEBUG_CONSTANT_EVENT(vm_pressure_event
, VM_PRESSURE_EVENT
, DBG_FUNC_NONE
, knote_get_kq(kn_max
)->kq_p
->p_pid
, resident_max
, 0, 0);
8095 VM_PRESSURE_DEBUG(1, "[vm_pressure] sending event to pid %d with %llu resident\n", knote_get_kq(kn_max
)->kq_p
->p_pid
, resident_max
);
8101 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
8102 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
8103 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
8105 uint64_t next_warning_notification_sent_at_ts
= 0;
8106 uint64_t next_critical_notification_sent_at_ts
= 0;
8109 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
8111 struct knote
*kn_max
= NULL
;
8112 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
8113 pid_t target_pid
= -1;
8114 struct klist dispatch_klist
= { NULL
};
8115 proc_t target_proc
= PROC_NULL
;
8116 struct task
*task
= NULL
;
8117 boolean_t found_candidate
= FALSE
;
8119 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
8120 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
8121 boolean_t smoothing_window_started
= FALSE
;
8122 struct timeval smoothing_window_start_tstamp
= {0, 0};
8123 struct timeval curr_tstamp
= {0, 0};
8124 int elapsed_msecs
= 0;
8125 uint64_t curr_ts
= mach_absolute_time();
8128 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
8130 int idle_kill_counter
= 0;
8133 * On desktop we take this opportunity to free up memory pressure
8134 * by immediately killing idle exitable processes. We use a delay
8135 * to avoid overkill. And we impose a max counter as a fail safe
8136 * in case daemons re-launch too fast.
8138 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
8139 if (memorystatus_idle_exit_from_VM() == FALSE
) {
8140 /* No idle exitable processes left to kill */
8143 idle_kill_counter
++;
8145 if (memorystatus_manual_testing_on
== TRUE
) {
8147 * Skip the delay when testing
8148 * the pressure notification scheme.
8151 delay(1000000); /* 1 second */
8154 #endif /* !CONFIG_JETSAM */
8156 if (level_snapshot
!= kVMPressureNormal
) {
8158 * Check to see if we are still in the 'resting' period
8159 * after having notified all clients interested in
8160 * a particular pressure level.
8163 level_snapshot
= memorystatus_vm_pressure_level
;
8165 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
8166 if (next_warning_notification_sent_at_ts
) {
8167 if (curr_ts
< next_warning_notification_sent_at_ts
) {
8168 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
8169 return KERN_SUCCESS
;
8172 next_warning_notification_sent_at_ts
= 0;
8173 memorystatus_klist_reset_all_for_level(kVMPressureWarning
);
8175 } else if (level_snapshot
== kVMPressureCritical
) {
8176 if (next_critical_notification_sent_at_ts
) {
8177 if (curr_ts
< next_critical_notification_sent_at_ts
) {
8178 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
8179 return KERN_SUCCESS
;
8181 next_critical_notification_sent_at_ts
= 0;
8182 memorystatus_klist_reset_all_for_level(kVMPressureCritical
);
8189 * There is a race window here. But it's not clear
8190 * how much we benefit from having extra synchronization.
8192 level_snapshot
= memorystatus_vm_pressure_level
;
8194 if (prev_level_snapshot
> level_snapshot
) {
8196 * Pressure decreased? Let's take a little breather
8197 * and see if this condition stays.
8199 if (smoothing_window_started
== FALSE
) {
8200 smoothing_window_started
= TRUE
;
8201 microuptime(&smoothing_window_start_tstamp
);
8204 microuptime(&curr_tstamp
);
8205 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
8206 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
8208 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
8209 delay(INTER_NOTIFICATION_DELAY
);
8214 prev_level_snapshot
= level_snapshot
;
8215 smoothing_window_started
= FALSE
;
8217 memorystatus_klist_lock();
8218 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
8220 if (kn_max
== NULL
) {
8221 memorystatus_klist_unlock();
8224 * No more level-based clients to notify.
8226 * Start the 'resting' window within which clients will not be re-notified.
8229 if (level_snapshot
!= kVMPressureNormal
) {
8230 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
8231 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
8233 /* Next warning notification (if nothing changes) won't be sent before...*/
8234 next_warning_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
8237 if (level_snapshot
== kVMPressureCritical
) {
8238 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
8240 /* Next critical notification (if nothing changes) won't be sent before...*/
8241 next_critical_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
8244 return KERN_FAILURE
;
8247 target_proc
= knote_get_kq(kn_max
)->kq_p
;
8250 if (target_proc
!= proc_ref_locked(target_proc
)) {
8251 target_proc
= PROC_NULL
;
8253 memorystatus_klist_unlock();
8258 target_pid
= target_proc
->p_pid
;
8260 task
= (struct task
*)(target_proc
->task
);
8262 if (level_snapshot
!= kVMPressureNormal
) {
8263 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
8264 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, 0, kVMPressureWarning
) == TRUE
) {
8265 found_candidate
= TRUE
;
8268 if (level_snapshot
== kVMPressureCritical
) {
8269 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, 0, kVMPressureCritical
) == TRUE
) {
8270 found_candidate
= TRUE
;
8275 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
8276 task_clear_has_been_notified(task
, kVMPressureWarning
);
8277 task_clear_has_been_notified(task
, kVMPressureCritical
);
8279 found_candidate
= TRUE
;
8283 if (found_candidate
== FALSE
) {
8284 proc_rele(target_proc
);
8285 memorystatus_klist_unlock();
8289 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
8290 int knote_pressure_level
= convert_internal_pressure_level_to_dispatch_level(level_snapshot
);
8292 if (is_knote_registered_modify_task_pressure_bits(kn_cur
, knote_pressure_level
, task
, 0, level_snapshot
) == TRUE
) {
8293 proc_t knote_proc
= knote_get_kq(kn_cur
)->kq_p
;
8294 pid_t knote_pid
= knote_proc
->p_pid
;
8295 if (knote_pid
== target_pid
) {
8296 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
8297 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
8302 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
8304 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
8305 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
8306 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
8309 memorystatus_klist_unlock();
8311 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
8312 proc_rele(target_proc
);
8314 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
8318 if (memorystatus_manual_testing_on
== TRUE
) {
8320 * Testing out the pressure notification scheme.
8321 * No need for delays etc.
8324 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
8326 unsigned int page_delta
= 0;
8327 unsigned int skip_delay_page_threshold
= 0;
8329 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
8331 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
8332 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
8334 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
8336 * We are nearing the critcal mark fast and can't afford to wait between
8341 #endif /* CONFIG_JETSAM */
8343 if (sleep_interval
) {
8344 delay(sleep_interval
);
8349 return KERN_SUCCESS
;
8353 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
8355 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
8357 switch (internal_pressure_level
) {
8358 case kVMPressureNormal
:
8360 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
8364 case kVMPressureWarning
:
8365 case kVMPressureUrgent
:
8367 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
8371 case kVMPressureCritical
:
8373 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
8381 return dispatch_level
;
8385 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
8387 #pragma unused(arg1, arg2, oidp)
8391 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
8396 #endif /* CONFIG_EMBEDDED */
8397 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
8399 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
8402 #if DEBUG || DEVELOPMENT
8404 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
8405 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
8407 #else /* DEBUG || DEVELOPMENT */
8409 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
| CTLFLAG_RD
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
8410 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
8412 #endif /* DEBUG || DEVELOPMENT */
8416 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
8418 #pragma unused(arg1, arg2)
8422 int pressure_level
= 0;
8423 int trigger_request
= 0;
8426 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
8427 if (error
|| !req
->newptr
) {
8431 memorystatus_manual_testing_on
= TRUE
;
8433 trigger_request
= (level
>> 16) & 0xFFFF;
8434 pressure_level
= (level
& 0xFFFF);
8436 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
8437 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
8440 switch (pressure_level
) {
8441 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
8442 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
8443 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
8450 * The pressure level is being set from user-space.
8451 * And user-space uses the constants in sys/event.h
8452 * So we translate those events to our internal levels here.
8454 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
8455 memorystatus_manual_testing_level
= kVMPressureNormal
;
8457 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
8458 memorystatus_manual_testing_level
= kVMPressureWarning
;
8459 force_purge
= vm_pageout_state
.memorystatus_purge_on_warning
;
8460 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
8461 memorystatus_manual_testing_level
= kVMPressureCritical
;
8462 force_purge
= vm_pageout_state
.memorystatus_purge_on_critical
;
8465 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
8467 /* purge according to the new pressure level */
8468 switch (trigger_request
) {
8469 case TEST_PURGEABLE_TRIGGER_ONE
:
8470 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
8471 if (force_purge
== 0) {
8472 /* no purging requested */
8475 vm_purgeable_object_purge_one_unlocked(force_purge
);
8477 case TEST_PURGEABLE_TRIGGER_ALL
:
8478 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
8479 if (force_purge
== 0) {
8480 /* no purging requested */
8483 while (vm_purgeable_object_purge_one_unlocked(force_purge
)) {
8489 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
8490 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
8491 memorystatus_update_vm_pressure(TRUE
);
8494 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
8495 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
8496 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
8501 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
8502 memorystatus_manual_testing_on
= FALSE
;
8508 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
8509 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
8512 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &vm_pageout_state
.memorystatus_purge_on_warning
, 0, "");
8513 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &vm_pageout_state
.memorystatus_purge_on_urgent
, 0, "");
8514 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &vm_pageout_state
.memorystatus_purge_on_critical
, 0, "");
8516 #if DEBUG || DEVELOPMENT
8517 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_vm_pressure_events_enabled
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &vm_pressure_events_enabled
, 0, "");
8520 #endif /* VM_PRESSURE_EVENTS */
8522 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
8524 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
8526 uint32_t list_count
, i
= 0;
8527 memorystatus_priority_entry_t
*list_entry
;
8530 list_count
= memorystatus_list_count
;
8531 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
8533 /* Just a size check? */
8538 /* Otherwise, validate the size of the buffer */
8539 if (*buffer_size
< *list_size
) {
8543 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
8548 memset(*list_ptr
, 0, *list_size
);
8550 *buffer_size
= *list_size
;
8553 list_entry
= *list_ptr
;
8557 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
8558 while (p
&& (*list_size
< *buffer_size
)) {
8559 list_entry
->pid
= p
->p_pid
;
8560 list_entry
->priority
= p
->p_memstat_effectivepriority
;
8561 list_entry
->user_data
= p
->p_memstat_userdata
;
8563 if (p
->p_memstat_memlimit
<= 0) {
8564 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
8566 list_entry
->limit
= p
->p_memstat_memlimit
;
8569 list_entry
->state
= memorystatus_build_state(p
);
8572 *list_size
+= sizeof(memorystatus_priority_entry_t
);
8574 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
8579 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
8585 memorystatus_get_priority_pid(pid_t pid
, user_addr_t buffer
, size_t buffer_size
)
8588 memorystatus_priority_entry_t mp_entry
;
8590 /* Validate inputs */
8591 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_entry_t
))) {
8595 proc_t p
= proc_find(pid
);
8600 memset(&mp_entry
, 0, sizeof(memorystatus_priority_entry_t
));
8602 mp_entry
.pid
= p
->p_pid
;
8603 mp_entry
.priority
= p
->p_memstat_effectivepriority
;
8604 mp_entry
.user_data
= p
->p_memstat_userdata
;
8605 if (p
->p_memstat_memlimit
<= 0) {
8606 task_get_phys_footprint_limit(p
->task
, &mp_entry
.limit
);
8608 mp_entry
.limit
= p
->p_memstat_memlimit
;
8610 mp_entry
.state
= memorystatus_build_state(p
);
8614 error
= copyout(&mp_entry
, buffer
, buffer_size
);
8620 memorystatus_cmd_get_priority_list(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
)
8623 boolean_t size_only
;
8627 * When a non-zero pid is provided, the 'list' has only one entry.
8630 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
8633 list_size
= sizeof(memorystatus_priority_entry_t
) * 1;
8635 error
= memorystatus_get_priority_pid(pid
, buffer
, buffer_size
);
8638 memorystatus_priority_entry_t
*list
= NULL
;
8639 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
8643 error
= copyout(list
, buffer
, list_size
);
8648 kfree(list
, buffer_size
);
8653 *retval
= list_size
;
8660 memorystatus_clear_errors(void)
8665 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
8669 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
8671 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
8672 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
8674 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
8679 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
8684 memorystatus_update_levels_locked(boolean_t critical_only
)
8686 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
8689 * If there's an entry in the first bucket, we have idle processes.
8692 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
8693 if (first_bucket
->count
) {
8694 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
8696 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
8698 * The critical threshold must never exceed the pressure threshold
8700 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
8704 #if DEBUG || DEVELOPMENT
8705 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
8706 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
8708 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
8710 * The critical threshold must never exceed the pressure threshold
8712 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
8715 #endif /* DEBUG || DEVELOPMENT */
8717 if (memorystatus_jetsam_policy
& kPolicyMoreFree
) {
8718 memorystatus_available_pages_critical
+= memorystatus_policy_more_free_offset_pages
;
8721 if (critical_only
) {
8725 #if VM_PRESSURE_EVENTS
8726 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
8727 #if DEBUG || DEVELOPMENT
8728 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
8729 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
8736 memorystatus_fast_jetsam_override(boolean_t enable_override
)
8738 /* If fast jetsam is not enabled, simply return */
8739 if (!fast_jetsam_enabled
) {
8743 if (enable_override
) {
8744 if ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == kPolicyMoreFree
) {
8748 memorystatus_jetsam_policy
|= kPolicyMoreFree
;
8749 memorystatus_thread_pool_max();
8750 memorystatus_update_levels_locked(TRUE
);
8753 if ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == 0) {
8757 memorystatus_jetsam_policy
&= ~kPolicyMoreFree
;
8758 memorystatus_thread_pool_default();
8759 memorystatus_update_levels_locked(TRUE
);
8766 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
8768 #pragma unused(arg1, arg2, oidp)
8769 int error
= 0, more_free
= 0;
8772 * TODO: Enable this privilege check?
8774 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
8779 error
= sysctl_handle_int(oidp
, &more_free
, 0, req
);
8780 if (error
|| !req
->newptr
) {
8785 memorystatus_fast_jetsam_override(true);
8787 memorystatus_fast_jetsam_override(false);
8792 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_policy_more_free
, CTLTYPE_INT
| CTLFLAG_WR
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
,
8793 0, 0, &sysctl_kern_memorystatus_policy_more_free
, "I", "");
8795 #endif /* CONFIG_JETSAM */
8798 * Get the at_boot snapshot
8801 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
)
8803 size_t input_size
= *snapshot_size
;
8806 * The at_boot snapshot has no entry list.
8808 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
8815 * Validate the size of the snapshot buffer
8817 if (input_size
< *snapshot_size
) {
8822 * Update the notification_time only
8824 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
8825 *snapshot
= &memorystatus_at_boot_snapshot
;
8827 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
8828 (long)input_size
, (long)*snapshot_size
, 0);
8833 * Get the previous fully populated snapshot
8836 memorystatus_get_jetsam_snapshot_copy(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
)
8838 size_t input_size
= *snapshot_size
;
8840 if (memorystatus_jetsam_snapshot_copy_count
> 0) {
8841 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_copy_count
));
8850 if (input_size
< *snapshot_size
) {
8854 *snapshot
= memorystatus_jetsam_snapshot_copy
;
8856 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot_copy: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
8857 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_copy_count
);
8863 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
)
8865 size_t input_size
= *snapshot_size
;
8866 uint32_t ods_list_count
= memorystatus_list_count
;
8867 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
8869 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
8876 * Validate the size of the snapshot buffer.
8877 * This is inherently racey. May want to revisit
8878 * this error condition and trim the output when
8881 if (input_size
< *snapshot_size
) {
8886 * Allocate and initialize a snapshot buffer.
8888 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
8893 memset(ods
, 0, *snapshot_size
);
8896 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
8900 * Return the kernel allocated, on_demand buffer.
8901 * The caller of this routine will copy the data out
8902 * to user space and then free the kernel allocated
8907 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
8908 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
8914 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
)
8916 size_t input_size
= *snapshot_size
;
8918 if (memorystatus_jetsam_snapshot_count
> 0) {
8919 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
8928 if (input_size
< *snapshot_size
) {
8932 *snapshot
= memorystatus_jetsam_snapshot
;
8934 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
8935 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
8942 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
)
8945 boolean_t size_only
;
8946 boolean_t is_default_snapshot
= FALSE
;
8947 boolean_t is_on_demand_snapshot
= FALSE
;
8948 boolean_t is_at_boot_snapshot
= FALSE
;
8949 memorystatus_jetsam_snapshot_t
*snapshot
;
8951 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
8955 is_default_snapshot
= TRUE
;
8956 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
8958 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
| MEMORYSTATUS_SNAPSHOT_COPY
)) {
8960 * Unsupported bit set in flag.
8965 if (flags
& (flags
- 0x1)) {
8967 * Can't have multiple flags set at the same time.
8972 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
8973 is_on_demand_snapshot
= TRUE
;
8975 * When not requesting the size only, the following call will allocate
8976 * an on_demand snapshot buffer, which is freed below.
8978 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
8979 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
8980 is_at_boot_snapshot
= TRUE
;
8981 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
8982 } else if (flags
& MEMORYSTATUS_SNAPSHOT_COPY
) {
8983 error
= memorystatus_get_jetsam_snapshot_copy(&snapshot
, &buffer_size
, size_only
);
8986 * Invalid flag setting.
8997 * Copy the data out to user space and clear the snapshot buffer.
8998 * If working with the jetsam snapshot,
8999 * clearing the buffer means, reset the count.
9000 * If working with an on_demand snapshot
9001 * clearing the buffer means, free it.
9002 * If working with the at_boot snapshot
9003 * there is nothing to clear or update.
9004 * If working with a copy of the snapshot
9005 * there is nothing to clear or update.
9008 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
9009 if (is_default_snapshot
) {
9011 * The jetsam snapshot is never freed, its count is simply reset.
9012 * However, we make a copy for any parties that might be interested
9013 * in the previous fully populated snapshot.
9016 memcpy(memorystatus_jetsam_snapshot_copy
, memorystatus_jetsam_snapshot
, memorystatus_jetsam_snapshot_size
);
9017 memorystatus_jetsam_snapshot_copy_count
= memorystatus_jetsam_snapshot_count
;
9018 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
9019 memorystatus_jetsam_snapshot_last_timestamp
= 0;
9024 if (is_on_demand_snapshot
) {
9026 * The on_demand snapshot is always freed,
9027 * even if the copyout failed.
9030 kfree(snapshot
, buffer_size
);
9036 *retval
= buffer_size
;
9043 * Routine: memorystatus_cmd_grp_set_priorities
9044 * Purpose: Update priorities for a group of processes.
9047 * Move each process out of its effective priority
9048 * band and into a new priority band.
9049 * Maintains relative order from lowest to highest priority.
9050 * In single band, maintains relative order from head to tail.
9052 * eg: before [effectivepriority | pid]
9054 * [17 | p55, p67, p19 ]
9059 * after [ new band | pid]
9060 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
9062 * Returns: 0 on success, else non-zero.
9064 * Caveat: We know there is a race window regarding recycled pids.
9065 * A process could be killed before the kernel can act on it here.
9066 * If a pid cannot be found in any of the jetsam priority bands,
9067 * then we simply ignore it. No harm.
9068 * But, if the pid has been recycled then it could be an issue.
9069 * In that scenario, we might move an unsuspecting process to the new
9070 * priority band. It's not clear how the kernel can safeguard
9071 * against this, but it would be an extremely rare case anyway.
9072 * The caller of this api might avoid such race conditions by
9073 * ensuring that the processes passed in the pid list are suspended.
9078 memorystatus_cmd_grp_set_priorities(user_addr_t buffer
, size_t buffer_size
)
9081 * We only handle setting priority
9086 memorystatus_properties_entry_v1_t
*entries
= NULL
;
9087 uint32_t entry_count
= 0;
9089 /* This will be the ordered proc list */
9090 typedef struct memorystatus_internal_properties
{
9093 } memorystatus_internal_properties_t
;
9095 memorystatus_internal_properties_t
*table
= NULL
;
9096 size_t table_size
= 0;
9097 uint32_t table_count
= 0;
9100 uint32_t bucket_index
= 0;
9101 boolean_t head_insert
;
9102 int32_t new_priority
;
9107 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0)) {
9112 entry_count
= (buffer_size
/ sizeof(memorystatus_properties_entry_v1_t
));
9113 if ((entries
= (memorystatus_properties_entry_v1_t
*)kalloc(buffer_size
)) == NULL
) {
9118 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);
9120 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
9124 /* Verify sanity of input priorities */
9125 if (entries
[0].version
== MEMORYSTATUS_MPE_VERSION_1
) {
9126 if ((buffer_size
% MEMORYSTATUS_MPE_VERSION_1_SIZE
) != 0) {
9135 for (i
= 0; i
< entry_count
; i
++) {
9136 if (entries
[i
].priority
== -1) {
9137 /* Use as shorthand for default priority */
9138 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
9139 } else if ((entries
[i
].priority
== system_procs_aging_band
) || (entries
[i
].priority
== applications_aging_band
)) {
9140 /* Both the aging bands are reserved for internal use;
9141 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
9142 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
9143 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
9144 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
9146 /* Deal with this later */
9147 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
9154 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
9155 if ((table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
9159 memset(table
, 0, table_size
);
9163 * For each jetsam bucket entry, spin through the input property list.
9164 * When a matching pid is found, populate an adjacent table with the
9165 * appropriate proc pointer and new property values.
9166 * This traversal automatically preserves order from lowest
9167 * to highest priority.
9174 /* Create the ordered table */
9175 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
9176 while (p
&& (table_count
< entry_count
)) {
9177 for (i
= 0; i
< entry_count
; i
++) {
9178 if (p
->p_pid
== entries
[i
].pid
) {
9179 /* Build the table data */
9180 table
[table_count
].proc
= p
;
9181 table
[table_count
].priority
= entries
[i
].priority
;
9186 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
9189 /* We now have ordered list of procs ready to move */
9190 for (i
= 0; i
< table_count
; i
++) {
9194 /* Allow head inserts -- but relative order is now */
9195 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
9196 new_priority
= JETSAM_PRIORITY_IDLE
;
9199 new_priority
= table
[i
].priority
;
9200 head_insert
= false;
9204 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
9209 * Take appropriate steps if moving proc out of
9210 * either of the aging bands.
9212 if ((p
->p_memstat_effectivepriority
== system_procs_aging_band
) || (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
9213 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
9216 memorystatus_update_priority_locked(p
, new_priority
, head_insert
, false);
9222 * if (table_count != entry_count)
9223 * then some pids were not found in a jetsam band.
9224 * harmless but interesting...
9227 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);
9230 kfree(entries
, buffer_size
);
9233 kfree(table
, table_size
);
9240 memorystatus_cmd_grp_set_probabilities(user_addr_t buffer
, size_t buffer_size
)
9243 memorystatus_properties_entry_v1_t
*entries
= NULL
;
9244 uint32_t entry_count
= 0, i
= 0;
9245 memorystatus_internal_probabilities_t
*tmp_table_new
= NULL
, *tmp_table_old
= NULL
;
9246 size_t tmp_table_new_size
= 0, tmp_table_old_size
= 0;
9249 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0)) {
9254 entry_count
= (buffer_size
/ sizeof(memorystatus_properties_entry_v1_t
));
9256 if ((entries
= (memorystatus_properties_entry_v1_t
*) kalloc(buffer_size
)) == NULL
) {
9261 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);
9263 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
9267 if (entries
[0].version
== MEMORYSTATUS_MPE_VERSION_1
) {
9268 if ((buffer_size
% MEMORYSTATUS_MPE_VERSION_1_SIZE
) != 0) {
9277 /* Verify sanity of input priorities */
9278 for (i
= 0; i
< entry_count
; i
++) {
9280 * 0 - low probability of use.
9281 * 1 - high probability of use.
9283 * Keeping this field an int (& not a bool) to allow
9284 * us to experiment with different values/approaches
9287 if (entries
[i
].use_probability
> 1) {
9293 tmp_table_new_size
= sizeof(memorystatus_internal_probabilities_t
) * entry_count
;
9295 if ((tmp_table_new
= (memorystatus_internal_probabilities_t
*) kalloc(tmp_table_new_size
)) == NULL
) {
9299 memset(tmp_table_new
, 0, tmp_table_new_size
);
9303 if (memorystatus_global_probabilities_table
) {
9304 tmp_table_old
= memorystatus_global_probabilities_table
;
9305 tmp_table_old_size
= memorystatus_global_probabilities_size
;
9308 memorystatus_global_probabilities_table
= tmp_table_new
;
9309 memorystatus_global_probabilities_size
= tmp_table_new_size
;
9310 tmp_table_new
= NULL
;
9312 for (i
= 0; i
< entry_count
; i
++) {
9313 /* Build the table data */
9314 strlcpy(memorystatus_global_probabilities_table
[i
].proc_name
, entries
[i
].proc_name
, MAXCOMLEN
+ 1);
9315 memorystatus_global_probabilities_table
[i
].use_probability
= entries
[i
].use_probability
;
9321 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);
9324 kfree(entries
, buffer_size
);
9328 if (tmp_table_old
) {
9329 kfree(tmp_table_old
, tmp_table_old_size
);
9330 tmp_table_old
= NULL
;
9337 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
)
9341 if ((flags
& MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY
) == MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY
) {
9342 error
= memorystatus_cmd_grp_set_priorities(buffer
, buffer_size
);
9343 } else if ((flags
& MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY
) == MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY
) {
9344 error
= memorystatus_cmd_grp_set_probabilities(buffer
, buffer_size
);
9353 * This routine is used to update a process's jetsam priority position and stored user_data.
9354 * It is not used for the setting of memory limits, which is why the last 6 args to the
9355 * memorystatus_update() call are 0 or FALSE.
9359 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
)
9362 memorystatus_priority_properties_t mpp_entry
;
9364 /* Validate inputs */
9365 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
9369 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
9379 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
9384 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
);
9392 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
)
9395 memorystatus_memlimit_properties_t mmp_entry
;
9397 /* Validate inputs */
9398 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
9402 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
9405 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
9412 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
9413 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
9414 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
9415 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
9416 * to the task's ledgers via task_set_phys_footprint_limit().
9419 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
)
9422 memorystatus_memlimit_properties_t mmp_entry
;
9424 /* Validate inputs */
9425 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
9429 memset(&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
9431 proc_t p
= proc_find(pid
);
9437 * Get the active limit and attributes.
9438 * No locks taken since we hold a reference to the proc.
9441 if (p
->p_memstat_memlimit_active
> 0) {
9442 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
9444 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
9447 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
9448 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
9452 * Get the inactive limit and attributes
9454 if (p
->p_memstat_memlimit_inactive
<= 0) {
9455 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
9457 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
9459 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
9460 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
9464 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
9471 * SPI for kbd - pr24956468
9472 * This is a very simple snapshot that calculates how much a
9473 * process's phys_footprint exceeds a specific memory limit.
9474 * Only the inactive memory limit is supported for now.
9475 * The delta is returned as bytes in excess or zero.
9478 memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
)
9481 uint64_t footprint_in_bytes
= 0;
9482 uint64_t delta_in_bytes
= 0;
9483 int32_t memlimit_mb
= 0;
9484 uint64_t memlimit_bytes
= 0;
9486 /* Validate inputs */
9487 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(uint64_t)) || (flags
!= 0)) {
9491 proc_t p
= proc_find(pid
);
9497 * Get the inactive limit.
9498 * No locks taken since we hold a reference to the proc.
9501 if (p
->p_memstat_memlimit_inactive
<= 0) {
9502 task_convert_phys_footprint_limit(-1, &memlimit_mb
);
9504 memlimit_mb
= p
->p_memstat_memlimit_inactive
;
9507 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
9511 memlimit_bytes
= memlimit_mb
* 1024 * 1024; /* MB to bytes */
9514 * Computed delta always returns >= 0 bytes
9516 if (footprint_in_bytes
> memlimit_bytes
) {
9517 delta_in_bytes
= footprint_in_bytes
- memlimit_bytes
;
9520 error
= copyout(&delta_in_bytes
, buffer
, sizeof(delta_in_bytes
));
9527 memorystatus_cmd_get_pressure_status(int32_t *retval
)
9531 /* Need privilege for check */
9532 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
9537 /* Inherently racy, so it's not worth taking a lock here */
9538 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
9544 memorystatus_get_pressure_status_kdp()
9546 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
9550 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
9552 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
9553 * So, with 2-level HWM preserving previous behavior will map as follows.
9554 * - treat the limit passed in as both an active and inactive limit.
9555 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
9557 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
9558 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
9559 * - so mapping is (active/non-fatal, inactive/non-fatal)
9561 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
9562 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
9563 * - so mapping is (active/fatal, inactive/fatal)
9568 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
)
9571 memorystatus_memlimit_properties_t entry
;
9573 entry
.memlimit_active
= high_water_mark
;
9574 entry
.memlimit_active_attr
= 0;
9575 entry
.memlimit_inactive
= high_water_mark
;
9576 entry
.memlimit_inactive_attr
= 0;
9578 if (is_fatal_limit
== TRUE
) {
9579 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
9580 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
9583 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
9586 #endif /* CONFIG_JETSAM */
9589 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
)
9591 int32_t memlimit_active
;
9592 boolean_t memlimit_active_is_fatal
;
9593 int32_t memlimit_inactive
;
9594 boolean_t memlimit_inactive_is_fatal
;
9595 uint32_t valid_attrs
= 0;
9598 proc_t p
= proc_find(pid
);
9604 * Check for valid attribute flags.
9606 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
9607 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
9611 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
9617 * Setup the active memlimit properties
9619 memlimit_active
= entry
->memlimit_active
;
9620 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
9621 memlimit_active_is_fatal
= TRUE
;
9623 memlimit_active_is_fatal
= FALSE
;
9627 * Setup the inactive memlimit properties
9629 memlimit_inactive
= entry
->memlimit_inactive
;
9630 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
9631 memlimit_inactive_is_fatal
= TRUE
;
9633 memlimit_inactive_is_fatal
= FALSE
;
9637 * Setting a limit of <= 0 implies that the process has no
9638 * high-water-mark and has no per-task-limit. That means
9639 * the system_wide task limit is in place, which by the way,
9643 if (memlimit_active
<= 0) {
9645 * Enforce the fatal system_wide task limit while process is active.
9647 memlimit_active
= -1;
9648 memlimit_active_is_fatal
= TRUE
;
9651 if (memlimit_inactive
<= 0) {
9653 * Enforce the fatal system_wide task limit while process is inactive.
9655 memlimit_inactive
= -1;
9656 memlimit_inactive_is_fatal
= TRUE
;
9662 * Store the active limit variants in the proc.
9664 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
9667 * Store the inactive limit variants in the proc.
9669 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
9672 * Enforce appropriate limit variant by updating the cached values
9673 * and writing the ledger.
9674 * Limit choice is based on process active/inactive state.
9677 if (memorystatus_highwater_enabled
) {
9679 boolean_t use_active
;
9681 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
9682 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
9685 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
9689 /* Enforce the limit by writing to the ledgers */
9690 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
;
9692 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
9693 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
9694 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
9695 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
9696 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit
, proc_t
, p
, int32_t, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1));
9706 * Returns the jetsam priority (effective or requested) of the process
9707 * associated with this task.
9710 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
9713 if (effective_priority
) {
9714 return p
->p_memstat_effectivepriority
;
9716 return p
->p_memstat_requestedpriority
;
9723 memorystatus_get_process_is_managed(pid_t pid
, int *is_managed
)
9727 /* Validate inputs */
9738 *is_managed
= ((p
->p_memstat_state
& P_MEMSTAT_MANAGED
) ? 1 : 0);
9739 proc_rele_locked(p
);
9746 memorystatus_set_process_is_managed(pid_t pid
, boolean_t set_managed
)
9750 /* Validate inputs */
9761 if (set_managed
== TRUE
) {
9762 p
->p_memstat_state
|= P_MEMSTAT_MANAGED
;
9764 p
->p_memstat_state
&= ~P_MEMSTAT_MANAGED
;
9766 proc_rele_locked(p
);
9773 memorystatus_get_process_is_freezable(pid_t pid
, int *is_freezable
)
9775 proc_t p
= PROC_NULL
;
9787 * Only allow this on the current proc for now.
9788 * We can check for privileges and allow targeting another process in the future.
9790 if (p
!= current_proc()) {
9796 *is_freezable
= ((p
->p_memstat_state
& P_MEMSTAT_FREEZE_DISABLED
) ? 0 : 1);
9797 proc_rele_locked(p
);
9804 memorystatus_set_process_is_freezable(pid_t pid
, boolean_t is_freezable
)
9806 proc_t p
= PROC_NULL
;
9818 * Only allow this on the current proc for now.
9819 * We can check for privileges and allow targeting another process in the future.
9821 if (p
!= current_proc()) {
9827 if (is_freezable
== FALSE
) {
9828 /* Freeze preference set to FALSE. Set the P_MEMSTAT_FREEZE_DISABLED bit. */
9829 p
->p_memstat_state
|= P_MEMSTAT_FREEZE_DISABLED
;
9830 printf("memorystatus_set_process_is_freezable: disabling freeze for pid %d [%s]\n",
9831 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"));
9833 p
->p_memstat_state
&= ~P_MEMSTAT_FREEZE_DISABLED
;
9834 printf("memorystatus_set_process_is_freezable: enabling freeze for pid %d [%s]\n",
9835 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"));
9837 proc_rele_locked(p
);
9844 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
)
9847 boolean_t skip_auth_check
= FALSE
;
9848 os_reason_t jetsam_reason
= OS_REASON_NULL
;
9852 #pragma unused(jetsam_reason)
9855 /* We don't need entitlements if we're setting/ querying the freeze preference for a process. Skip the check below. */
9856 if (args
->command
== MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE
|| args
->command
== MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE
) {
9857 skip_auth_check
= TRUE
;
9860 /* Need to be root or have entitlement. */
9861 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
) && !skip_auth_check
) {
9868 * Do not enforce it for snapshots.
9870 if (args
->command
!= MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
) {
9871 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
9877 switch (args
->command
) {
9878 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
9879 error
= memorystatus_cmd_get_priority_list(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
9881 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
9882 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
9884 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
9885 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
9887 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
9888 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
9890 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS
:
9891 error
= memorystatus_cmd_get_memlimit_excess_np(args
->pid
, args
->flags
, args
->buffer
, args
->buffersize
, ret
);
9893 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
9894 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
9896 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
9897 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
9899 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
9900 error
= memorystatus_cmd_get_pressure_status(ret
);
9903 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
9905 * This call does not distinguish between active and inactive limits.
9906 * Default behavior in 2-level HWM world is to set both.
9907 * Non-fatal limit is also assumed for both.
9909 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
9911 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
9913 * This call does not distinguish between active and inactive limits.
9914 * Default behavior in 2-level HWM world is to set both.
9915 * Fatal limit is also assumed for both.
9917 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
9919 #endif /* CONFIG_JETSAM */
9921 #if DEVELOPMENT || DEBUG
9922 case MEMORYSTATUS_CMD_TEST_JETSAM
:
9923 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_GENERIC
);
9924 if (jetsam_reason
== OS_REASON_NULL
) {
9925 printf("memorystatus_control: failed to allocate jetsam reason\n");
9928 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
, jetsam_reason
) ? 0 : EINVAL
;
9930 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
9931 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
9934 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
9935 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
9937 #endif /* CONFIG_JETSAM */
9938 #else /* DEVELOPMENT || DEBUG */
9939 #pragma unused(jetsam_reason)
9940 #endif /* DEVELOPMENT || DEBUG */
9941 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE
:
9942 if (memorystatus_aggressive_jetsam_lenient_allowed
== FALSE
) {
9943 #if DEVELOPMENT || DEBUG
9944 printf("Enabling Lenient Mode\n");
9945 #endif /* DEVELOPMENT || DEBUG */
9947 memorystatus_aggressive_jetsam_lenient_allowed
= TRUE
;
9948 memorystatus_aggressive_jetsam_lenient
= TRUE
;
9952 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE
:
9953 #if DEVELOPMENT || DEBUG
9954 printf("Disabling Lenient mode\n");
9955 #endif /* DEVELOPMENT || DEBUG */
9956 memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
9957 memorystatus_aggressive_jetsam_lenient
= FALSE
;
9960 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
9961 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
9962 error
= memorystatus_low_mem_privileged_listener(args
->command
);
9965 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
:
9966 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
:
9967 error
= memorystatus_update_inactive_jetsam_priority_band(args
->pid
, args
->command
, JETSAM_PRIORITY_ELEVATED_INACTIVE
, args
->flags
? TRUE
: FALSE
);
9969 case MEMORYSTATUS_CMD_SET_PROCESS_IS_MANAGED
:
9970 error
= memorystatus_set_process_is_managed(args
->pid
, args
->flags
);
9973 case MEMORYSTATUS_CMD_GET_PROCESS_IS_MANAGED
:
9974 error
= memorystatus_get_process_is_managed(args
->pid
, ret
);
9977 case MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE
:
9978 error
= memorystatus_set_process_is_freezable(args
->pid
, args
->flags
? TRUE
: FALSE
);
9981 case MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE
:
9982 error
= memorystatus_get_process_is_freezable(args
->pid
, ret
);
9986 #if DEVELOPMENT || DEBUG
9987 case MEMORYSTATUS_CMD_FREEZER_CONTROL
:
9988 error
= memorystatus_freezer_control(args
->flags
, args
->buffer
, args
->buffersize
, ret
);
9990 #endif /* DEVELOPMENT || DEBUG */
9991 #endif /* CONFIG_FREEZE */
10003 filt_memorystatusattach(struct knote
*kn
, __unused
struct kevent_internal_s
*kev
)
10007 kn
->kn_flags
|= EV_CLEAR
;
10008 error
= memorystatus_knote_register(kn
);
10010 kn
->kn_flags
= EV_ERROR
;
10011 kn
->kn_data
= error
;
10017 filt_memorystatusdetach(struct knote
*kn
)
10019 memorystatus_knote_unregister(kn
);
10023 filt_memorystatus(struct knote
*kn __unused
, long hint
)
10027 case kMemorystatusNoPressure
:
10028 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
10029 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
10032 case kMemorystatusPressure
:
10033 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
10034 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
10035 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
10037 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
10038 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
10039 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
10043 case kMemorystatusLowSwap
:
10044 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
10045 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
10049 case kMemorystatusProcLimitWarn
:
10050 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
10051 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
10055 case kMemorystatusProcLimitCritical
:
10056 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
10057 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
10067 if (kn
->kn_fflags
!= 0) {
10068 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
10069 pid_t knote_pid
= knote_proc
->p_pid
;
10071 printf("filt_memorystatus: sending kn 0x%lx (event 0x%x) for pid (%d)\n",
10072 (unsigned long)kn
, kn
->kn_fflags
, knote_pid
);
10076 return kn
->kn_fflags
!= 0;
10080 filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
10083 int prev_kn_sfflags
= 0;
10085 memorystatus_klist_lock();
10088 * copy in new kevent settings
10089 * (saving the "desired" data and fflags).
10092 prev_kn_sfflags
= kn
->kn_sfflags
;
10093 kn
->kn_sfflags
= (kev
->fflags
& EVFILT_MEMORYSTATUS_ALL_MASK
);
10095 #if !CONFIG_EMBEDDED
10097 * Only on desktop do we restrict notifications to
10098 * one per active/inactive state (soft limits only).
10100 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
10102 * Is there previous state to preserve?
10104 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
10106 * This knote was previously interested in proc_limit_warn,
10107 * so yes, preserve previous state.
10109 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
10110 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
10112 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
10113 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
10117 * This knote was not previously interested in proc_limit_warn,
10118 * but it is now. Set both states.
10120 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
10121 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
10125 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
10127 * Is there previous state to preserve?
10129 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
10131 * This knote was previously interested in proc_limit_critical,
10132 * so yes, preserve previous state.
10134 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
10135 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
10137 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
10138 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
10142 * This knote was not previously interested in proc_limit_critical,
10143 * but it is now. Set both states.
10145 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
10146 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
10149 #endif /* !CONFIG_EMBEDDED */
10152 * reset the output flags based on a
10153 * combination of the old events and
10154 * the new desired event list.
10156 //kn->kn_fflags &= kn->kn_sfflags;
10158 res
= (kn
->kn_fflags
!= 0);
10160 memorystatus_klist_unlock();
10166 filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
10168 #pragma unused(data)
10171 memorystatus_klist_lock();
10172 res
= (kn
->kn_fflags
!= 0);
10174 *kev
= kn
->kn_kevent
;
10175 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
10179 memorystatus_klist_unlock();
10185 memorystatus_klist_lock(void)
10187 lck_mtx_lock(&memorystatus_klist_mutex
);
10191 memorystatus_klist_unlock(void)
10193 lck_mtx_unlock(&memorystatus_klist_mutex
);
10197 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
)
10199 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
10200 klist_init(&memorystatus_klist
);
10204 memorystatus_knote_register(struct knote
*kn
)
10208 memorystatus_klist_lock();
10211 * Support only userspace visible flags.
10213 if ((kn
->kn_sfflags
& EVFILT_MEMORYSTATUS_ALL_MASK
) == (unsigned int) kn
->kn_sfflags
) {
10214 #if !CONFIG_EMBEDDED
10215 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
10216 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
10217 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
10220 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
10221 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
10222 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
10224 #endif /* !CONFIG_EMBEDDED */
10226 KNOTE_ATTACH(&memorystatus_klist
, kn
);
10231 memorystatus_klist_unlock();
10237 memorystatus_knote_unregister(struct knote
*kn __unused
)
10239 memorystatus_klist_lock();
10240 KNOTE_DETACH(&memorystatus_klist
, kn
);
10241 memorystatus_klist_unlock();
10246 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
10248 memorystatus_issue_pressure_kevent(boolean_t pressured
)
10250 memorystatus_klist_lock();
10251 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
10252 memorystatus_klist_unlock();
10255 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
10258 /* Coalition support */
10260 /* sorting info for a particular priority bucket */
10261 typedef struct memstat_sort_info
{
10262 coalition_t msi_coal
;
10263 uint64_t msi_page_count
;
10266 } memstat_sort_info_t
;
10269 * qsort from smallest page count to largest page count
10271 * return < 0 for a < b
10276 memstat_asc_cmp(const void *a
, const void *b
)
10278 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
10279 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
10281 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
10285 * Return the number of pids rearranged during this sort.
10288 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
10290 #define MAX_SORT_PIDS 80
10291 #define MAX_COAL_LEADERS 10
10293 unsigned int b
= bucket_index
;
10297 coalition_t coal
= COALITION_NULL
;
10298 int pids_moved
= 0;
10299 int total_pids_moved
= 0;
10303 * The system is typically under memory pressure when in this
10304 * path, hence, we want to avoid dynamic memory allocation.
10306 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
10307 pid_t pid_list
[MAX_SORT_PIDS
];
10309 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
10314 * Clear the array that holds coalition leader information
10316 for (i
= 0; i
< MAX_COAL_LEADERS
; i
++) {
10317 leaders
[i
].msi_coal
= COALITION_NULL
;
10318 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
10319 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
10320 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
10323 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
10325 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
10326 if (nleaders
< MAX_COAL_LEADERS
) {
10327 int coal_ntasks
= 0;
10328 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
10329 leaders
[nleaders
].msi_coal
= coal
;
10330 leaders
[nleaders
].msi_page_count
= coal_page_count
;
10331 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
10332 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
10336 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
10337 * Abandoned coalitions will linger at the tail of the priority band
10338 * when this sort session ends.
10339 * TODO: should this be an assert?
10341 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
10342 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
10346 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
10349 if (nleaders
== 0) {
10350 /* Nothing to sort */
10355 * Sort the coalition leader array, from smallest coalition page count
10356 * to largest coalition page count. When inserted in the priority bucket,
10357 * smallest coalition is handled first, resulting in the last to be jetsammed.
10359 if (nleaders
> 1) {
10360 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
10364 for (i
= 0; i
< nleaders
; i
++) {
10365 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
10366 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
10367 leaders
[i
].msi_ntasks
);
10372 * During coalition sorting, processes in a priority band are rearranged
10373 * by being re-inserted at the head of the queue. So, when handling a
10374 * list, the first process that gets moved to the head of the queue,
10375 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
10377 * So, for example, the coalition leader is expected to jetsam last,
10378 * after its coalition members. Therefore, the coalition leader is
10379 * inserted at the head of the queue first.
10381 * After processing a coalition, the jetsam order is as follows:
10382 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
10386 * Coalition members are rearranged in the priority bucket here,
10387 * based on their coalition role.
10389 total_pids_moved
= 0;
10390 for (i
= 0; i
< nleaders
; i
++) {
10391 /* a bit of bookkeeping */
10394 /* Coalition leaders are jetsammed last, so move into place first */
10395 pid_list
[0] = leaders
[i
].msi_pid
;
10396 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
10398 /* xpc services should jetsam after extensions */
10399 ntasks
= coalition_get_pid_list(leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
10400 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
10403 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
10404 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
10407 /* extensions should jetsam after unmarked processes */
10408 ntasks
= coalition_get_pid_list(leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
10409 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
10412 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
10413 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
10416 /* undefined coalition members should be the first to jetsam */
10417 ntasks
= coalition_get_pid_list(leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
10418 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
10421 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
10422 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
10426 if (pids_moved
== leaders
[i
].msi_ntasks
) {
10428 * All the pids in the coalition were found in this band.
10430 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
10431 pids_moved
, leaders
[i
].msi_ntasks
);
10432 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
10434 * Apparently new coalition members showed up during the sort?
10436 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
10437 pids_moved
, leaders
[i
].msi_ntasks
);
10440 * Apparently not all the pids in the coalition were found in this band?
10442 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
10443 pids_moved
, leaders
[i
].msi_ntasks
);
10447 total_pids_moved
+= pids_moved
;
10450 return total_pids_moved
;
10455 * Traverse a list of pids, searching for each within the priority band provided.
10456 * If pid is found, move it to the front of the priority band.
10457 * Never searches outside the priority band provided.
10460 * bucket_index - jetsam priority band.
10461 * pid_list - pointer to a list of pids.
10462 * list_sz - number of pids in the list.
10464 * Pid list ordering is important in that,
10465 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
10466 * The sort_order is set by the coalition default.
10469 * the number of pids found and hence moved within the priority band.
10472 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
10474 memstat_bucket_t
*current_bucket
;
10476 int found_pids
= 0;
10478 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
10482 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
10486 current_bucket
= &memstat_bucket
[bucket_index
];
10487 for (i
= 0; i
< list_sz
; i
++) {
10488 unsigned int b
= bucket_index
;
10490 proc_t aProc
= NULL
;
10494 list_index
= ((list_sz
- 1) - i
);
10495 aPid
= pid_list
[list_index
];
10497 /* never search beyond bucket_index provided */
10498 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
10500 if (p
->p_pid
== aPid
) {
10504 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
10507 if (aProc
== NULL
) {
10508 /* pid not found in this band, just skip it */
10511 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
10512 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
10520 memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index
)
10522 int32_t i
= JETSAM_PRIORITY_IDLE
;
10525 if (max_bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
10529 while (i
<= max_bucket_index
) {
10530 count
+= memstat_bucket
[i
++].count
;
10537 memorystatus_update_priority_for_appnap(proc_t p
, boolean_t is_appnap
)
10540 if (!p
|| (!isApp(p
)) || (p
->p_memstat_state
& (P_MEMSTAT_INTERNAL
| P_MEMSTAT_MANAGED
))) {
10542 * Ineligible processes OR system processes e.g. launchd.
10544 * We also skip processes that have the P_MEMSTAT_MANAGED bit set, i.e.
10545 * they're managed by assertiond. These are iOS apps that have been ported
10546 * to macOS. assertiond might be in the process of modifying the app's
10547 * priority / memory limit - so it might have the proc_list lock, and then try
10548 * to take the task lock. Meanwhile we've entered this function with the task lock
10549 * held, and we need the proc_list lock below. So we'll deadlock with assertiond.
10551 * It should be fine to read the P_MEMSTAT_MANAGED bit without the proc_list
10552 * lock here, since assertiond only sets this bit on process launch.
10559 * We would like to use memorystatus_update() here to move the processes
10560 * within the bands. Unfortunately memorystatus_update() calls
10561 * memorystatus_update_priority_locked() which uses any band transitions
10562 * as an indication to modify ledgers. For that it needs the task lock
10563 * and since we came into this function with the task lock held, we'll deadlock.
10565 * Unfortunately we can't completely disable ledger updates because we still
10566 * need the ledger updates for a subset of processes i.e. daemons.
10567 * When all processes on all platforms support memory limits, we can simply call
10568 * memorystatus_update().
10570 * It also has some logic to deal with 'aging' which, currently, is only applicable
10571 * on CONFIG_JETSAM configs. So, till every platform has CONFIG_JETSAM we'll need
10572 * to do this explicit band transition.
10575 memstat_bucket_t
*current_bucket
, *new_bucket
;
10576 int32_t priority
= 0;
10580 if (((p
->p_listflag
& P_LIST_EXITED
) != 0) ||
10581 (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
))) {
10583 * If the process is on its way out OR
10584 * jetsam has alread tried and failed to kill this process,
10585 * let's skip the whole jetsam band transition.
10587 proc_list_unlock();
10592 current_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
10593 new_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
10594 priority
= JETSAM_PRIORITY_IDLE
;
10596 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
10598 * It is possible that someone pulled this process
10599 * out of the IDLE band without updating its app-nap
10602 proc_list_unlock();
10606 current_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
10607 new_bucket
= &memstat_bucket
[p
->p_memstat_requestedpriority
];
10608 priority
= p
->p_memstat_requestedpriority
;
10611 TAILQ_REMOVE(¤t_bucket
->list
, p
, p_memstat_list
);
10612 current_bucket
->count
--;
10614 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
10615 new_bucket
->count
++;
10618 * Record idle start or idle delta.
10620 if (p
->p_memstat_effectivepriority
== priority
) {
10622 * This process is not transitioning between
10623 * jetsam priority buckets. Do nothing.
10625 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
10628 * Transitioning out of the idle priority bucket.
10629 * Record idle delta.
10631 assert(p
->p_memstat_idle_start
!= 0);
10632 now
= mach_absolute_time();
10633 if (now
> p
->p_memstat_idle_start
) {
10634 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
10636 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
10638 * Transitioning into the idle priority bucket.
10639 * Record idle start.
10641 p
->p_memstat_idle_start
= mach_absolute_time();
10644 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CHANGE_PRIORITY
), p
->p_pid
, priority
, p
->p_memstat_effectivepriority
, 0, 0);
10646 p
->p_memstat_effectivepriority
= priority
;
10648 proc_list_unlock();
10652 #else /* !CONFIG_JETSAM */
10654 #pragma unused(is_appnap)
10656 #endif /* !CONFIG_JETSAM */