2 * Copyright (c) 2006 Apple Computer, 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>
40 #include <IOKit/IOBSD.h>
42 #include <libkern/libkern.h>
43 #include <mach/coalition.h>
44 #include <mach/mach_time.h>
45 #include <mach/task.h>
46 #include <mach/host_priv.h>
47 #include <mach/mach_host.h>
48 #include <pexpert/pexpert.h>
49 #include <sys/coalition.h>
50 #include <sys/kern_event.h>
52 #include <sys/proc_info.h>
53 #include <sys/reason.h>
54 #include <sys/signal.h>
55 #include <sys/signalvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
61 #include <vm/vm_pageout.h>
62 #include <vm/vm_protos.h>
65 #include <vm/vm_map.h>
66 #endif /* CONFIG_FREEZE */
68 #include <sys/kern_memorystatus.h>
70 #include <mach/machine/sdt.h>
72 /* For logging clarity */
73 static const char *jetsam_kill_cause_name
[] = {
75 "jettisoned" , /* kMemorystatusKilled */
76 "highwater" , /* kMemorystatusKilledHiwat */
77 "vnode-limit" , /* kMemorystatusKilledVnodes */
78 "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
79 "vm-thrashing" , /* kMemorystatusKilledVMThrashing */
80 "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
81 "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
82 "diagnostic" , /* kMemorystatusKilledDiagnostic */
83 "idle-exit" , /* kMemorystatusKilledIdleExit */
87 /* Does cause indicate vm or fc thrashing? */
89 is_thrashing(unsigned cause
)
92 case kMemorystatusKilledVMThrashing
:
93 case kMemorystatusKilledFCThrashing
:
100 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
101 extern void vm_thrashing_jetsam_done(void);
102 #endif /* CONFIG_JETSAM */
104 /* These are very verbose printfs(), enable with
105 * MEMORYSTATUS_DEBUG_LOG
107 #if MEMORYSTATUS_DEBUG_LOG
108 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
110 if (cond) { printf(format, ##__VA_ARGS__); } \
113 #define MEMORYSTATUS_DEBUG(cond, format, ...)
117 * Active / Inactive limit support
118 * proc list must be locked
120 * The SET_*** macros are used to initialize a limit
121 * for the first time.
123 * The CACHE_*** macros are use to cache the limit that will
124 * soon be in effect down in the ledgers.
127 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
129 (p)->p_memstat_memlimit_active = (limit); \
131 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
133 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
137 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
139 (p)->p_memstat_memlimit_inactive = (limit); \
141 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
143 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
147 #define CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal) \
149 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
150 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
151 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
154 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
159 #define CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal) \
161 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
162 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
163 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
166 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
172 /* General tunables */
174 unsigned long delta_percentage
= 5;
175 unsigned long critical_threshold_percentage
= 5;
176 unsigned long idle_offset_percentage
= 5;
177 unsigned long pressure_threshold_percentage
= 15;
178 unsigned long freeze_threshold_percentage
= 50;
179 unsigned long policy_more_free_offset_percentage
= 5;
181 /* General memorystatus stuff */
183 struct klist memorystatus_klist
;
184 static lck_mtx_t memorystatus_klist_mutex
;
186 static void memorystatus_klist_lock(void);
187 static void memorystatus_klist_unlock(void);
189 static uint64_t memorystatus_sysprocs_idle_delay_time
= 0;
190 static uint64_t memorystatus_apps_idle_delay_time
= 0;
193 * Memorystatus kevents
196 static int filt_memorystatusattach(struct knote
*kn
);
197 static void filt_memorystatusdetach(struct knote
*kn
);
198 static int filt_memorystatus(struct knote
*kn
, long hint
);
199 static int filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
200 static int filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
202 struct filterops memorystatus_filtops
= {
203 .f_attach
= filt_memorystatusattach
,
204 .f_detach
= filt_memorystatusdetach
,
205 .f_event
= filt_memorystatus
,
206 .f_touch
= filt_memorystatustouch
,
207 .f_process
= filt_memorystatusprocess
,
211 kMemorystatusNoPressure
= 0x1,
212 kMemorystatusPressure
= 0x2,
213 kMemorystatusLowSwap
= 0x4,
214 kMemorystatusProcLimitWarn
= 0x8,
215 kMemorystatusProcLimitCritical
= 0x10
218 /* Idle guard handling */
220 static int32_t memorystatus_scheduled_idle_demotions_sysprocs
= 0;
221 static int32_t memorystatus_scheduled_idle_demotions_apps
= 0;
223 static thread_call_t memorystatus_idle_demotion_call
;
225 static void memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
);
226 static void memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
);
227 static void memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clean_state
);
228 static void memorystatus_reschedule_idle_demotion_locked(void);
230 static void memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
);
232 vm_pressure_level_t
convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
234 boolean_t
is_knote_registered_modify_task_pressure_bits(struct knote
*, int, task_t
, vm_pressure_level_t
, vm_pressure_level_t
);
235 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
);
236 void memorystatus_send_low_swap_note(void);
238 int memorystatus_wakeup
= 0;
240 unsigned int memorystatus_level
= 0;
242 static int memorystatus_list_count
= 0;
244 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
246 typedef struct memstat_bucket
{
247 TAILQ_HEAD(, proc
) list
;
251 memstat_bucket_t memstat_bucket
[MEMSTAT_BUCKET_COUNT
];
253 uint64_t memstat_idle_demotion_deadline
= 0;
255 int system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
256 int applications_aging_band
= JETSAM_PRIORITY_IDLE
;
258 #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)))
259 #define isApp(p) (! (p->p_memstat_dirty & P_DIRTY_TRACK))
260 #define isSysProc(p) ((p->p_memstat_dirty & P_DIRTY_TRACK))
262 #define kJetsamAgingPolicyNone (0)
263 #define kJetsamAgingPolicyLegacy (1)
264 #define kJetsamAgingPolicySysProcsReclaimedFirst (2)
265 #define kJetsamAgingPolicyAppsReclaimedFirst (3)
266 #define kJetsamAgingPolicyMax kJetsamAgingPolicyAppsReclaimedFirst
268 unsigned int jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
270 extern int corpse_for_fatal_memkill
;
271 extern unsigned long total_corpses_count
;
272 extern void task_purge_all_corpses(void);
276 /* Keeping around for future use if we need a utility that can do this OR an app that needs a dynamic adjustment. */
279 sysctl_set_jetsam_aging_policy SYSCTL_HANDLER_ARGS
281 #pragma unused(oidp, arg1, arg2)
283 int error
= 0, val
= 0;
284 memstat_bucket_t
*old_bucket
= 0;
285 int old_system_procs_aging_band
= 0, new_system_procs_aging_band
= 0;
286 int old_applications_aging_band
= 0, new_applications_aging_band
= 0;
287 proc_t p
= NULL
, next_proc
= NULL
;
290 error
= sysctl_io_number(req
, jetsam_aging_policy
, sizeof(int), &val
, NULL
);
291 if (error
|| !req
->newptr
) {
295 if ((val
< 0) || (val
> kJetsamAgingPolicyMax
)) {
296 printf("jetsam: ordering policy sysctl has invalid value - %d\n", val
);
301 * We need to synchronize with any potential adding/removal from aging bands
302 * that might be in progress currently. We use the proc_list_lock() just for
303 * consistency with all the routines dealing with 'aging' processes. We need
304 * a lighterweight lock.
308 old_system_procs_aging_band
= system_procs_aging_band
;
309 old_applications_aging_band
= applications_aging_band
;
313 case kJetsamAgingPolicyNone
:
314 new_system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
315 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
318 case kJetsamAgingPolicyLegacy
:
320 * Legacy behavior where some daemons get a 10s protection once and only before the first clean->dirty->clean transition before going into IDLE band.
322 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
323 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
326 case kJetsamAgingPolicySysProcsReclaimedFirst
:
327 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
328 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
331 case kJetsamAgingPolicyAppsReclaimedFirst
:
332 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
333 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
340 if (old_system_procs_aging_band
&& (old_system_procs_aging_band
!= new_system_procs_aging_band
)) {
342 old_bucket
= &memstat_bucket
[old_system_procs_aging_band
];
343 p
= TAILQ_FIRST(&old_bucket
->list
);
347 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
350 if (new_system_procs_aging_band
== JETSAM_PRIORITY_IDLE
) {
351 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
354 memorystatus_update_priority_locked(p
, new_system_procs_aging_band
, false, true);
362 if (old_applications_aging_band
&& (old_applications_aging_band
!= new_applications_aging_band
)) {
364 old_bucket
= &memstat_bucket
[old_applications_aging_band
];
365 p
= TAILQ_FIRST(&old_bucket
->list
);
369 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
372 if (new_applications_aging_band
== JETSAM_PRIORITY_IDLE
) {
373 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
376 memorystatus_update_priority_locked(p
, new_applications_aging_band
, false, true);
384 jetsam_aging_policy
= val
;
385 system_procs_aging_band
= new_system_procs_aging_band
;
386 applications_aging_band
= new_applications_aging_band
;
393 SYSCTL_PROC(_kern
, OID_AUTO
, set_jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RW
,
394 0, 0, sysctl_set_jetsam_aging_policy
, "I", "Jetsam Aging Policy");
398 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
400 #pragma unused(oidp, arg1, arg2)
402 int error
= 0, val
= 0, old_time_in_secs
= 0;
403 uint64_t old_time_in_ns
= 0;
405 absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time
, &old_time_in_ns
);
406 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
408 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
409 if (error
|| !req
->newptr
) {
413 if ((val
< 0) || (val
> INT32_MAX
)) {
414 printf("jetsam: new idle delay interval has invalid value.\n");
418 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
423 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_sysprocs_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
424 0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time
, "I", "Aging window for system processes");
428 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
430 #pragma unused(oidp, arg1, arg2)
432 int error
= 0, val
= 0, old_time_in_secs
= 0;
433 uint64_t old_time_in_ns
= 0;
435 absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time
, &old_time_in_ns
);
436 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
438 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
439 if (error
|| !req
->newptr
) {
443 if ((val
< 0) || (val
> INT32_MAX
)) {
444 printf("jetsam: new idle delay interval has invalid value.\n");
448 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
453 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_apps_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
454 0, 0, sysctl_jetsam_set_apps_idle_delay_time
, "I", "Aging window for applications");
456 SYSCTL_INT(_kern
, OID_AUTO
, jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RD
, &jetsam_aging_policy
, 0, "");
458 static unsigned int memorystatus_dirty_count
= 0;
460 SYSCTL_INT(_kern
, OID_AUTO
, max_task_pmem
, CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
, &max_task_footprint_mb
, 0, "");
464 memorystatus_get_level(__unused
struct proc
*p
, struct memorystatus_get_level_args
*args
, __unused
int *ret
)
466 user_addr_t level
= 0;
470 if (copyout(&memorystatus_level
, level
, sizeof(memorystatus_level
)) != 0) {
477 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
);
478 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
);
480 static void memorystatus_thread(void *param __unused
, wait_result_t wr __unused
);
484 static int memorystatus_highwater_enabled
= 1; /* Update the cached memlimit data. */
486 static boolean_t
proc_jetsam_state_is_active_locked(proc_t
);
487 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
488 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
495 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
);
497 static int memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
499 static int memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
);
501 static int memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
503 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
);
505 int proc_get_memstat_priority(proc_t
, boolean_t
);
507 static boolean_t memorystatus_idle_snapshot
= 0;
509 unsigned int memorystatus_delta
= 0;
511 static unsigned int memorystatus_available_pages_critical_base
= 0;
512 //static unsigned int memorystatus_last_foreground_pressure_pages = (unsigned int)-1;
513 static unsigned int memorystatus_available_pages_critical_idle_offset
= 0;
515 /* Jetsam Loop Detection */
516 static boolean_t memorystatus_jld_enabled
= TRUE
; /* Enables jetsam loop detection on all devices */
517 static uint32_t memorystatus_jld_eval_period_msecs
= 0; /* Init pass sets this based on device memory size */
518 static int memorystatus_jld_eval_aggressive_count
= 3; /* Raise the priority max after 'n' aggressive loops */
519 static int memorystatus_jld_eval_aggressive_priority_band_max
= 15; /* Kill aggressively up through this band */
522 * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
523 * --- 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.
526 * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
527 * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
529 * - 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.
531 * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
534 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD 25
535 boolean_t memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
536 boolean_t memorystatus_aggressive_jetsam_lenient
= FALSE
;
538 #if DEVELOPMENT || DEBUG
540 * Jetsam Loop Detection tunables.
543 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_period_msecs
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_period_msecs
, 0, "");
544 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_count
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_count
, 0, "");
545 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_priority_band_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_priority_band_max
, 0, "");
546 #endif /* DEVELOPMENT || DEBUG */
548 #if DEVELOPMENT || DEBUG
549 static unsigned int memorystatus_jetsam_panic_debug
= 0;
550 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic
= 0;
553 static unsigned int memorystatus_jetsam_policy
= kPolicyDefault
;
554 static unsigned int memorystatus_thread_wasted_wakeup
= 0;
556 static uint32_t kill_under_pressure_cause
= 0;
559 * default jetsam snapshot support
561 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot
;
562 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
563 static unsigned int memorystatus_jetsam_snapshot_count
= 0;
564 static unsigned int memorystatus_jetsam_snapshot_max
= 0;
565 static uint64_t memorystatus_jetsam_snapshot_last_timestamp
= 0;
566 static uint64_t memorystatus_jetsam_snapshot_timeout
= 0;
567 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
570 * snapshot support for memstats collected at boot.
572 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot
;
574 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
);
575 static boolean_t
memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
);
576 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
);
578 static void memorystatus_clear_errors(void);
579 static void memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
);
580 static void memorystatus_get_task_phys_footprint_page_counts(task_t task
,
581 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
582 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
583 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
584 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
);
586 static void memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
);
588 static uint32_t memorystatus_build_state(proc_t p
);
589 static void memorystatus_update_levels_locked(boolean_t critical_only
);
590 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
592 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
);
593 static boolean_t
memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, int32_t priority_max
, uint32_t *errors
);
594 static boolean_t
memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
);
595 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t *errors
);
597 static boolean_t
memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
);
599 /* Priority Band Sorting Routines */
600 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
);
601 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
);
602 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
);
603 static int memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
);
606 typedef int (*cmpfunc_t
)(const void *a
, const void *b
);
607 extern void qsort(void *a
, size_t n
, size_t es
, cmpfunc_t cmp
);
608 static int memstat_asc_cmp(const void *a
, const void *b
);
610 #endif /* CONFIG_JETSAM */
614 extern unsigned int vm_page_free_count
;
615 extern unsigned int vm_page_active_count
;
616 extern unsigned int vm_page_inactive_count
;
617 extern unsigned int vm_page_throttled_count
;
618 extern unsigned int vm_page_purgeable_count
;
619 extern unsigned int vm_page_wire_count
;
620 #if CONFIG_SECLUDED_MEMORY
621 extern unsigned int vm_page_secluded_count
;
622 #endif /* CONFIG_SECLUDED_MEMORY */
624 #if VM_PRESSURE_EVENTS
626 boolean_t
memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t exceeded
);
628 vm_pressure_level_t memorystatus_vm_pressure_level
= kVMPressureNormal
;
630 #if CONFIG_MEMORYSTATUS
631 unsigned int memorystatus_available_pages
= (unsigned int)-1;
632 unsigned int memorystatus_available_pages_pressure
= 0;
633 unsigned int memorystatus_available_pages_critical
= 0;
634 unsigned int memorystatus_frozen_count
= 0;
635 unsigned int memorystatus_suspended_count
= 0;
636 unsigned int memorystatus_policy_more_free_offset_pages
= 0;
639 #if DEVELOPMENT || DEBUG
640 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
642 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_MASKED
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
643 #endif /* DEVELOPMENT || DEBUG */
644 #endif /* CONFIG_JETSAM */
647 * We use this flag to signal if we have any HWM offenders
648 * on the system. This way we can reduce the number of wakeups
649 * of the memorystatus_thread when the system is between the
650 * "pressure" and "critical" threshold.
652 * The (re-)setting of this variable is done without any locks
653 * or synchronization simply because it is not possible (currently)
654 * to keep track of HWM offenders that drop down below their memory
655 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
656 * by allowing the unguarded modification of this variable.
658 boolean_t memorystatus_hwm_candidates
= 0;
660 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
661 #endif /* CONFIG_MEMORYSTATUS */
663 #endif /* VM_PRESSURE_EVENTS */
666 #if DEVELOPMENT || DEBUG
668 lck_grp_attr_t
*disconnect_page_mappings_lck_grp_attr
;
669 lck_grp_t
*disconnect_page_mappings_lck_grp
;
670 static lck_mtx_t disconnect_page_mappings_mutex
;
679 boolean_t memorystatus_freeze_enabled
= FALSE
;
680 int memorystatus_freeze_wakeup
= 0;
682 lck_grp_attr_t
*freezer_lck_grp_attr
;
683 lck_grp_t
*freezer_lck_grp
;
684 static lck_mtx_t freezer_mutex
;
686 static inline boolean_t
memorystatus_can_freeze_processes(void);
687 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
689 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
692 static unsigned int memorystatus_freeze_threshold
= 0;
694 static unsigned int memorystatus_freeze_pages_min
= 0;
695 static unsigned int memorystatus_freeze_pages_max
= 0;
697 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
699 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
702 static uint64_t memorystatus_freeze_count
= 0;
703 static uint64_t memorystatus_freeze_pageouts
= 0;
706 static throttle_interval_t throttle_intervals
[] = {
707 { 60, 8, 0, 0, { 0, 0 }, FALSE
}, /* 1 hour intermediate interval, 8x burst */
708 { 24 * 60, 1, 0, 0, { 0, 0 }, FALSE
}, /* 24 hour long interval, no burst */
711 static uint64_t memorystatus_freeze_throttle_count
= 0;
713 static unsigned int memorystatus_suspended_footprint_total
= 0; /* pages */
715 extern uint64_t vm_swap_get_free_space(void);
717 static boolean_t
memorystatus_freeze_update_throttle();
719 #endif /* CONFIG_FREEZE */
723 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
725 #if DEVELOPMENT || DEBUG
727 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
730 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index
)
734 int ledger_limit
= 0;
735 unsigned int b
= bucket_index
;
736 boolean_t traverse_all_buckets
= FALSE
;
738 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
739 traverse_all_buckets
= TRUE
;
742 traverse_all_buckets
= FALSE
;
747 * footprint reported in [pages / MB ]
748 * limits reported as:
749 * L-limit proc's Ledger limit
750 * C-limit proc's Cached limit, should match Ledger
751 * A-limit proc's Active limit
752 * IA-limit proc's Inactive limit
753 * F==Fatal, NF==NonFatal
756 printf("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64
);
757 printf("bucket [pid] [pages / MB] [state] [EP / RP] dirty deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
758 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
760 bytes
= get_task_phys_footprint(p
->task
);
761 task_get_phys_footprint_limit(p
->task
, &ledger_limit
);
762 printf("%2d [%5d] [%5lld /%3lldMB] 0x%-8x [%2d / %2d] 0x%-3x %10lld [%3d / %3d%s / %3d%s / %3d%s] %s\n",
764 (bytes
/ PAGE_SIZE_64
), /* task's footprint converted from bytes to pages */
765 (bytes
/ (1024ULL * 1024ULL)), /* task's footprint converted from bytes to MB */
766 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
768 p
->p_memstat_memlimit
,
769 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
770 p
->p_memstat_memlimit_active
,
771 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
772 p
->p_memstat_memlimit_inactive
,
773 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
774 (*p
->p_name
? p
->p_name
: "unknown"));
775 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
777 printf("memorystatus_debug_dump ***END***\n");
781 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
783 #pragma unused(oidp, arg2)
784 int bucket_index
= 0;
786 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
787 if (error
|| !req
->newptr
) {
790 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
791 if (error
|| !req
->newptr
) {
794 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
796 * All jetsam buckets will be dumped.
800 * Only a single bucket will be dumped.
805 memorystatus_debug_dump_bucket_locked(bucket_index
);
807 memorystatus_debug_dump_this_bucket
= bucket_index
;
812 * Debug aid to look at jetsam buckets and proc jetsam fields.
813 * Use this sysctl to act on a particular jetsam bucket.
814 * Writing the sysctl triggers the dump.
815 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
818 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", "");
821 /* Debug aid to aid determination of limit */
824 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
826 #pragma unused(oidp, arg2)
829 int error
, enable
= 0;
830 boolean_t use_active
; /* use the active limit and active limit attributes */
833 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
834 if (error
|| !req
->newptr
) {
838 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
839 if (error
|| !req
->newptr
) {
843 if (!(enable
== 0 || enable
== 1)) {
849 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
851 use_active
= proc_jetsam_state_is_active_locked(p
);
855 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
856 * Background limits are described via the inactive limit slots.
859 if (use_active
== TRUE
) {
860 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
862 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
867 * Disabling limits does not touch the stored variants.
868 * Set the cached limit fields to system_wide defaults.
870 p
->p_memstat_memlimit
= -1;
871 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
876 * Enforce the cached limit by writing to the ledger.
878 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
880 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
883 memorystatus_highwater_enabled
= enable
;
891 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
893 #if VM_PRESSURE_EVENTS
896 * This routine is used for targeted notifications regardless of system memory pressure
897 * and regardless of whether or not the process has already been notified.
898 * It bypasses and has no effect on the only-one-notification per soft-limit policy.
900 * "memnote" is the current user.
904 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
906 #pragma unused(arg1, arg2)
908 int error
= 0, pid
= 0;
909 struct knote
*kn
= NULL
;
910 boolean_t found_knote
= FALSE
;
911 int fflags
= 0; /* filter flags for EVFILT_MEMORYSTATUS */
914 error
= sysctl_handle_quad(oidp
, &value
, 0, req
);
915 if (error
|| !req
->newptr
)
919 * Find the pid in the low 32 bits of value passed in.
921 pid
= (int)(value
& 0xFFFFFFFF);
924 * Find notification in the high 32 bits of the value passed in.
926 fflags
= (int)((value
>> 32) & 0xFFFFFFFF);
929 * For backwards compatibility, when no notification is
930 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
933 fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
934 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
938 * See event.h ... fflags for EVFILT_MEMORYSTATUS
940 if (!((fflags
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
)||
941 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) ||
942 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) ||
943 (fflags
== NOTE_MEMORYSTATUS_LOW_SWAP
) ||
944 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) ||
945 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
))) {
947 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags
);
953 * Forcibly send pid a memorystatus notification.
956 memorystatus_klist_lock();
958 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
959 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
960 pid_t knote_pid
= knote_proc
->p_pid
;
962 if (knote_pid
== pid
) {
964 * Forcibly send this pid a memorystatus notification.
966 kn
->kn_fflags
= fflags
;
972 KNOTE(&memorystatus_klist
, 0);
973 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value
, fflags
, pid
);
976 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value
, fflags
, pid
);
980 memorystatus_klist_unlock();
985 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_QUAD
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
986 0, 0, &sysctl_memorystatus_vm_pressure_send
, "Q", "");
988 #endif /* VM_PRESSURE_EVENTS */
992 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
994 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
995 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
996 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
997 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_policy_more_free_offset_pages
, CTLFLAG_RW
, &memorystatus_policy_more_free_offset_pages
, 0, "");
999 /* Diagnostic code */
1002 kJetsamDiagnosticModeNone
= 0,
1003 kJetsamDiagnosticModeAll
= 1,
1004 kJetsamDiagnosticModeStopAtFirstActive
= 2,
1005 kJetsamDiagnosticModeCount
1006 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
1008 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
1011 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1013 #pragma unused(arg1, arg2)
1015 const char *diagnosticStrings
[] = {
1016 "jetsam: diagnostic mode: resetting critical level.",
1017 "jetsam: diagnostic mode: will examine all processes",
1018 "jetsam: diagnostic mode: will stop at first active process"
1021 int error
, val
= jetsam_diagnostic_mode
;
1022 boolean_t changed
= FALSE
;
1024 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
1025 if (error
|| !req
->newptr
)
1027 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
1028 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
1034 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
1035 jetsam_diagnostic_mode
= val
;
1037 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
1039 switch (jetsam_diagnostic_mode
) {
1040 case kJetsamDiagnosticModeNone
:
1041 /* Already cleared */
1043 case kJetsamDiagnosticModeAll
:
1044 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
1046 case kJetsamDiagnosticModeStopAtFirstActive
:
1047 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
1050 /* Already validated */
1054 memorystatus_update_levels_locked(FALSE
);
1061 printf("%s\n", diagnosticStrings
[val
]);
1067 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
|CTLFLAG_ANYBODY
,
1068 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
1070 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
1072 #if VM_PRESSURE_EVENTS
1074 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
1076 #endif /* VM_PRESSURE_EVENTS */
1078 #endif /* CONFIG_JETSAM */
1082 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
1084 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
1086 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
1087 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
1089 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_count
, "");
1090 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
1091 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_throttle_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_count
, "");
1092 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
1094 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
1095 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
1097 #define VM_PAGES_FOR_ALL_PROCS (2)
1099 * Manual trigger of freeze and thaw for dev / debug kernels only.
1102 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1104 #pragma unused(arg1, arg2)
1108 if (memorystatus_freeze_enabled
== FALSE
) {
1112 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1113 if (error
|| !req
->newptr
)
1116 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1117 vm_pageout_anonymous_pages();
1122 lck_mtx_lock(&freezer_mutex
);
1126 uint32_t purgeable
, wired
, clean
, dirty
;
1128 uint32_t max_pages
= 0;
1130 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1132 unsigned int avail_swap_space
= 0; /* in pages. */
1135 * Freezer backed by the compressor and swap file(s)
1136 * while will hold compressed data.
1138 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
1140 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
1144 * We only have the compressor without any swap.
1146 max_pages
= UINT32_MAX
- 1;
1149 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
1155 lck_mtx_unlock(&freezer_mutex
);
1159 lck_mtx_unlock(&freezer_mutex
);
1163 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1164 0, 0, &sysctl_memorystatus_freeze
, "I", "");
1167 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1169 #pragma unused(arg1, arg2)
1174 if (memorystatus_freeze_enabled
== FALSE
) {
1178 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1179 if (error
|| !req
->newptr
)
1182 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1183 do_fastwake_warmup_all();
1188 error
= task_thaw(p
->task
);
1200 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1201 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
1203 #endif /* CONFIG_FREEZE */
1205 #endif /* DEVELOPMENT || DEBUG */
1207 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
1210 thread_t
*new_thread
);
1212 #if DEVELOPMENT || DEBUG
1215 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1217 #pragma unused(arg1, arg2)
1218 int error
= 0, pid
= 0;
1221 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1222 if (error
|| !req
->newptr
)
1225 lck_mtx_lock(&disconnect_page_mappings_mutex
);
1228 vm_pageout_disconnect_all_pages();
1233 error
= task_disconnect_page_mappings(p
->task
);
1242 lck_mtx_unlock(&disconnect_page_mappings_mutex
);
1247 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_disconnect_page_mappings
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1248 0, 0, &sysctl_memorystatus_disconnect_page_mappings
, "I", "");
1250 #endif /* DEVELOPMENT || DEBUG */
1256 * Picks the sorting routine for a given jetsam priority band.
1259 * bucket_index - jetsam priority band to be sorted.
1260 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1261 * Currently sort_order is only meaningful when handling
1268 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
1270 int coal_sort_order
;
1273 * Verify the jetsam priority
1275 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1279 #if DEVELOPMENT || DEBUG
1280 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1281 coal_sort_order
= COALITION_SORT_DEFAULT
;
1283 coal_sort_order
= sort_order
; /* only used for testing scenarios */
1286 /* Verify default */
1287 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1288 coal_sort_order
= COALITION_SORT_DEFAULT
;
1295 switch (bucket_index
) {
1296 case JETSAM_PRIORITY_FOREGROUND
:
1297 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
1299 * Fall back to per process sorting when zero coalitions are found.
1301 memorystatus_sort_by_largest_process_locked(bucket_index
);
1305 memorystatus_sort_by_largest_process_locked(bucket_index
);
1314 * Sort processes by size for a single jetsam bucket.
1317 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
1319 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
1320 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
1321 uint32_t pages
= 0, max_pages
= 0;
1322 memstat_bucket_t
*current_bucket
;
1324 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1328 current_bucket
= &memstat_bucket
[bucket_index
];
1330 p
= TAILQ_FIRST(¤t_bucket
->list
);
1333 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1338 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
1339 /* traversing list until we find next largest process */
1341 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1342 if (pages
> max_pages
) {
1348 if (prev_max_proc
!= max_proc
) {
1349 /* found a larger process, place it in the list */
1350 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1351 if (insert_after_proc
== NULL
) {
1352 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1354 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1356 prev_max_proc
= max_proc
;
1359 insert_after_proc
= max_proc
;
1361 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1365 #endif /* CONFIG_JETSAM */
1367 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
) {
1368 memstat_bucket_t
*current_bucket
;
1371 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1375 current_bucket
= &memstat_bucket
[*bucket_index
];
1376 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1377 if (!next_p
&& search
) {
1378 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1379 current_bucket
= &memstat_bucket
[*bucket_index
];
1380 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1387 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
) {
1388 memstat_bucket_t
*current_bucket
;
1391 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1395 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1396 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1397 current_bucket
= &memstat_bucket
[*bucket_index
];
1398 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1404 __private_extern__
void
1405 memorystatus_init(void)
1407 thread_t thread
= THREAD_NULL
;
1408 kern_return_t result
;
1412 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1413 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1416 #if DEVELOPMENT || DEBUG
1417 disconnect_page_mappings_lck_grp_attr
= lck_grp_attr_alloc_init();
1418 disconnect_page_mappings_lck_grp
= lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr
);
1420 lck_mtx_init(&disconnect_page_mappings_mutex
, disconnect_page_mappings_lck_grp
, NULL
);
1423 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
1424 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
1427 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1428 TAILQ_INIT(&memstat_bucket
[i
].list
);
1429 memstat_bucket
[i
].count
= 0;
1432 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1434 /* Apply overrides */
1435 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1436 if (delta_percentage
== 0) {
1437 delta_percentage
= 5;
1439 assert(delta_percentage
< 100);
1440 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1441 assert(critical_threshold_percentage
< 100);
1442 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1443 assert(idle_offset_percentage
< 100);
1444 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1445 assert(pressure_threshold_percentage
< 100);
1446 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1447 assert(freeze_threshold_percentage
< 100);
1449 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy
,
1450 sizeof (jetsam_aging_policy
))) {
1452 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy
,
1453 sizeof(jetsam_aging_policy
))) {
1455 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1459 if (jetsam_aging_policy
> kJetsamAgingPolicyMax
) {
1460 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1463 switch (jetsam_aging_policy
) {
1465 case kJetsamAgingPolicyNone
:
1466 system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
1467 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1470 case kJetsamAgingPolicyLegacy
:
1472 * Legacy behavior where some daemons get a 10s protection once
1473 * AND only before the first clean->dirty->clean transition before
1474 * going into IDLE band.
1476 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1477 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1480 case kJetsamAgingPolicySysProcsReclaimedFirst
:
1481 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1482 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1485 case kJetsamAgingPolicyAppsReclaimedFirst
:
1486 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1487 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1495 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1496 * band and must be below it in priority. This is so that we don't have to make
1497 * our 'aging' code worry about a mix of processes, some of which need to age
1498 * and some others that need to stay elevated in the jetsam bands.
1500 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> system_procs_aging_band
);
1501 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> applications_aging_band
);
1504 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1505 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof (memorystatus_idle_snapshot
))) {
1506 /* ...no boot-arg, so check the device tree */
1507 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1510 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1511 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1512 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1513 memorystatus_policy_more_free_offset_pages
= (policy_more_free_offset_percentage
/ delta_percentage
) * memorystatus_delta
;
1515 memorystatus_jetsam_snapshot_max
= maxproc
;
1516 memorystatus_jetsam_snapshot
=
1517 (memorystatus_jetsam_snapshot_t
*)kalloc(sizeof(memorystatus_jetsam_snapshot_t
) +
1518 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
1519 if (!memorystatus_jetsam_snapshot
) {
1520 panic("Could not allocate memorystatus_jetsam_snapshot");
1523 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
1525 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
1527 /* No contention at this point */
1528 memorystatus_update_levels_locked(FALSE
);
1530 /* Jetsam Loop Detection */
1531 if (max_mem
<= (512 * 1024 * 1024)) {
1532 /* 512 MB devices */
1533 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
1535 /* 1GB and larger devices */
1536 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
1541 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1544 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &thread
);
1545 if (result
== KERN_SUCCESS
) {
1546 thread_deallocate(thread
);
1548 panic("Could not create memorystatus_thread");
1552 /* Centralised for the purposes of allowing panic-on-jetsam */
1554 vm_run_compactor(void);
1557 * The jetsam no frills kill call
1558 * Return: 0 on success
1559 * error code on failure (EINVAL...)
1562 jetsam_do_kill(proc_t p
, int jetsam_flags
, os_reason_t jetsam_reason
) {
1564 error
= exit_with_reason(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
, jetsam_reason
);
1569 * Wrapper for processes exiting with memorystatus details
1572 memorystatus_do_kill(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
) {
1575 __unused pid_t victim_pid
= p
->p_pid
;
1577 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
1578 victim_pid
, cause
, vm_page_free_count
, 0, 0);
1580 DTRACE_MEMORYSTATUS3(memorystatus_do_kill
, proc_t
, p
, os_reason_t
, jetsam_reason
, uint32_t, cause
);
1581 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1582 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
1583 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
1586 #pragma unused(cause)
1588 int jetsam_flags
= P_LTERM_JETSAM
;
1590 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
1591 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
1592 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
1593 case kMemorystatusKilledVMThrashing
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
1594 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
1595 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
1596 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
1598 error
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
1600 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
1601 victim_pid
, cause
, vm_page_free_count
, error
, 0);
1605 return (error
== 0);
1613 memorystatus_check_levels_locked(void) {
1616 memorystatus_update_levels_locked(TRUE
);
1621 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1622 * For an application: that means no longer in the FG band
1623 * For a daemon: that means no longer in its 'requested' jetsam priority band
1627 memorystatus_update_inactive_jetsam_priority_band(pid_t pid
, uint32_t op_flags
, boolean_t effective_now
)
1630 boolean_t enable
= FALSE
;
1633 if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
) {
1635 } else if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
) {
1644 if ((enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) ||
1645 (!enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == 0))) {
1647 * No change in state.
1655 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1656 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1658 if (effective_now
) {
1659 if (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1660 if(memorystatus_highwater_enabled
) {
1662 * Process is about to transition from
1663 * inactive --> active
1664 * assign active state
1667 boolean_t use_active
= TRUE
;
1668 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
1669 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
1671 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_ELEVATED_INACTIVE
, FALSE
, FALSE
);
1674 if (isProcessInAgingBands(p
)) {
1675 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1680 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1681 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1683 if (effective_now
) {
1684 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1685 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1688 if (isProcessInAgingBands(p
)) {
1689 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1707 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
1710 uint64_t current_time
= 0, idle_delay_time
= 0;
1711 int demote_prio_band
= 0;
1712 memstat_bucket_t
*demotion_bucket
;
1714 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1716 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1718 current_time
= mach_absolute_time();
1722 demote_prio_band
= JETSAM_PRIORITY_IDLE
+ 1;
1724 for (; demote_prio_band
< JETSAM_PRIORITY_MAX
; demote_prio_band
++) {
1726 if (demote_prio_band
!= system_procs_aging_band
&& demote_prio_band
!= applications_aging_band
)
1729 demotion_bucket
= &memstat_bucket
[demote_prio_band
];
1730 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1733 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
1735 assert(p
->p_memstat_idledeadline
);
1737 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
1739 if (current_time
>= p
->p_memstat_idledeadline
) {
1741 if ((isSysProc(p
) &&
1742 ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) != P_DIRTY_IDLE_EXIT_ENABLED
)) || /* system proc marked dirty*/
1743 task_has_assertions((struct task
*)(p
->task
))) { /* has outstanding assertions which might indicate outstanding work too */
1744 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1746 p
->p_memstat_idledeadline
+= idle_delay_time
;
1747 p
= TAILQ_NEXT(p
, p_memstat_list
);
1751 proc_t next_proc
= NULL
;
1753 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
1754 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1756 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false, true);
1763 // No further candidates
1770 memorystatus_reschedule_idle_demotion_locked();
1774 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
1778 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
1780 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1781 boolean_t present_in_apps_aging_bucket
= FALSE
;
1782 uint64_t idle_delay_time
= 0;
1784 if (jetsam_aging_policy
== kJetsamAgingPolicyNone
) {
1788 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
1790 * This process isn't going to be making the trip to the lower bands.
1795 if (isProcessInAgingBands(p
)){
1797 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1798 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) != P_DIRTY_AGING_IN_PROGRESS
);
1801 if (isSysProc(p
) && system_procs_aging_band
) {
1802 present_in_sysprocs_aging_bucket
= TRUE
;
1804 } else if (isApp(p
) && applications_aging_band
) {
1805 present_in_apps_aging_bucket
= TRUE
;
1809 assert(!present_in_sysprocs_aging_bucket
);
1810 assert(!present_in_apps_aging_bucket
);
1812 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",
1813 p
->p_pid
, p
->p_memstat_dirty
, set_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1816 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
1819 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1822 p
->p_memstat_dirty
|= P_DIRTY_AGING_IN_PROGRESS
;
1823 p
->p_memstat_idledeadline
= mach_absolute_time() + idle_delay_time
;
1826 assert(p
->p_memstat_idledeadline
);
1828 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== FALSE
) {
1829 memorystatus_scheduled_idle_demotions_sysprocs
++;
1831 } else if (isApp(p
) && present_in_apps_aging_bucket
== FALSE
) {
1832 memorystatus_scheduled_idle_demotions_apps
++;
1837 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
1839 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1840 boolean_t present_in_apps_aging_bucket
= FALSE
;
1842 if (!system_procs_aging_band
&& !applications_aging_band
) {
1846 if ((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0) {
1850 if (isProcessInAgingBands(p
)) {
1852 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1853 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == P_DIRTY_AGING_IN_PROGRESS
);
1856 if (isSysProc(p
) && system_procs_aging_band
) {
1857 assert(p
->p_memstat_effectivepriority
== system_procs_aging_band
);
1858 assert(p
->p_memstat_idledeadline
);
1859 present_in_sysprocs_aging_bucket
= TRUE
;
1861 } else if (isApp(p
) && applications_aging_band
) {
1862 assert(p
->p_memstat_effectivepriority
== applications_aging_band
);
1863 assert(p
->p_memstat_idledeadline
);
1864 present_in_apps_aging_bucket
= TRUE
;
1868 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1869 p
->p_pid
, clear_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1873 p
->p_memstat_idledeadline
= 0;
1874 p
->p_memstat_dirty
&= ~P_DIRTY_AGING_IN_PROGRESS
;
1877 if (isSysProc(p
) &&present_in_sysprocs_aging_bucket
== TRUE
) {
1878 memorystatus_scheduled_idle_demotions_sysprocs
--;
1879 assert(memorystatus_scheduled_idle_demotions_sysprocs
>= 0);
1881 } else if (isApp(p
) && present_in_apps_aging_bucket
== TRUE
) {
1882 memorystatus_scheduled_idle_demotions_apps
--;
1883 assert(memorystatus_scheduled_idle_demotions_apps
>= 0);
1886 assert((memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
) >= 0);
1890 memorystatus_reschedule_idle_demotion_locked(void) {
1891 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
)) {
1892 if (memstat_idle_demotion_deadline
) {
1893 /* Transitioned 1->0, so cancel next call */
1894 thread_call_cancel(memorystatus_idle_demotion_call
);
1895 memstat_idle_demotion_deadline
= 0;
1898 memstat_bucket_t
*demotion_bucket
;
1899 proc_t p
= NULL
, p1
= NULL
, p2
= NULL
;
1901 if (system_procs_aging_band
) {
1903 demotion_bucket
= &memstat_bucket
[system_procs_aging_band
];
1904 p1
= TAILQ_FIRST(&demotion_bucket
->list
);
1909 if (applications_aging_band
) {
1911 demotion_bucket
= &memstat_bucket
[applications_aging_band
];
1912 p2
= TAILQ_FIRST(&demotion_bucket
->list
);
1915 p
= (p1
->p_memstat_idledeadline
> p2
->p_memstat_idledeadline
) ? p2
: p1
;
1917 p
= (p1
== NULL
) ? p2
: p1
;
1925 assert(p
&& p
->p_memstat_idledeadline
);
1926 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
){
1927 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
1928 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
1939 memorystatus_add(proc_t p
, boolean_t locked
)
1941 memstat_bucket_t
*bucket
;
1943 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
1949 DTRACE_MEMORYSTATUS2(memorystatus_add
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
);
1951 /* Processes marked internal do not have priority tracked */
1952 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1956 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1958 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
1959 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
- 1);
1961 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
1962 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
- 1);
1964 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
1966 * Entering the idle band.
1967 * Record idle start time.
1969 p
->p_memstat_idle_start
= mach_absolute_time();
1972 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
1975 memorystatus_list_count
++;
1977 memorystatus_check_levels_locked();
1989 * Moves a process from one jetsam bucket to another.
1990 * which changes the LRU position of the process.
1992 * Monitors transition between buckets and if necessary
1993 * will update cached memory limits accordingly.
1995 * skip_demotion_check:
1996 * - if the 'jetsam aging policy' is NOT 'legacy':
1997 * When this flag is TRUE, it means we are going
1998 * to age the ripe processes out of the aging bands and into the
1999 * IDLE band and apply their inactive memory limits.
2001 * - if the 'jetsam aging policy' is 'legacy':
2002 * When this flag is TRUE, it might mean the above aging mechanism
2004 * It might be that we have a process that has used up its 'idle deferral'
2005 * stay that is given to it once per lifetime. And in this case, the process
2006 * won't be going through any aging codepaths. But we still need to apply
2007 * the right inactive limits and so we explicitly set this to TRUE if the
2008 * new priority for the process is the IDLE band.
2011 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
)
2013 memstat_bucket_t
*old_bucket
, *new_bucket
;
2015 assert(priority
< MEMSTAT_BUCKET_COUNT
);
2017 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2018 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2022 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2023 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, head_insert
? "head" : "tail");
2025 DTRACE_MEMORYSTATUS3(memorystatus_update_priority
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
, int, priority
);
2027 #if DEVELOPMENT || DEBUG
2028 if (priority
== JETSAM_PRIORITY_IDLE
&& /* if the process is on its way into the IDLE band */
2029 skip_demotion_check
== FALSE
&& /* and it isn't via the path that will set the INACTIVE memlimits */
2030 (p
->p_memstat_dirty
& P_DIRTY_TRACK
) && /* and it has 'DIRTY' tracking enabled */
2031 ((p
->p_memstat_memlimit
!= p
->p_memstat_memlimit_inactive
) || /* and we notice that the current limit isn't the right value (inactive) */
2032 ((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) */
2033 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 */
2034 #endif /* DEVELOPMENT || DEBUG */
2036 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2038 if (skip_demotion_check
== FALSE
) {
2042 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2043 * the processes from the aging bands and balancing the demotion counts.
2044 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2047 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2048 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2050 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2052 } else if (isApp(p
)) {
2055 * Check to see if the application is being lowered in jetsam priority. If so, and:
2056 * - it has an 'elevated inactive jetsam band' attribute, then put it in the JETSAM_PRIORITY_ELEVATED_INACTIVE band.
2057 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2060 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2061 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2064 if (applications_aging_band
) {
2065 if (p
->p_memstat_effectivepriority
== applications_aging_band
) {
2066 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions_apps
+ 1));
2069 if ((jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) && (priority
<= applications_aging_band
)) {
2070 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2071 priority
= applications_aging_band
;
2072 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2079 if ((system_procs_aging_band
&& (priority
== system_procs_aging_band
)) || (applications_aging_band
&& (priority
== applications_aging_band
))) {
2080 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2083 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
2084 old_bucket
->count
--;
2086 new_bucket
= &memstat_bucket
[priority
];
2088 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
2090 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
2091 new_bucket
->count
++;
2093 if (memorystatus_highwater_enabled
) {
2095 boolean_t use_active
;
2098 * If cached limit data is updated, then the limits
2099 * will be enforced by writing to the ledgers.
2101 boolean_t ledger_update_needed
= TRUE
;
2104 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
2105 * Background limits are described via the inactive limit slots.
2107 * Here, we must update the cached memory limit if the task
2108 * is transitioning between:
2109 * active <--> inactive
2112 * dirty <--> clean is ignored
2114 * We bypass non-idle processes that have opted into dirty tracking because
2115 * a move between buckets does not imply a transition between the
2116 * dirty <--> clean state.
2119 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2121 if (skip_demotion_check
== TRUE
&& priority
== JETSAM_PRIORITY_IDLE
) {
2122 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2125 ledger_update_needed
= FALSE
;
2128 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
2130 * inactive --> active
2132 * assign active state
2134 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2137 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
2139 * active --> inactive
2141 * assign inactive state
2143 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2147 * The transition between jetsam priority buckets apparently did
2148 * not affect active/inactive state.
2149 * This is not unusual... especially during startup when
2150 * processes are getting established in their respective bands.
2152 ledger_update_needed
= FALSE
;
2156 * Enforce the new limits by writing to the ledger
2158 if (ledger_update_needed
) {
2159 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
2161 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2162 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2163 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
2164 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2169 * Record idle start or idle delta.
2171 if (p
->p_memstat_effectivepriority
== priority
) {
2173 * This process is not transitioning between
2174 * jetsam priority buckets. Do nothing.
2176 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2179 * Transitioning out of the idle priority bucket.
2180 * Record idle delta.
2182 assert(p
->p_memstat_idle_start
!= 0);
2183 now
= mach_absolute_time();
2184 if (now
> p
->p_memstat_idle_start
) {
2185 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2187 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
2189 * Transitioning into the idle priority bucket.
2190 * Record idle start.
2192 p
->p_memstat_idle_start
= mach_absolute_time();
2195 p
->p_memstat_effectivepriority
= priority
;
2197 #if CONFIG_SECLUDED_MEMORY
2198 if (secluded_for_apps
&&
2199 task_could_use_secluded_mem(p
->task
)) {
2200 task_set_can_use_secluded_mem(
2202 (priority
>= JETSAM_PRIORITY_FOREGROUND
));
2204 #endif /* CONFIG_SECLUDED_MEMORY */
2206 memorystatus_check_levels_locked();
2211 * Description: Update the jetsam priority and memory limit attributes for a given process.
2214 * p init this process's jetsam information.
2215 * priority The jetsam priority band
2216 * user_data user specific data, unused by the kernel
2217 * effective guards against race if process's update already occurred
2218 * update_memlimit When true we know this is the init step via the posix_spawn path.
2220 * memlimit_active Value in megabytes; The monitored footprint level while the
2221 * process is active. Exceeding it may result in termination
2222 * based on it's associated fatal flag.
2224 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2225 * this describes whether or not it should be immediately fatal.
2227 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2228 * process is inactive. Exceeding it may result in termination
2229 * based on it's associated fatal flag.
2231 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2232 * this describes whether or not it should be immediatly fatal.
2234 * memlimit_background This process has a high-water-mark while in the background.
2235 * No longer meaningful. Background limits are described via
2236 * the inactive slots. Flag is ignored.
2239 * Returns: 0 Success
2244 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
2245 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
2246 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
,
2247 __unused boolean_t memlimit_background
)
2250 boolean_t head_insert
= false;
2252 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
);
2254 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
2256 if (priority
== -1) {
2257 /* Use as shorthand for default priority */
2258 priority
= JETSAM_PRIORITY_DEFAULT
;
2259 } else if ((priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
2260 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2261 priority
= JETSAM_PRIORITY_IDLE
;
2262 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
2263 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2264 priority
= JETSAM_PRIORITY_IDLE
;
2266 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
2274 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2276 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
2279 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
2283 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
2285 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2292 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
2293 p
->p_memstat_userdata
= user_data
;
2294 p
->p_memstat_requestedpriority
= priority
;
2296 if (update_memlimit
) {
2298 boolean_t use_active
;
2301 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2302 * Forked processes do not come through this path, so no ledger limits exist.
2303 * (That's why forked processes can consume unlimited memory.)
2306 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2307 p
->p_pid
, priority
, p
->p_memstat_dirty
,
2308 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2309 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2311 if (memlimit_background
) {
2314 * With 2-level HWM support, we no longer honor P_MEMSTAT_MEMLIMIT_BACKGROUND.
2315 * Background limits are described via the inactive limit slots.
2318 // p->p_memstat_state |= P_MEMSTAT_MEMLIMIT_BACKGROUND;
2320 #if DEVELOPMENT || DEBUG
2321 printf("memorystatus_update: WARNING %s[%d] set unused flag P_MEMSTAT_MEMLIMIT_BACKGROUND [A==%dMB %s] [IA==%dMB %s]\n",
2322 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
,
2323 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2324 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2325 #endif /* DEVELOPMENT || DEBUG */
2328 if (memlimit_active
<= 0) {
2330 * This process will have a system_wide task limit when active.
2331 * System_wide task limit is always fatal.
2332 * It's quite common to see non-fatal flag passed in here.
2333 * It's not an error, we just ignore it.
2337 * For backward compatibility with some unexplained launchd behavior,
2338 * we allow a zero sized limit. But we still enforce system_wide limit
2339 * when written to the ledgers.
2342 if (memlimit_active
< 0) {
2343 memlimit_active
= -1; /* enforces system_wide task limit */
2345 memlimit_active_is_fatal
= TRUE
;
2348 if (memlimit_inactive
<= 0) {
2350 * This process will have a system_wide task limit when inactive.
2351 * System_wide task limit is always fatal.
2354 memlimit_inactive
= -1;
2355 memlimit_inactive_is_fatal
= TRUE
;
2359 * Initialize the active limit variants for this process.
2361 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
2364 * Initialize the inactive limit variants for this process.
2366 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
2369 * Initialize the cached limits for target process.
2370 * When the target process is dirty tracked, it's typically
2371 * in a clean state. Non dirty tracked processes are
2372 * typically active (Foreground or above).
2373 * But just in case, we don't make assumptions...
2376 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2377 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2380 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2385 * Enforce the cached limit by writing to the ledger.
2387 if (memorystatus_highwater_enabled
) {
2389 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, use_active
, is_fatal
);
2391 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2392 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2393 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
2394 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2399 * We can't add to the aging bands buckets here.
2400 * But, we could be removing it from those buckets.
2401 * Check and take appropriate steps if so.
2404 if (isProcessInAgingBands(p
)) {
2406 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2407 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2409 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
&& priority
== JETSAM_PRIORITY_IDLE
) {
2411 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2412 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2413 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2414 * is any other aging policy, then we don't need to worry because all processes
2415 * will go through the aging bands and then the demotion thread will take care to
2416 * move them into the IDLE band and apply the required limits.
2418 memorystatus_update_priority_locked(p
, priority
, head_insert
, TRUE
);
2422 memorystatus_update_priority_locked(p
, priority
, head_insert
, FALSE
);
2428 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
2434 memorystatus_remove(proc_t p
, boolean_t locked
)
2437 memstat_bucket_t
*bucket
;
2438 boolean_t reschedule
= FALSE
;
2440 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
2446 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2448 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2450 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2452 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
);
2455 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2457 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
);
2465 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2466 uint64_t now
= mach_absolute_time();
2467 if (now
> p
->p_memstat_idle_start
) {
2468 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2472 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
2475 memorystatus_list_count
--;
2477 /* If awaiting demotion to the idle band, clean up */
2479 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2480 memorystatus_reschedule_idle_demotion_locked();
2483 memorystatus_check_levels_locked();
2486 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
2487 memorystatus_frozen_count
--;
2490 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
2491 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
2492 memorystatus_suspended_count
--;
2510 * Validate dirty tracking flags with process state.
2516 * The proc_list_lock is held by the caller.
2520 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
) {
2521 /* See that the process isn't marked for termination */
2522 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
2526 /* Idle exit requires that process be tracked */
2527 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
2528 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2532 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2533 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
2534 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2538 /* Deferral is only relevant if idle exit is specified */
2539 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
2540 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
2548 memorystatus_update_idle_priority_locked(proc_t p
) {
2551 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
2553 assert(isSysProc(p
));
2555 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2557 priority
= (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) ? system_procs_aging_band
: JETSAM_PRIORITY_IDLE
;
2559 priority
= p
->p_memstat_requestedpriority
;
2562 if (priority
!= p
->p_memstat_effectivepriority
) {
2564 if ((jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) &&
2565 (priority
== JETSAM_PRIORITY_IDLE
)) {
2568 * This process is on its way into the IDLE band. The system is
2569 * using 'legacy' jetsam aging policy. That means, this process
2570 * has already used up its idle-deferral aging time that is given
2571 * once per its lifetime. So we need to set the INACTIVE limits
2572 * explicitly because it won't be going through the demotion paths
2573 * that take care to apply the limits appropriately.
2575 memorystatus_update_priority_locked(p
, priority
, false, true);
2578 memorystatus_update_priority_locked(p
, priority
, false, false);
2584 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
2585 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2586 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2587 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2589 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2590 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2591 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2592 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2593 * band. The deferral can be cleared early by clearing the appropriate flag.
2595 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2596 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2597 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2601 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
) {
2602 unsigned int old_dirty
;
2603 boolean_t reschedule
= FALSE
;
2604 boolean_t already_deferred
= FALSE
;
2605 boolean_t defer_now
= FALSE
;
2608 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
2609 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
2613 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2615 * Process is on its way out.
2621 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2626 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
2631 old_dirty
= p
->p_memstat_dirty
;
2633 /* These bits are cumulative, as per <rdar://problem/11159924> */
2634 if (pcontrol
& PROC_DIRTY_TRACK
) {
2635 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
2638 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
2639 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
2642 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2643 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
2646 if (old_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2647 already_deferred
= TRUE
;
2651 /* This can be set and cleared exactly once. */
2652 if (pcontrol
& PROC_DIRTY_DEFER
) {
2654 if ( !(old_dirty
& P_DIRTY_DEFER
)) {
2655 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
2661 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2662 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
2663 defer_now
? "Y" : "N",
2664 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
2667 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
2668 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
2669 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2671 if (defer_now
&& !already_deferred
) {
2674 * Request to defer a clean process that's idle-exit enabled
2675 * and not already in the jetsam deferred band. Most likely a
2678 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2681 } else if (!defer_now
) {
2684 * The process isn't asking for the 'aging' facility.
2685 * Could be that it is:
2688 if (already_deferred
) {
2690 * already in the aging bands. Traditionally,
2691 * some processes have tried to use this to
2692 * opt out of the 'aging' facility.
2695 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2698 * agnostic to the 'aging' facility. In that case,
2699 * we'll go ahead and opt it in because this is likely
2700 * a new launch (clean process, dirty tracking enabled)
2703 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2712 * We are trying to operate on a dirty process. Dirty processes have to
2713 * be removed from the deferred band. The question is do we reset the
2714 * deferred state or not?
2716 * This could be a legal request like:
2717 * - this process had opted into the 'aging' band
2718 * - but it's now dirty and requests to opt out.
2719 * In this case, we remove the process from the band and reset its
2720 * state too. It'll opt back in properly when needed.
2722 * OR, this request could be a user-space bug. E.g.:
2723 * - this process had opted into the 'aging' band when clean
2724 * - and, then issues another request to again put it into the band except
2725 * this time the process is dirty.
2726 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
2727 * the deferred band with its state intact. So our request below is no-op.
2728 * But we do it here anyways for coverage.
2730 * memorystatus_update_idle_priority_locked()
2731 * single-mindedly treats a dirty process as "cannot be in the aging band".
2734 if (!defer_now
&& already_deferred
) {
2735 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2739 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2741 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2746 memorystatus_update_idle_priority_locked(p
);
2749 memorystatus_reschedule_idle_demotion_locked();
2761 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
) {
2763 boolean_t kill
= false;
2764 boolean_t reschedule
= FALSE
;
2765 boolean_t was_dirty
= FALSE
;
2766 boolean_t now_dirty
= FALSE
;
2768 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2769 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
2773 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2775 * Process is on its way out.
2781 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2786 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2789 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2790 /* Dirty tracking not enabled */
2792 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2794 * Process is set to be terminated and we're attempting to mark it dirty.
2795 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2799 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
2800 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
2801 /* Mark the process as having been dirtied at some point */
2802 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
2803 memorystatus_dirty_count
++;
2805 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
2806 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
2807 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2808 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2810 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2811 /* Kill previously terminated processes if set clean */
2814 p
->p_memstat_dirty
&= ~flag
;
2815 memorystatus_dirty_count
--;
2827 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2830 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
2831 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
2833 /* Manage idle exit deferral, if applied */
2834 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2837 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
2838 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
2840 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
2841 * in that band on it's way to IDLE.
2844 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2846 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2848 * The process will move from its aging band to its higher requested
2851 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2853 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2858 * Process is back from "dirty" to "clean".
2861 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) {
2862 if (mach_absolute_time() >= p
->p_memstat_idledeadline
) {
2864 * The process' deadline has expired. It currently
2865 * does not reside in any of the aging buckets.
2867 * It's on its way to the JETSAM_PRIORITY_IDLE
2868 * bucket via memorystatus_update_idle_priority_locked()
2871 * So all we need to do is reset all the state on the
2872 * process that's related to the aging bucket i.e.
2873 * the AGING_IN_PROGRESS flag and the timer deadline.
2876 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2880 * It still has some protection window left and so
2881 * we just re-arm the timer without modifying any
2882 * state on the process iff it still wants into that band.
2885 if (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2886 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
2892 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2898 memorystatus_update_idle_priority_locked(p
);
2900 if (memorystatus_highwater_enabled
) {
2901 boolean_t ledger_update_needed
= TRUE
;
2902 boolean_t use_active
;
2905 * We are in this path because this process transitioned between
2906 * dirty <--> clean state. Update the cached memory limits.
2909 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2913 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2915 ledger_update_needed
= TRUE
;
2918 * process is clean...but if it has opted into pressured-exit
2919 * we don't apply the INACTIVE limit till the process has aged
2920 * out and is entering the IDLE band.
2921 * See memorystatus_update_priority_locked() for that.
2924 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
2925 ledger_update_needed
= FALSE
;
2927 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2929 ledger_update_needed
= TRUE
;
2934 * Enforce the new limits by writing to the ledger.
2936 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
2937 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
2938 * We aren't traversing the jetsam bucket list here, so we should be safe.
2939 * See rdar://21394491.
2942 if (ledger_update_needed
&& proc_ref_locked(p
) == p
) {
2944 if (p
->p_memstat_memlimit
> 0) {
2945 ledger_limit
= p
->p_memstat_memlimit
;
2950 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, use_active
, is_fatal
);
2952 proc_rele_locked(p
);
2954 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
2955 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2956 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
2957 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2962 /* If the deferral state changed, reschedule the demotion timer */
2964 memorystatus_reschedule_idle_demotion_locked();
2969 if (proc_ref_locked(p
) == p
) {
2971 psignal(p
, SIGKILL
);
2973 proc_rele_locked(p
);
2984 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
) {
2988 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2990 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
2994 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2996 * Process is on its way out.
3002 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3007 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
3008 /* Dirty tracking not enabled */
3013 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
)) == 0) {
3018 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
3019 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
3022 /* This can be set and cleared exactly once. */
3023 if (pcontrol
& PROC_DIRTY_DEFER
) {
3025 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
3027 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER
;
3029 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3030 memorystatus_update_idle_priority_locked(p
);
3031 memorystatus_reschedule_idle_demotion_locked();
3043 memorystatus_dirty_get(proc_t p
) {
3048 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3049 ret
|= PROC_DIRTY_TRACKED
;
3050 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3051 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
3053 if (p
->p_memstat_dirty
& P_DIRTY
) {
3054 ret
|= PROC_DIRTY_IS_DIRTY
;
3056 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
3057 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
3067 memorystatus_on_terminate(proc_t p
) {
3072 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3074 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
3075 /* Clean; mark as terminated and issue SIGKILL */
3078 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3088 memorystatus_on_suspend(proc_t p
)
3092 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3096 p
->p_memstat_suspendedfootprint
= pages
;
3097 memorystatus_suspended_footprint_total
+= pages
;
3098 memorystatus_suspended_count
++;
3100 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
3105 memorystatus_on_resume(proc_t p
)
3115 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
3117 memorystatus_frozen_count
--;
3118 p
->p_memstat_state
|= P_MEMSTAT_PRIOR_THAW
;
3121 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
3122 memorystatus_suspended_count
--;
3127 p
->p_memstat_state
&= ~(P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
);
3133 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
3134 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3140 memorystatus_on_inactivity(proc_t p
)
3144 /* Wake the freeze thread */
3145 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
3150 * The proc_list_lock is held by the caller.
3153 memorystatus_build_state(proc_t p
) {
3154 uint32_t snapshot_state
= 0;
3157 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3158 snapshot_state
|= kMemorystatusSuspended
;
3160 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
3161 snapshot_state
|= kMemorystatusFrozen
;
3163 if (p
->p_memstat_state
& P_MEMSTAT_PRIOR_THAW
) {
3164 snapshot_state
|= kMemorystatusWasThawed
;
3168 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3169 snapshot_state
|= kMemorystatusTracked
;
3171 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3172 snapshot_state
|= kMemorystatusSupportsIdleExit
;
3174 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3175 snapshot_state
|= kMemorystatusDirty
;
3178 return snapshot_state
;
3184 kill_idle_exit_proc(void)
3186 proc_t p
, victim_p
= PROC_NULL
;
3187 uint64_t current_time
;
3188 boolean_t killed
= FALSE
;
3190 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3192 /* Pick next idle exit victim. */
3193 current_time
= mach_absolute_time();
3195 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_IDLE_EXIT
);
3196 if (jetsam_reason
== OS_REASON_NULL
) {
3197 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3202 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
3204 /* No need to look beyond the idle band */
3205 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
3209 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
|P_DIRTY_IS_DIRTY
|P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
3210 if (current_time
>= p
->p_memstat_idledeadline
) {
3211 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3212 victim_p
= proc_ref_locked(p
);
3217 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
3223 printf("memorystatus_thread: idle exiting pid %d [%s]\n", victim_p
->p_pid
, (*victim_p
->p_name
? victim_p
->p_name
: "(unknown)"));
3224 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
, jetsam_reason
);
3225 proc_rele(victim_p
);
3227 os_reason_free(jetsam_reason
);
3236 memorystatus_thread_wake(void) {
3237 thread_wakeup((event_t
)&memorystatus_wakeup
);
3239 #endif /* CONFIG_JETSAM */
3241 extern void vm_pressure_response(void);
3244 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
3247 assert_wait_timeout(&memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, 1000 * NSEC_PER_USEC
);
3249 assert_wait(&memorystatus_wakeup
, THREAD_UNINT
);
3252 return thread_block(continuation
);
3256 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
3258 static boolean_t is_vm_privileged
= FALSE
;
3261 boolean_t post_snapshot
= FALSE
;
3262 uint32_t errors
= 0;
3263 uint32_t hwm_kill
= 0;
3264 boolean_t sort_flag
= TRUE
;
3265 boolean_t corpse_list_purged
= FALSE
;
3267 /* Jetsam Loop Detection - locals */
3268 memstat_bucket_t
*bucket
;
3269 int jld_bucket_count
= 0;
3270 struct timeval jld_now_tstamp
= {0,0};
3271 uint64_t jld_now_msecs
= 0;
3272 int elevated_bucket_count
= 0;
3274 /* Jetsam Loop Detection - statics */
3275 static uint64_t jld_timestamp_msecs
= 0;
3276 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
3277 static int jld_idle_kills
= 0; /* Number of procs killed during eval period */
3278 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
3279 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3282 if (is_vm_privileged
== FALSE
) {
3284 * It's the first time the thread has run, so just mark the thread as privileged and block.
3285 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
3287 thread_wire(host_priv_self(), current_thread(), TRUE
);
3288 is_vm_privileged
= TRUE
;
3290 if (vm_restricted_to_single_processor
== TRUE
)
3291 thread_vm_bind_group_add();
3293 memorystatus_thread_block(0, memorystatus_thread
);
3298 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
3299 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
,0);
3302 * Jetsam aware version.
3304 * The VM pressure notification thread is working it's way through clients in parallel.
3306 * So, while the pressure notification thread is targeting processes in order of
3307 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
3308 * any processes that have exceeded their highwater mark.
3310 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
3311 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
3313 while (is_thrashing(kill_under_pressure_cause
) ||
3314 memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3318 uint64_t jetsam_reason_code
= JETSAM_REASON_INVALID
;
3319 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3321 cause
= kill_under_pressure_cause
;
3323 case kMemorystatusKilledFCThrashing
:
3324 jetsam_reason_code
= JETSAM_REASON_MEMORY_FCTHRASHING
;
3326 case kMemorystatusKilledVMThrashing
:
3327 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMTHRASHING
;
3329 case kMemorystatusKilledVMPageShortage
:
3332 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMPAGESHORTAGE
;
3333 cause
= kMemorystatusKilledVMPageShortage
;
3338 killed
= memorystatus_kill_hiwat_proc(&errors
);
3341 post_snapshot
= TRUE
;
3344 memorystatus_hwm_candidates
= FALSE
;
3347 /* No highwater processes to kill. Continue or stop for now? */
3348 if (!is_thrashing(kill_under_pressure_cause
) &&
3349 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
3351 * We are _not_ out of pressure but we are above the critical threshold and there's:
3352 * - no compressor thrashing
3353 * - no more HWM processes left.
3354 * For now, don't kill any other processes.
3357 if (hwm_kill
== 0) {
3358 memorystatus_thread_wasted_wakeup
++;
3364 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, jetsam_reason_code
);
3365 if (jetsam_reason
== OS_REASON_NULL
) {
3366 printf("memorystatus_thread: failed to allocate jetsam reason\n");
3369 if (memorystatus_jld_enabled
== TRUE
) {
3372 * Jetsam Loop Detection: attempt to detect
3373 * rapid daemon relaunches in the lower bands.
3376 microuptime(&jld_now_tstamp
);
3379 * Ignore usecs in this calculation.
3380 * msecs granularity is close enough.
3382 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
3385 switch (jetsam_aging_policy
) {
3386 case kJetsamAgingPolicyLegacy
:
3387 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3388 jld_bucket_count
= bucket
->count
;
3389 bucket
= &memstat_bucket
[JETSAM_PRIORITY_AGING_BAND1
];
3390 jld_bucket_count
+= bucket
->count
;
3392 case kJetsamAgingPolicySysProcsReclaimedFirst
:
3393 case kJetsamAgingPolicyAppsReclaimedFirst
:
3394 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3395 jld_bucket_count
= bucket
->count
;
3396 bucket
= &memstat_bucket
[system_procs_aging_band
];
3397 jld_bucket_count
+= bucket
->count
;
3398 bucket
= &memstat_bucket
[applications_aging_band
];
3399 jld_bucket_count
+= bucket
->count
;
3401 case kJetsamAgingPolicyNone
:
3403 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3404 jld_bucket_count
= bucket
->count
;
3408 bucket
= &memstat_bucket
[JETSAM_PRIORITY_ELEVATED_INACTIVE
];
3409 elevated_bucket_count
= bucket
->count
;
3414 * memorystatus_jld_eval_period_msecs is a tunable
3415 * memorystatus_jld_eval_aggressive_count is a tunable
3416 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
3418 if ( (jld_bucket_count
== 0) ||
3419 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
3422 * Refresh evaluation parameters
3424 jld_timestamp_msecs
= jld_now_msecs
;
3425 jld_idle_kill_candidates
= jld_bucket_count
;
3427 jld_eval_aggressive_count
= 0;
3428 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3431 if (jld_idle_kills
> jld_idle_kill_candidates
) {
3432 jld_eval_aggressive_count
++;
3434 #if DEVELOPMENT || DEBUG
3435 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
3436 jld_eval_aggressive_count
,
3437 jld_timestamp_msecs
,
3439 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
3440 jld_eval_aggressive_count
,
3441 jld_idle_kill_candidates
,
3443 #endif /* DEVELOPMENT || DEBUG */
3445 if ((jld_eval_aggressive_count
== memorystatus_jld_eval_aggressive_count
) &&
3446 (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3448 * If we reach this aggressive cycle, corpses might be causing memory pressure.
3449 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
3450 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
3452 task_purge_all_corpses();
3453 corpse_list_purged
= TRUE
;
3455 else if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
3457 * Bump up the jetsam priority limit (eg: the bucket index)
3458 * Enforce bucket index sanity.
3460 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
3461 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
3463 * Do nothing. Stick with the default level.
3466 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
3470 /* Visit elevated processes first */
3471 while (elevated_bucket_count
) {
3473 elevated_bucket_count
--;
3476 * memorystatus_kill_elevated_process() drops a reference,
3477 * so take another one so we can continue to use this exit reason
3478 * even after it returns.
3481 os_reason_ref(jetsam_reason
);
3482 killed
= memorystatus_kill_elevated_process(
3483 kMemorystatusKilledVMThrashing
,
3485 jld_eval_aggressive_count
,
3489 post_snapshot
= TRUE
;
3490 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3492 * Still under pressure.
3493 * Find another pinned processes.
3501 * No pinned processes left to kill.
3502 * Abandon elevated band.
3509 * memorystatus_kill_top_process_aggressive() drops a reference,
3510 * so take another one so we can continue to use this exit reason
3511 * even after it returns
3513 os_reason_ref(jetsam_reason
);
3514 killed
= memorystatus_kill_top_process_aggressive(
3516 kMemorystatusKilledVMThrashing
,
3518 jld_eval_aggressive_count
,
3519 jld_priority_band_max
,
3523 /* Always generate logs after aggressive kill */
3524 post_snapshot
= TRUE
;
3532 * memorystatus_kill_top_process() drops a reference,
3533 * so take another one so we can continue to use this exit reason
3534 * even after it returns
3536 os_reason_ref(jetsam_reason
);
3539 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, jetsam_reason
, &priority
, &errors
);
3544 * Don't generate logs for steady-state idle-exit kills,
3545 * unless it is overridden for debug or by the device
3548 if ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
) {
3549 post_snapshot
= TRUE
;
3552 /* Jetsam Loop Detection */
3553 if (memorystatus_jld_enabled
== TRUE
) {
3554 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
3558 * We've reached into bands beyond idle deferred.
3559 * We make no attempt to monitor them
3564 if ((priority
>= JETSAM_PRIORITY_UI_SUPPORT
) && (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3566 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
3567 * then we attempt to relieve pressure by purging corpse memory.
3569 task_purge_all_corpses();
3570 corpse_list_purged
= TRUE
;
3575 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3577 * Still under pressure and unable to kill a process - purge corpse memory
3579 if (total_corpses_count
> 0) {
3580 task_purge_all_corpses();
3581 corpse_list_purged
= TRUE
;
3584 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3586 * Still under pressure and unable to kill a process - panic
3588 panic("memorystatus_jetsam_thread: no victim! available pages:%d\n", memorystatus_available_pages
);
3595 * We do not want to over-kill when thrashing has been detected.
3596 * To avoid that, we reset the flag here and notify the
3599 if (is_thrashing(kill_under_pressure_cause
)) {
3600 kill_under_pressure_cause
= 0;
3601 vm_thrashing_jetsam_done();
3604 os_reason_free(jetsam_reason
);
3607 kill_under_pressure_cause
= 0;
3610 memorystatus_clear_errors();
3613 #if VM_PRESSURE_EVENTS
3615 * LD: We used to target the foreground process first and foremost here.
3616 * Now, we target all processes, starting from the non-suspended, background
3617 * processes first. We will target foreground too.
3619 * memorystatus_update_vm_pressure(TRUE);
3621 //vm_pressure_response();
3624 if (post_snapshot
) {
3626 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3627 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
3628 uint64_t timestamp_now
= mach_absolute_time();
3629 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3630 memorystatus_jetsam_snapshot
->js_gencount
++;
3631 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3632 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3634 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3637 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3645 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
3646 memorystatus_available_pages
, 0, 0, 0, 0);
3648 #else /* CONFIG_JETSAM */
3651 * Jetsam not enabled
3654 #endif /* CONFIG_JETSAM */
3656 memorystatus_thread_block(0, memorystatus_thread
);
3662 * when an idle-exitable proc was killed
3664 * when there are no more idle-exitable procs found
3665 * when the attempt to kill an idle-exitable proc failed
3667 boolean_t
memorystatus_idle_exit_from_VM(void) {
3668 return(kill_idle_exit_proc());
3670 #endif /* !CONFIG_JETSAM */
3673 * Callback invoked when allowable physical memory footprint exceeded
3674 * (dirty pages + IOKit mappings)
3676 * This is invoked for both advisory, non-fatal per-task high watermarks,
3677 * as well as the fatal task memory limits.
3680 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3682 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3684 proc_t p
= current_proc();
3686 #if VM_PRESSURE_EVENTS
3687 if (warning
== TRUE
) {
3689 * This is a warning path which implies that the current process is close, but has
3690 * not yet exceeded its per-process memory limit.
3692 if (memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, FALSE
/* not exceeded */) != TRUE
) {
3693 /* Print warning, since it's possible that task has not registered for pressure notifications */
3694 printf("task_exceeded_footprint: failed to warn the current task (%d exiting, or no handler registered?).\n", p
->p_pid
);
3698 #endif /* VM_PRESSURE_EVENTS */
3700 if (memlimit_is_fatal
) {
3702 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
3703 * has violated either the system-wide per-task memory limit OR its own task limit.
3705 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_PERPROCESSLIMIT
);
3706 if (jetsam_reason
== NULL
) {
3707 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
3708 } else if (corpse_for_fatal_memkill
!= 0) {
3709 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
3710 jetsam_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
3713 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
, jetsam_reason
) != TRUE
) {
3714 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
3718 * HWM offender exists. Done without locks or synchronization.
3719 * See comment near its declaration for more details.
3721 memorystatus_hwm_candidates
= TRUE
;
3723 #if VM_PRESSURE_EVENTS
3725 * The current process is not in the warning path.
3726 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
3727 * Failure to send note is ignored here.
3729 (void)memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, TRUE
/* exceeded */);
3731 #endif /* VM_PRESSURE_EVENTS */
3736 memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3738 proc_t p
= current_proc();
3741 * The limit violation is logged here, but only once per process per limit.
3742 * Soft memory limit is a non-fatal high-water-mark
3743 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
3746 printf("process %d (%s) exceeded physical memory footprint, the %s%sMemoryLimit of %d MB\n",
3747 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"), (memlimit_is_active
? "Active" : "Inactive"),
3748 (memlimit_is_fatal
? "Hard" : "Soft"), max_footprint_mb
);
3756 * Evaluates active vs. inactive process state.
3757 * Processes that opt into dirty tracking are evaluated
3758 * based on clean vs dirty state.
3760 * clean ==> inactive
3762 * Process that do not opt into dirty tracking are
3763 * evalulated based on priority level.
3764 * Foreground or above ==> active
3765 * Below Foreground ==> inactive
3767 * Return: TRUE if active
3772 proc_jetsam_state_is_active_locked(proc_t p
) {
3774 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3776 * process has opted into dirty tracking
3777 * active state is based on dirty vs. clean
3779 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3782 * implies active state
3788 * implies inactive state
3792 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
3794 * process is Foreground or higher
3795 * implies active state
3800 * process found below Foreground
3801 * implies inactive state
3808 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3812 uint32_t errors
= 0;
3814 if (victim_pid
== -1) {
3815 /* No pid, so kill first process */
3816 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, jetsam_reason
, NULL
, &errors
);
3818 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3822 memorystatus_clear_errors();
3826 /* Fire off snapshot notification */
3828 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3829 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
3830 uint64_t timestamp_now
= mach_absolute_time();
3831 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3832 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3833 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3835 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3838 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3845 #else /* !CONFIG_JETSAM */
3847 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3849 #endif /* CONFIG_JETSAM */
3855 * Jetsam a specific process.
3858 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3861 uint64_t killtime
= 0;
3863 clock_usec_t tv_usec
;
3866 /* TODO - add a victim queue and push this into the main jetsam thread */
3868 p
= proc_find(victim_pid
);
3870 os_reason_free(jetsam_reason
);
3877 if (memorystatus_jetsam_snapshot_count
== 0) {
3878 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3881 killtime
= mach_absolute_time();
3882 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3883 tv_msec
= tv_usec
/ 1000;
3885 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
3889 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3890 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3891 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, memorystatus_available_pages
);
3892 #else /* !CONFIG_JETSAM */
3895 killtime
= mach_absolute_time();
3896 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3897 tv_msec
= tv_usec
/ 1000;
3898 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d)\n",
3899 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3900 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
);
3901 #endif /* CONFIG_JETSAM */
3903 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
3911 * Toggle the P_MEMSTAT_TERMINATED state.
3912 * Takes the proc_list_lock.
3915 proc_memstat_terminated(proc_t p
, boolean_t set
)
3917 #if DEVELOPMENT || DEBUG
3921 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3923 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3928 #pragma unused(p, set)
3932 #endif /* DEVELOPMENT || DEBUG */
3939 * This is invoked when cpulimits have been exceeded while in fatal mode.
3940 * The jetsam_flags do not apply as those are for memory related kills.
3941 * We call this routine so that the offending process is killed with
3942 * a non-zero exit status.
3945 jetsam_on_ledger_cpulimit_exceeded(void)
3948 int jetsam_flags
= 0; /* make it obvious */
3949 proc_t p
= current_proc();
3950 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3952 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
3953 p
->p_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"));
3955 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_CPULIMIT
);
3956 if (jetsam_reason
== OS_REASON_NULL
) {
3957 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
3960 retval
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
3963 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
3968 memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
)
3973 *count
= get_task_memory_region_count(task
);
3977 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
3984 pages
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
3985 assert(((uint32_t)pages
) == pages
);
3986 *footprint
= (uint32_t)pages
;
3988 if (max_footprint
) {
3989 pages
= (get_task_phys_footprint_max(task
) / PAGE_SIZE_64
);
3990 assert(((uint32_t)pages
) == pages
);
3991 *max_footprint
= (uint32_t)pages
;
3993 if (max_footprint_lifetime
) {
3994 pages
= (get_task_resident_max(task
) / PAGE_SIZE_64
);
3995 assert(((uint32_t)pages
) == pages
);
3996 *max_footprint_lifetime
= (uint32_t)pages
;
3998 if (purgeable_pages
) {
3999 pages
= (get_task_purgeable_size(task
) / PAGE_SIZE_64
);
4000 assert(((uint32_t)pages
) == pages
);
4001 *purgeable_pages
= (uint32_t)pages
;
4006 memorystatus_get_task_phys_footprint_page_counts(task_t task
,
4007 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
4008 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
4009 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
4010 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
)
4014 if (internal_pages
) {
4015 *internal_pages
= (get_task_internal(task
) / PAGE_SIZE_64
);
4018 if (internal_compressed_pages
) {
4019 *internal_compressed_pages
= (get_task_internal_compressed(task
) / PAGE_SIZE_64
);
4022 if (purgeable_nonvolatile_pages
) {
4023 *purgeable_nonvolatile_pages
= (get_task_purgeable_nonvolatile(task
) / PAGE_SIZE_64
);
4026 if (purgeable_nonvolatile_compressed_pages
) {
4027 *purgeable_nonvolatile_compressed_pages
= (get_task_purgeable_nonvolatile_compressed(task
) / PAGE_SIZE_64
);
4030 if (alternate_accounting_pages
) {
4031 *alternate_accounting_pages
= (get_task_alternate_accounting(task
) / PAGE_SIZE_64
);
4034 if (alternate_accounting_compressed_pages
) {
4035 *alternate_accounting_compressed_pages
= (get_task_alternate_accounting_compressed(task
) / PAGE_SIZE_64
);
4038 if (iokit_mapped_pages
) {
4039 *iokit_mapped_pages
= (get_task_iokit_mapped(task
) / PAGE_SIZE_64
);
4042 if (page_table_pages
) {
4043 *page_table_pages
= (get_task_page_table(task
) / PAGE_SIZE_64
);
4048 * This routine only acts on the global jetsam event snapshot.
4049 * Updating the process's entry can race when the memorystatus_thread
4050 * has chosen to kill a process that is racing to exit on another core.
4053 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
)
4055 memorystatus_jetsam_snapshot_entry_t
*entry
= NULL
;
4056 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4057 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4061 if (memorystatus_jetsam_snapshot_count
== 0) {
4063 * No active snapshot.
4070 * Sanity check as this routine should only be called
4071 * from a jetsam kill path.
4073 assert(kill_cause
!= 0 && killtime
!= 0);
4075 snapshot
= memorystatus_jetsam_snapshot
;
4076 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4078 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
4079 if (snapshot_list
[i
].pid
== p
->p_pid
) {
4081 entry
= &snapshot_list
[i
];
4083 if (entry
->killed
|| entry
->jse_killtime
) {
4085 * We apparently raced on the exit path
4086 * for this process, as it's snapshot entry
4087 * has already recorded a kill.
4089 assert(entry
->killed
&& entry
->jse_killtime
);
4094 * Update the entry we just found in the snapshot.
4097 entry
->killed
= kill_cause
;
4098 entry
->jse_killtime
= killtime
;
4099 entry
->jse_gencount
= snapshot
->js_gencount
;
4100 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
;
4103 * If a process has moved between bands since snapshot was
4104 * initialized, then likely these fields changed too.
4106 if (entry
->priority
!= p
->p_memstat_effectivepriority
) {
4108 strlcpy(entry
->name
, p
->p_name
, sizeof(entry
->name
));
4109 entry
->priority
= p
->p_memstat_effectivepriority
;
4110 entry
->state
= memorystatus_build_state(p
);
4111 entry
->user_data
= p
->p_memstat_userdata
;
4112 entry
->fds
= p
->p_fd
->fd_nfiles
;
4116 * Always update the page counts on a kill.
4120 uint32_t max_pages
= 0;
4121 uint32_t max_pages_lifetime
= 0;
4122 uint32_t purgeable_pages
= 0;
4124 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4125 entry
->pages
= (uint64_t)pages
;
4126 entry
->max_pages
= (uint64_t)max_pages
;
4127 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4128 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4130 uint64_t internal_pages
= 0;
4131 uint64_t internal_compressed_pages
= 0;
4132 uint64_t purgeable_nonvolatile_pages
= 0;
4133 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4134 uint64_t alternate_accounting_pages
= 0;
4135 uint64_t alternate_accounting_compressed_pages
= 0;
4136 uint64_t iokit_mapped_pages
= 0;
4137 uint64_t page_table_pages
= 0;
4139 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4140 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4141 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4142 &iokit_mapped_pages
, &page_table_pages
);
4144 entry
->jse_internal_pages
= internal_pages
;
4145 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4146 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4147 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4148 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4149 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4150 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4151 entry
->jse_page_table_pages
= page_table_pages
;
4153 uint64_t region_count
= 0;
4154 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4155 entry
->jse_memory_region_count
= region_count
;
4161 if (entry
== NULL
) {
4163 * The entry was not found in the snapshot, so the process must have
4164 * launched after the snapshot was initialized.
4165 * Let's try to append the new entry.
4167 if (memorystatus_jetsam_snapshot_count
< memorystatus_jetsam_snapshot_max
) {
4169 * A populated snapshot buffer exists
4170 * and there is room to init a new entry.
4172 assert(memorystatus_jetsam_snapshot_count
== snapshot
->entry_count
);
4174 unsigned int next
= memorystatus_jetsam_snapshot_count
;
4176 if(memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[next
], (snapshot
->js_gencount
)) == TRUE
) {
4178 entry
= &snapshot_list
[next
];
4179 entry
->killed
= kill_cause
;
4180 entry
->jse_killtime
= killtime
;
4182 snapshot
->entry_count
= ++next
;
4183 memorystatus_jetsam_snapshot_count
= next
;
4185 if (memorystatus_jetsam_snapshot_count
>= memorystatus_jetsam_snapshot_max
) {
4187 * We just used the last slot in the snapshot buffer.
4188 * We only want to log it once... so we do it here
4189 * when we notice we've hit the max.
4191 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
4192 memorystatus_jetsam_snapshot_count
);
4199 if (entry
== NULL
) {
4201 * If we reach here, the snapshot buffer could not be updated.
4202 * Most likely, the buffer is full, in which case we would have
4203 * logged a warning in the previous call.
4205 * For now, we will stop appending snapshot entries.
4206 * When the buffer is consumed, the snapshot state will reset.
4209 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
4210 p
->p_pid
, p
->p_memstat_effectivepriority
, memorystatus_jetsam_snapshot_count
);
4216 void memorystatus_pages_update(unsigned int pages_avail
)
4218 memorystatus_available_pages
= pages_avail
;
4220 #if VM_PRESSURE_EVENTS
4222 * Since memorystatus_available_pages changes, we should
4223 * re-evaluate the pressure levels on the system and
4224 * check if we need to wake the pressure thread.
4225 * We also update memorystatus_level in that routine.
4227 vm_pressure_response();
4229 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
4231 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
4232 memorystatus_thread_wake();
4235 #else /* VM_PRESSURE_EVENTS */
4237 boolean_t critical
, delta
;
4239 if (!memorystatus_delta
) {
4243 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
4244 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
4245 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
4247 if (critical
|| delta
) {
4248 unsigned int total_pages
;
4250 total_pages
= (unsigned int) atop_64(max_mem
);
4251 #if CONFIG_SECLUDED_MEMORY
4252 total_pages
-= vm_page_secluded_count
;
4253 #endif /* CONFIG_SECLUDED_MEMORY */
4254 memorystatus_level
= memorystatus_available_pages
* 100 / total_pages
;
4255 memorystatus_thread_wake();
4257 #endif /* VM_PRESSURE_EVENTS */
4261 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
)
4264 clock_usec_t tv_usec
;
4266 uint32_t max_pages
= 0;
4267 uint32_t max_pages_lifetime
= 0;
4268 uint32_t purgeable_pages
= 0;
4269 uint64_t internal_pages
= 0;
4270 uint64_t internal_compressed_pages
= 0;
4271 uint64_t purgeable_nonvolatile_pages
= 0;
4272 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4273 uint64_t alternate_accounting_pages
= 0;
4274 uint64_t alternate_accounting_compressed_pages
= 0;
4275 uint64_t iokit_mapped_pages
= 0;
4276 uint64_t page_table_pages
=0;
4277 uint64_t region_count
= 0;
4278 uint64_t cids
[COALITION_NUM_TYPES
];
4280 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
4282 entry
->pid
= p
->p_pid
;
4283 strlcpy(&entry
->name
[0], p
->p_name
, sizeof(entry
->name
));
4284 entry
->priority
= p
->p_memstat_effectivepriority
;
4286 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4287 entry
->pages
= (uint64_t)pages
;
4288 entry
->max_pages
= (uint64_t)max_pages
;
4289 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4290 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4292 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4293 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4294 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4295 &iokit_mapped_pages
, &page_table_pages
);
4297 entry
->jse_internal_pages
= internal_pages
;
4298 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4299 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4300 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4301 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4302 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4303 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4304 entry
->jse_page_table_pages
= page_table_pages
;
4306 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4307 entry
->jse_memory_region_count
= region_count
;
4309 entry
->state
= memorystatus_build_state(p
);
4310 entry
->user_data
= p
->p_memstat_userdata
;
4311 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
4312 entry
->fds
= p
->p_fd
->fd_nfiles
;
4314 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
4315 entry
->cpu_time
.tv_sec
= tv_sec
;
4316 entry
->cpu_time
.tv_usec
= tv_usec
;
4318 assert(p
->p_stats
!= NULL
);
4319 entry
->jse_starttime
= p
->p_stats
->ps_start
; /* abstime process started */
4320 entry
->jse_killtime
= 0; /* abstime jetsam chose to kill process */
4321 entry
->killed
= 0; /* the jetsam kill cause */
4322 entry
->jse_gencount
= gencount
; /* indicates a pass through jetsam thread, when process was targeted to be killed */
4324 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
; /* Most recent timespan spent in idle-band */
4326 proc_coalitionids(p
, cids
);
4327 entry
->jse_coalition_jetsam_id
= cids
[COALITION_TYPE_JETSAM
];
4333 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
4335 kern_return_t kr
= KERN_SUCCESS
;
4336 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
4337 vm_statistics64_data_t vm_stat
;
4339 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
) != KERN_SUCCESS
)) {
4340 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
4341 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
4343 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
4344 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
4345 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
4346 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
4347 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
4348 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
4350 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
4351 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
4352 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
4353 snapshot
->stats
.compressions
= vm_stat
.compressions
;
4354 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
4355 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
4356 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
4361 * Collect vm statistics at boot.
4362 * Called only once (see kern_exec.c)
4363 * Data can be consumed at any time.
4366 memorystatus_init_at_boot_snapshot() {
4367 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
4368 memorystatus_at_boot_snapshot
.entry_count
= 0;
4369 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
4370 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
4374 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
4377 unsigned int b
= 0, i
= 0;
4379 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4380 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4381 unsigned int snapshot_max
= 0;
4385 * This is an on_demand snapshot
4387 snapshot
= od_snapshot
;
4388 snapshot_list
= od_snapshot
->entries
;
4389 snapshot_max
= ods_list_count
;
4392 * This is a jetsam event snapshot
4394 snapshot
= memorystatus_jetsam_snapshot
;
4395 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4396 snapshot_max
= memorystatus_jetsam_snapshot_max
;
4400 * Init the snapshot header information
4402 memorystatus_init_snapshot_vmstats(snapshot
);
4403 snapshot
->snapshot_time
= mach_absolute_time();
4404 snapshot
->notification_time
= 0;
4405 snapshot
->js_gencount
= 0;
4407 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
4410 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
4412 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
], snapshot
->js_gencount
)) {
4416 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",
4418 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],
4419 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]);
4421 if (++i
== snapshot_max
) {
4426 snapshot
->entry_count
= i
;
4429 /* update the system buffer count */
4430 memorystatus_jetsam_snapshot_count
= i
;
4434 #if DEVELOPMENT || DEBUG
4437 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
) {
4439 memorystatus_jetsam_panic_options_t debug
;
4441 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
4445 ret
= copyin(buffer
, &debug
, buffer_size
);
4450 /* Panic bits match kMemorystatusKilled* enum */
4451 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
4453 /* Copyout new value */
4454 debug
.data
= memorystatus_jetsam_panic_debug
;
4455 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
4461 * Triggers a sort_order on a specified jetsam priority band.
4462 * This is for testing only, used to force a path through the sort
4466 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
) {
4470 unsigned int bucket_index
= 0;
4472 if (priority
== -1) {
4473 /* Use as shorthand for default priority */
4474 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
4476 bucket_index
= (unsigned int)priority
;
4479 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
4484 #endif /* DEVELOPMENT || DEBUG */
4487 * Jetsam the first process in the queue.
4490 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
,
4491 int32_t *priority
, uint32_t *errors
)
4494 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4495 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4499 uint64_t killtime
= 0;
4501 clock_usec_t tv_usec
;
4504 #ifndef CONFIG_FREEZE
4508 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4509 memorystatus_available_pages
, 0, 0, 0, 0);
4512 if (sort_flag
== TRUE
) {
4513 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4518 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4520 #if DEVELOPMENT || DEBUG
4522 int procSuspendedForDiagnosis
;
4523 #endif /* DEVELOPMENT || DEBUG */
4526 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4528 #if DEVELOPMENT || DEBUG
4529 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4530 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4531 #endif /* DEVELOPMENT || DEBUG */
4534 aPid_ep
= p
->p_memstat_effectivepriority
;
4536 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4537 continue; /* with lock held */
4540 #if DEVELOPMENT || DEBUG
4541 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4542 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4545 #endif /* DEVELOPMENT || DEBUG */
4547 if (cause
== kMemorystatusKilledVnodes
)
4550 * If the system runs out of vnodes, we systematically jetsam
4551 * processes in hopes of stumbling onto a vnode gain that helps
4552 * the system recover. The process that happens to trigger
4553 * this path has no known relationship to the vnode consumption.
4554 * We attempt to safeguard that process e.g: do not jetsam it.
4557 if (p
== current_proc()) {
4558 /* do not jetsam the current process */
4565 boolean_t reclaim_proc
= !(p
->p_memstat_state
& (P_MEMSTAT_LOCKED
| P_MEMSTAT_NORECLAIM
));
4566 if (any
|| reclaim_proc
) {
4578 * Capture a snapshot if none exists and:
4579 * - priority was not requested (this is something other than an ambient kill)
4580 * - the priority was requested *and* the targeted process is not at idle priority
4582 if ((memorystatus_jetsam_snapshot_count
== 0) &&
4583 (memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (aPid_ep
!= JETSAM_PRIORITY_IDLE
))))) {
4584 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4585 new_snapshot
= TRUE
;
4589 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4590 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4591 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4592 * acquisition of the proc lock.
4594 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4596 killtime
= mach_absolute_time();
4597 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4598 tv_msec
= tv_usec
/ 1000;
4600 #if DEVELOPMENT || DEBUG
4601 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && activeProcess
) {
4602 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
4603 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_level
);
4604 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
4605 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
4606 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
4607 jetsam_diagnostic_suspended_one_active_proc
= 1;
4608 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
4611 p
= proc_ref_locked(p
);
4614 task_suspend(p
->task
);
4616 *priority
= aPid_ep
;
4624 #endif /* DEVELOPMENT || DEBUG */
4626 /* Shift queue, update stats */
4627 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4629 if (proc_ref_locked(p
) == p
) {
4631 printf("%lu.%02d memorystatus: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4632 (unsigned long)tv_sec
, tv_msec
,
4633 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing top process pid"),
4634 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4635 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4638 * memorystatus_do_kill() drops a reference, so take another one so we can
4639 * continue to use this exit reason even after memorystatus_do_kill()
4642 os_reason_ref(jetsam_reason
);
4644 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4649 *priority
= aPid_ep
;
4657 * Failure - first unwind the state,
4658 * then fall through to restart the search.
4661 proc_rele_locked(p
);
4662 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4663 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4668 * Failure - restart the search.
4670 * We might have raced with "p" exiting on another core, resulting in no
4671 * ref on "p". Or, we may have failed to kill "p".
4673 * Either way, we fall thru to here, leaving the proc in the
4674 * P_MEMSTAT_TERMINATED state.
4676 * And, we hold the the proc_list_lock at this point.
4680 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4688 os_reason_free(jetsam_reason
);
4690 /* Clear snapshot if freshly captured and no target was found */
4691 if (new_snapshot
&& !killed
) {
4693 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4697 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4698 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4704 * Jetsam aggressively
4707 memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
,
4708 int32_t priority_max
, uint32_t *errors
)
4711 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4712 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4715 int32_t aPid_ep
= 0;
4716 unsigned int memorystatus_level_snapshot
= 0;
4717 uint64_t killtime
= 0;
4719 clock_usec_t tv_usec
;
4724 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4725 memorystatus_available_pages
, priority_max
, 0, 0, 0);
4727 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4731 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4733 #if DEVELOPMENT || DEBUG
4735 int procSuspendedForDiagnosis
;
4736 #endif /* DEVELOPMENT || DEBUG */
4738 if ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
) {
4741 * We have raced with next_p running on another core, as it has
4742 * moved to a different jetsam priority band. This means we have
4743 * lost our place in line while traversing the jetsam list. We
4744 * attempt to recover by rewinding to the beginning of the band
4745 * we were already traversing. By doing this, we do not guarantee
4746 * that no process escapes this aggressive march, but we can make
4747 * skipping an entire range of processes less likely. (PR-21069019)
4750 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding %s moved from band %d --> %d\n",
4751 aggr_count
, (*next_p
->p_name
? next_p
->p_name
: "unknown"), i
, next_p
->p_memstat_effectivepriority
);
4753 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4758 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4760 if (p
->p_memstat_effectivepriority
> priority_max
) {
4762 * Bail out of this killing spree if we have
4763 * reached beyond the priority_max jetsam band.
4764 * That is, we kill up to and through the
4765 * priority_max jetsam band.
4771 #if DEVELOPMENT || DEBUG
4772 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4773 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4774 #endif /* DEVELOPMENT || DEBUG */
4777 aPid_ep
= p
->p_memstat_effectivepriority
;
4779 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4783 #if DEVELOPMENT || DEBUG
4784 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4785 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4788 #endif /* DEVELOPMENT || DEBUG */
4791 * Capture a snapshot if none exists.
4793 if (memorystatus_jetsam_snapshot_count
== 0) {
4794 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4795 new_snapshot
= TRUE
;
4799 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4800 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4801 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4802 * acquisition of the proc lock.
4804 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4806 killtime
= mach_absolute_time();
4807 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4808 tv_msec
= tv_usec
/ 1000;
4810 /* Shift queue, update stats */
4811 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4814 * In order to kill the target process, we will drop the proc_list_lock.
4815 * To guaranteee that p and next_p don't disappear out from under the lock,
4816 * we must take a ref on both.
4817 * If we cannot get a reference, then it's likely we've raced with
4818 * that process exiting on another core.
4820 if (proc_ref_locked(p
) == p
) {
4822 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
4826 * We must have raced with next_p exiting on another core.
4827 * Recover by getting the next eligible process in the band.
4830 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
4831 aggr_count
, next_p
->p_pid
, (*next_p
->p_name
? next_p
->p_name
: "(unknown)"));
4834 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
4839 printf("%lu.%01d memorystatus: aggressive%d: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4840 (unsigned long)tv_sec
, tv_msec
, aggr_count
,
4841 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing pid"),
4842 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4843 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4845 memorystatus_level_snapshot
= memorystatus_level
;
4848 * memorystatus_do_kill() drops a reference, so take another one so we can
4849 * continue to use this exit reason even after memorystatus_do_kill()
4852 os_reason_ref(jetsam_reason
);
4853 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4863 * Continue the killing spree.
4867 proc_rele_locked(next_p
);
4870 if (aPid_ep
== JETSAM_PRIORITY_FOREGROUND
&& memorystatus_aggressive_jetsam_lenient
== TRUE
) {
4871 if (memorystatus_level
> memorystatus_level_snapshot
&& ((memorystatus_level
- memorystatus_level_snapshot
) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD
)) {
4872 #if DEVELOPMENT || DEBUG
4873 printf("Disabling Lenient mode after one-time deployment.\n");
4874 #endif /* DEVELOPMENT || DEBUG */
4875 memorystatus_aggressive_jetsam_lenient
= FALSE
;
4884 * Failure - first unwind the state,
4885 * then fall through to restart the search.
4888 proc_rele_locked(p
);
4890 proc_rele_locked(next_p
);
4892 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4893 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4899 * Failure - restart the search at the beginning of
4900 * the band we were already traversing.
4902 * We might have raced with "p" exiting on another core, resulting in no
4903 * ref on "p". Or, we may have failed to kill "p".
4905 * Either way, we fall thru to here, leaving the proc in the
4906 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
4908 * And, we hold the the proc_list_lock at this point.
4911 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4917 os_reason_free(jetsam_reason
);
4919 /* Clear snapshot if freshly captured and no target was found */
4920 if (new_snapshot
&& (kill_count
== 0)) {
4921 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4924 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4925 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4927 if (kill_count
> 0) {
4936 memorystatus_kill_hiwat_proc(uint32_t *errors
)
4939 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4940 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4944 uint64_t killtime
= 0;
4946 clock_usec_t tv_usec
;
4948 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4949 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
4950 memorystatus_available_pages
, 0, 0, 0, 0);
4952 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_HIGHWATER
);
4953 if (jetsam_reason
== OS_REASON_NULL
) {
4954 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
4959 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4961 uint64_t footprint_in_bytes
= 0;
4962 uint64_t memlimit_in_bytes
= 0;
4966 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4969 aPid_ep
= p
->p_memstat_effectivepriority
;
4971 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4975 /* skip if no limit set */
4976 if (p
->p_memstat_memlimit
<= 0) {
4982 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
4983 * Background limits are described via the inactive limit slots.
4984 * Their fatal/non-fatal setting will drive whether or not to be
4985 * considered in this kill path.
4988 /* skip if a currently inapplicable limit is encountered */
4989 if ((p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_BACKGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
4993 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
4994 memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
4995 skip
= (footprint_in_bytes
<= memlimit_in_bytes
);
4997 #if DEVELOPMENT || DEBUG
4998 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
4999 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
5003 #endif /* DEVELOPMENT || DEBUG */
5007 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5018 #if DEVELOPMENT || DEBUG
5019 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5020 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing",
5021 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5022 (footprint_in_bytes
/ (1024ULL * 1024ULL)), /* converted bytes to MB */
5023 p
->p_memstat_memlimit
);
5024 #endif /* DEVELOPMENT || DEBUG */
5026 if (memorystatus_jetsam_snapshot_count
== 0) {
5027 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5028 new_snapshot
= TRUE
;
5031 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5033 killtime
= mach_absolute_time();
5034 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5035 tv_msec
= tv_usec
/ 1000;
5037 #if DEVELOPMENT || DEBUG
5038 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5039 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid
, memorystatus_available_pages
);
5040 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
5041 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
5043 p
= proc_ref_locked(p
);
5046 task_suspend(p
->task
);
5053 #endif /* DEVELOPMENT || DEBUG */
5055 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledHiwat
, killtime
);
5057 if (proc_ref_locked(p
) == p
) {
5060 printf("%lu.%02d memorystatus: jetsam killing pid %d [%s] (highwater %d) - memorystatus_available_pages: %d\n",
5061 (unsigned long)tv_sec
, tv_msec
, aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), aPid_ep
, memorystatus_available_pages
);
5064 * memorystatus_do_kill drops a reference, so take another one so we can
5065 * continue to use this exit reason even after memorystatus_do_kill()
5068 os_reason_ref(jetsam_reason
);
5070 killed
= memorystatus_do_kill(p
, kMemorystatusKilledHiwat
, jetsam_reason
);
5080 * Failure - first unwind the state,
5081 * then fall through to restart the search.
5084 proc_rele_locked(p
);
5085 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5086 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5091 * Failure - restart the search.
5093 * We might have raced with "p" exiting on another core, resulting in no
5094 * ref on "p". Or, we may have failed to kill "p".
5096 * Either way, we fall thru to here, leaving the proc in the
5097 * P_MEMSTAT_TERMINATED state.
5099 * And, we hold the the proc_list_lock at this point.
5103 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5111 os_reason_free(jetsam_reason
);
5113 /* Clear snapshot if freshly captured and no target was found */
5114 if (new_snapshot
&& !killed
) {
5116 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5120 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
5121 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5127 * Jetsam a process pinned in the elevated band.
5129 * Return: true -- at least one pinned process was jetsammed
5130 * false -- no pinned process was jetsammed
5133 memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
)
5136 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5137 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5139 unsigned int i
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
5141 uint64_t killtime
= 0;
5143 clock_usec_t tv_usec
;
5147 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5148 memorystatus_available_pages
, 0, 0, 0, 0);
5152 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5156 next_p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
5159 aPid_ep
= p
->p_memstat_effectivepriority
;
5162 * Only pick a process pinned in this elevated band
5164 if (!(p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
5168 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5173 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5178 #if DEVELOPMENT || DEBUG
5179 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
5181 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5182 memorystatus_available_pages
);
5183 #endif /* DEVELOPMENT || DEBUG */
5185 if (memorystatus_jetsam_snapshot_count
== 0) {
5186 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5187 new_snapshot
= TRUE
;
5190 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5192 killtime
= mach_absolute_time();
5193 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5194 tv_msec
= tv_usec
/ 1000;
5196 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5198 if (proc_ref_locked(p
) == p
) {
5202 printf("%lu.%01d memorystatus: elevated%d: jetsam killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
5203 (unsigned long)tv_sec
, tv_msec
,
5205 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5206 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
5209 * memorystatus_do_kill drops a reference, so take another one so we can
5210 * continue to use this exit reason even after memorystatus_do_kill()
5213 os_reason_ref(jetsam_reason
);
5214 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5224 * Failure - first unwind the state,
5225 * then fall through to restart the search.
5228 proc_rele_locked(p
);
5229 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5230 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5235 * Failure - restart the search.
5237 * We might have raced with "p" exiting on another core, resulting in no
5238 * ref on "p". Or, we may have failed to kill "p".
5240 * Either way, we fall thru to here, leaving the proc in the
5241 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
5243 * And, we hold the the proc_list_lock at this point.
5246 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5252 os_reason_free(jetsam_reason
);
5254 /* Clear snapshot if freshly captured and no target was found */
5255 if (new_snapshot
&& (kill_count
== 0)) {
5257 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5261 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5262 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5268 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
) {
5270 * TODO: allow a general async path
5272 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
5273 * add the appropriate exit reason code mapping.
5275 if ((victim_pid
!= -1) || (cause
!= kMemorystatusKilledVMPageShortage
&& cause
!= kMemorystatusKilledVMThrashing
&&
5276 cause
!= kMemorystatusKilledFCThrashing
)) {
5280 kill_under_pressure_cause
= cause
;
5281 memorystatus_thread_wake();
5286 memorystatus_kill_on_VM_page_shortage(boolean_t async
) {
5288 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
5290 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMPAGESHORTAGE
);
5291 if (jetsam_reason
== OS_REASON_NULL
) {
5292 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
5295 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
, jetsam_reason
);
5300 memorystatus_kill_on_VM_thrashing(boolean_t async
) {
5302 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing
);
5304 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMTHRASHING
);
5305 if (jetsam_reason
== OS_REASON_NULL
) {
5306 printf("memorystatus_kill_on_VM_thrashing -- sync: failed to allocate jetsam reason\n");
5309 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing
, jetsam_reason
);
5314 memorystatus_kill_on_FC_thrashing(boolean_t async
) {
5318 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
5320 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_FCTHRASHING
);
5321 if (jetsam_reason
== OS_REASON_NULL
) {
5322 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
5325 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
, jetsam_reason
);
5330 memorystatus_kill_on_vnode_limit(void) {
5331 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_VNODE
);
5332 if (jetsam_reason
== OS_REASON_NULL
) {
5333 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
5336 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
, jetsam_reason
);
5339 #endif /* CONFIG_JETSAM */
5343 __private_extern__
void
5344 memorystatus_freeze_init(void)
5346 kern_return_t result
;
5349 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
5350 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
5352 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
5354 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
5355 if (result
== KERN_SUCCESS
) {
5356 thread_deallocate(thread
);
5358 panic("Could not create memorystatus_freeze_thread");
5363 * Synchronously freeze the passed proc. Called with a reference to the proc held.
5365 * Returns EINVAL or the value returned by task_freeze().
5368 memorystatus_freeze_process_sync(proc_t p
)
5372 boolean_t memorystatus_freeze_swap_low
= FALSE
;
5374 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5375 memorystatus_available_pages
, 0, 0, 0, 0);
5377 lck_mtx_lock(&freezer_mutex
);
5383 if (memorystatus_freeze_enabled
== FALSE
) {
5387 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5391 if (memorystatus_freeze_update_throttle()) {
5392 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
5393 memorystatus_freeze_throttle_count
++;
5400 uint32_t purgeable
, wired
, clean
, dirty
, state
;
5401 uint32_t max_pages
, pages
, i
;
5405 state
= p
->p_memstat_state
;
5407 /* Ensure the process is eligible for freezing */
5408 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5413 /* Only freeze processes meeting our minimum resident page criteria */
5414 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5415 if (pages
< memorystatus_freeze_pages_min
) {
5420 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5422 unsigned int avail_swap_space
= 0; /* in pages. */
5425 * Freezer backed by the compressor and swap file(s)
5426 * while will hold compressed data.
5428 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5430 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5432 if (max_pages
< memorystatus_freeze_pages_min
) {
5438 * We only have the compressor without any swap.
5440 max_pages
= UINT32_MAX
- 1;
5443 /* Mark as locked temporarily to avoid kill */
5444 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5447 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5449 DTRACE_MEMORYSTATUS6(memorystatus_freeze
, proc_t
, p
, unsigned int, memorystatus_available_pages
, boolean_t
, purgeable
, unsigned int, wired
, uint32_t, clean
, uint32_t, dirty
);
5451 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
5452 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5453 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5454 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5457 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5459 if (ret
== KERN_SUCCESS
) {
5460 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5462 memorystatus_frozen_count
++;
5464 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5466 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5468 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5469 throttle_intervals
[i
].pageouts
+= dirty
;
5473 memorystatus_freeze_pageouts
+= dirty
;
5474 memorystatus_freeze_count
++;
5478 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5485 lck_mtx_unlock(&freezer_mutex
);
5486 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5487 memorystatus_available_pages
, aPid
, 0, 0, 0);
5493 memorystatus_freeze_top_process(boolean_t
*memorystatus_freeze_swap_low
)
5497 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5500 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5501 memorystatus_available_pages
, 0, 0, 0, 0);
5505 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5508 uint32_t purgeable
, wired
, clean
, dirty
;
5511 uint32_t max_pages
= 0;
5515 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5518 state
= p
->p_memstat_state
;
5520 /* Ensure the process is eligible for freezing */
5521 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5522 continue; // with lock held
5525 /* Only freeze processes meeting our minimum resident page criteria */
5526 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5527 if (pages
< memorystatus_freeze_pages_min
) {
5528 continue; // with lock held
5531 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5533 /* Ensure there's enough free space to freeze this process. */
5535 unsigned int avail_swap_space
= 0; /* in pages. */
5538 * Freezer backed by the compressor and swap file(s)
5539 * while will hold compressed data.
5541 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5543 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5545 if (max_pages
< memorystatus_freeze_pages_min
) {
5546 *memorystatus_freeze_swap_low
= TRUE
;
5552 * We only have the compressor pool.
5554 max_pages
= UINT32_MAX
- 1;
5557 /* Mark as locked temporarily to avoid kill */
5558 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5560 p
= proc_ref_locked(p
);
5566 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5568 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
5569 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5570 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5571 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5574 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5577 if (KERN_SUCCESS
== kr
) {
5578 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5580 memorystatus_frozen_count
++;
5582 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5584 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5586 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5587 throttle_intervals
[i
].pageouts
+= dirty
;
5591 memorystatus_freeze_pageouts
+= dirty
;
5592 memorystatus_freeze_count
++;
5596 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5598 /* Return KERN_SUCESS */
5612 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5613 memorystatus_available_pages
, aPid
, 0, 0, 0);
5618 static inline boolean_t
5619 memorystatus_can_freeze_processes(void)
5625 if (memorystatus_suspended_count
) {
5626 uint32_t average_resident_pages
, estimated_processes
;
5628 /* Estimate the number of suspended processes we can fit */
5629 average_resident_pages
= memorystatus_suspended_footprint_total
/ memorystatus_suspended_count
;
5630 estimated_processes
= memorystatus_suspended_count
+
5631 ((memorystatus_available_pages
- memorystatus_available_pages_critical
) / average_resident_pages
);
5633 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
5634 if (estimated_processes
<= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
) {
5635 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_LOW
;
5637 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
5640 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
5641 memorystatus_suspended_count
, average_resident_pages
, estimated_processes
);
5643 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
5658 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
5660 boolean_t can_freeze
= TRUE
;
5662 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
5663 after boot, and is generally is a no-op once we've reached steady state. */
5664 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
5668 /* Check minimum suspended process threshold. */
5669 if (!memorystatus_can_freeze_processes()) {
5672 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT
);
5674 if ( !VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5676 * In-core compressor used for freezing WITHOUT on-disk swap support.
5678 if (vm_compressor_low_on_space()) {
5679 if (*memorystatus_freeze_swap_low
) {
5680 *memorystatus_freeze_swap_low
= TRUE
;
5686 if (*memorystatus_freeze_swap_low
) {
5687 *memorystatus_freeze_swap_low
= FALSE
;
5694 * Freezing WITH on-disk swap support.
5696 * In-core compressor fronts the swap.
5698 if (vm_swap_low_on_space()) {
5699 if (*memorystatus_freeze_swap_low
) {
5700 *memorystatus_freeze_swap_low
= TRUE
;
5712 memorystatus_freeze_update_throttle_interval(mach_timespec_t
*ts
, struct throttle_interval_t
*interval
)
5714 unsigned int freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
5715 if (CMP_MACH_TIMESPEC(ts
, &interval
->ts
) >= 0) {
5716 if (!interval
->max_pageouts
) {
5717 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / (24 * 60)));
5719 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval
->mins
);
5721 interval
->ts
.tv_sec
= interval
->mins
* 60;
5722 interval
->ts
.tv_nsec
= 0;
5723 ADD_MACH_TIMESPEC(&interval
->ts
, ts
);
5724 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
5725 if (interval
->pageouts
> interval
->max_pageouts
) {
5726 interval
->pageouts
-= interval
->max_pageouts
;
5728 interval
->pageouts
= 0;
5730 interval
->throttle
= FALSE
;
5731 } else if (!interval
->throttle
&& interval
->pageouts
>= interval
->max_pageouts
) {
5732 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval
->mins
);
5733 interval
->throttle
= TRUE
;
5736 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
5737 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
5738 interval
->throttle
? "on" : "off");
5742 memorystatus_freeze_update_throttle(void)
5748 boolean_t throttled
= FALSE
;
5750 #if DEVELOPMENT || DEBUG
5751 if (!memorystatus_freeze_throttle_enabled
)
5755 clock_get_system_nanotime(&sec
, &nsec
);
5759 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
5761 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
5762 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
5763 * order to allow for bursts of activity.
5765 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5766 memorystatus_freeze_update_throttle_interval(&ts
, &throttle_intervals
[i
]);
5767 if (throttle_intervals
[i
].throttle
== TRUE
)
5775 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
5777 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
5779 lck_mtx_lock(&freezer_mutex
);
5780 if (memorystatus_freeze_enabled
) {
5781 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5782 /* Only freeze if we've not exceeded our pageout budgets.*/
5783 if (!memorystatus_freeze_update_throttle()) {
5784 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low
);
5786 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
5787 memorystatus_freeze_throttle_count
++; /* Throttled, update stats */
5791 lck_mtx_unlock(&freezer_mutex
);
5793 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
5794 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
5798 sysctl_memorystatus_do_fastwake_warmup_all SYSCTL_HANDLER_ARGS
5800 #pragma unused(oidp, req, arg1, arg2)
5802 /* Need to be root or have entitlement */
5803 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
5807 if (memorystatus_freeze_enabled
== FALSE
) {
5811 do_fastwake_warmup_all();
5816 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_do_fastwake_warmup_all
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
5817 0, 0, &sysctl_memorystatus_do_fastwake_warmup_all
, "I", "");
5819 #endif /* CONFIG_FREEZE */
5821 #if VM_PRESSURE_EVENTS
5823 #if CONFIG_MEMORYSTATUS
5826 memorystatus_send_note(int event_code
, void *data
, size_t data_length
) {
5828 struct kev_msg ev_msg
;
5830 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
5831 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
5832 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
5834 ev_msg
.event_code
= event_code
;
5836 ev_msg
.dv
[0].data_length
= data_length
;
5837 ev_msg
.dv
[0].data_ptr
= data
;
5838 ev_msg
.dv
[1].data_length
= 0;
5840 ret
= kev_post_msg(&ev_msg
);
5842 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
5849 memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t limit_exceeded
) {
5851 boolean_t ret
= FALSE
;
5852 boolean_t found_knote
= FALSE
;
5853 struct knote
*kn
= NULL
;
5854 int send_knote_count
= 0;
5857 * See comment in sysctl_memorystatus_vm_pressure_send.
5860 memorystatus_klist_lock();
5862 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
5863 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
5864 pid_t knote_pid
= knote_proc
->p_pid
;
5866 if (knote_pid
== pid
) {
5868 * By setting the "fflags" here, we are forcing
5869 * a process to deal with the case where it's
5870 * bumping up into its memory limits. If we don't
5871 * do this here, we will end up depending on the
5872 * system pressure snapshot evaluation in
5873 * filt_memorystatus().
5876 if (!limit_exceeded
) {
5879 * Processes on desktop are not expecting to handle a system-wide
5880 * critical or system-wide warning notification from this path.
5881 * Intentionally set only the unambiguous limit warning here.
5883 * If the limit is soft, however, limit this to one notification per
5884 * active/inactive limit (per each registered listener).
5887 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
5891 * Restrict proc_limit_warn notifications when
5892 * non-fatal (soft) limit is at play.
5895 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
5897 * Mark this knote for delivery.
5899 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5901 * And suppress it from future notifications.
5903 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
5907 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
5909 * Mark this knote for delivery.
5911 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5913 * And suppress it from future notifications.
5915 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
5921 * No restriction on proc_limit_warn notifications when
5922 * fatal (hard) limit is at play.
5924 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5930 * Send this notification when a process has exceeded a soft limit,
5933 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
5937 * Restrict critical notifications for soft limits.
5941 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
5943 * Suppress future proc_limit_critical notifications
5944 * for the active soft limit.
5946 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
5947 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
5952 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
5954 * Suppress future proc_limit_critical_notifications
5955 * for the inactive soft limit.
5957 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
5958 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
5964 * We should never be trying to send a critical notification for
5965 * a hard limit... the process would be killed before it could be
5968 panic("Caught sending pid %d a critical warning for a fatal limit.\n", pid
);
5976 if (send_knote_count
> 0) {
5977 KNOTE(&memorystatus_klist
, 0);
5982 memorystatus_klist_unlock();
5988 * Can only be set by the current task on itself.
5991 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
5993 boolean_t set_privilege
= FALSE
;
5995 * Need an entitlement check here?
5997 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
5998 set_privilege
= TRUE
;
5999 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
6000 set_privilege
= FALSE
;
6005 return (task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
));
6009 memorystatus_send_pressure_note(pid_t pid
) {
6010 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
6011 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
6015 memorystatus_send_low_swap_note(void) {
6017 struct knote
*kn
= NULL
;
6019 memorystatus_klist_lock();
6020 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6021 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
6022 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
6023 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
6024 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
6025 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
6026 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
6031 memorystatus_klist_unlock();
6035 memorystatus_bg_pressure_eligible(proc_t p
) {
6036 boolean_t eligible
= FALSE
;
6040 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
6042 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
6043 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
6053 memorystatus_is_foreground_locked(proc_t p
) {
6054 return ((p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
6055 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
));
6059 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
6060 * to access the p_memstat_dirty field.
6063 memorystatus_proc_is_dirty_unsafe(void *v
)
6068 proc_t p
= (proc_t
)v
;
6069 return (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) != 0;
6072 #endif /* CONFIG_MEMORYSTATUS */
6075 * Trigger levels to test the mechanism.
6076 * Can be used via a sysctl.
6078 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
6079 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
6080 #define TEST_PURGEABLE_TRIGGER_ONE 3
6081 #define TEST_PURGEABLE_TRIGGER_ALL 4
6082 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
6083 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
6085 boolean_t memorystatus_manual_testing_on
= FALSE
;
6086 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
6088 extern struct knote
*
6089 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
6092 * This value is the threshold that a process must meet to be considered for scavenging.
6094 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
6096 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
6099 #define VM_PRESSURE_DEBUG(cond, format, ...) \
6101 if (cond) { printf(format, ##__VA_ARGS__); } \
6104 #define VM_PRESSURE_DEBUG(cond, format, ...)
6107 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
6109 void memorystatus_on_pageout_scan_end(void) {
6116 * knote_pressure_level - to check if the knote is registered for this notification level.
6118 * task - task whose bits we'll be modifying
6120 * 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.
6122 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
6127 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
)
6129 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
6131 if (pressure_level_to_clear
&& task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
6133 task_clear_has_been_notified(task
, pressure_level_to_clear
);
6136 task_mark_has_been_notified(task
, pressure_level_to_set
);
6144 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
)
6146 struct knote
*kn
= NULL
;
6148 memorystatus_klist_lock();
6149 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6151 proc_t p
= PROC_NULL
;
6152 struct task
* t
= TASK_NULL
;
6154 p
= knote_get_kq(kn
)->kq_p
;
6156 if (p
!= proc_ref_locked(p
)) {
6163 t
= (struct task
*)(p
->task
);
6165 task_clear_has_been_notified(t
, pressure_level_to_clear
);
6170 memorystatus_klist_unlock();
6173 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
6176 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
);
6179 * Used by the vm_pressure_thread which is
6180 * signalled from within vm_pageout_scan().
6182 static void vm_dispatch_memory_pressure(void);
6183 void consider_vm_pressure_events(void);
6185 void consider_vm_pressure_events(void)
6187 vm_dispatch_memory_pressure();
6189 static void vm_dispatch_memory_pressure(void)
6191 memorystatus_update_vm_pressure(FALSE
);
6194 extern vm_pressure_level_t
6195 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
6198 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
)
6200 struct knote
*kn
= NULL
, *kn_max
= NULL
;
6201 uint64_t resident_max
= 0; /* MB */
6202 struct timeval curr_tstamp
= {0, 0};
6203 int elapsed_msecs
= 0;
6204 int selected_task_importance
= 0;
6205 static int pressure_snapshot
= -1;
6206 boolean_t pressure_increase
= FALSE
;
6208 if (pressure_snapshot
== -1) {
6212 pressure_snapshot
= level
;
6213 pressure_increase
= TRUE
;
6216 if (level
>= pressure_snapshot
) {
6217 pressure_increase
= TRUE
;
6219 pressure_increase
= FALSE
;
6222 pressure_snapshot
= level
;
6225 if (pressure_increase
== TRUE
) {
6227 * We'll start by considering the largest
6228 * unimportant task in our list.
6230 selected_task_importance
= INT_MAX
;
6233 * We'll start by considering the largest
6234 * important task in our list.
6236 selected_task_importance
= 0;
6239 microuptime(&curr_tstamp
);
6241 SLIST_FOREACH(kn
, candidate_list
, kn_selnext
) {
6243 uint64_t resident_size
= 0; /* MB */
6244 proc_t p
= PROC_NULL
;
6245 struct task
* t
= TASK_NULL
;
6246 int curr_task_importance
= 0;
6247 boolean_t consider_knote
= FALSE
;
6248 boolean_t privileged_listener
= FALSE
;
6250 p
= knote_get_kq(kn
)->kq_p
;
6252 if (p
!= proc_ref_locked(p
)) {
6259 #if CONFIG_MEMORYSTATUS
6260 if (target_foreground_process
== TRUE
&& !memorystatus_is_foreground_locked(p
)) {
6262 * Skip process not marked foreground.
6267 #endif /* CONFIG_MEMORYSTATUS */
6269 t
= (struct task
*)(p
->task
);
6271 timevalsub(&curr_tstamp
, &p
->vm_pressure_last_notify_tstamp
);
6272 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6274 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(level
);
6276 if ((kn
->kn_sfflags
& dispatch_level
) == 0) {
6281 #if CONFIG_MEMORYSTATUS
6282 if (target_foreground_process
== FALSE
&& !memorystatus_bg_pressure_eligible(p
)) {
6283 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p
->p_pid
);
6287 #endif /* CONFIG_MEMORYSTATUS */
6289 curr_task_importance
= task_importance_estimate(t
);
6292 * Privileged listeners are only considered in the multi-level pressure scheme
6293 * AND only if the pressure is increasing.
6297 if (task_has_been_notified(t
, level
) == FALSE
) {
6300 * Is this a privileged listener?
6302 if (task_low_mem_privileged_listener(t
, FALSE
, &privileged_listener
) == 0) {
6304 if (privileged_listener
) {
6314 } else if (level
== 0) {
6317 * Task wasn't notified when the pressure was increasing and so
6318 * no need to notify it that the pressure is decreasing.
6320 if ((task_has_been_notified(t
, kVMPressureWarning
) == FALSE
) && (task_has_been_notified(t
, kVMPressureCritical
) == FALSE
)) {
6327 * We don't want a small process to block large processes from
6328 * being notified again. <rdar://problem/7955532>
6330 resident_size
= (get_task_phys_footprint(t
))/(1024*1024ULL); /* MB */
6332 if (resident_size
>= VM_PRESSURE_MINIMUM_RSIZE
) {
6336 * Warning or Critical Pressure.
6338 if (pressure_increase
) {
6339 if ((curr_task_importance
< selected_task_importance
) ||
6340 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6343 * We have found a candidate process which is:
6344 * a) at a lower importance than the current selected process
6346 * b) has importance equal to that of the current selected process but is larger
6349 consider_knote
= TRUE
;
6352 if ((curr_task_importance
> selected_task_importance
) ||
6353 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6356 * We have found a candidate process which is:
6357 * a) at a higher importance than the current selected process
6359 * b) has importance equal to that of the current selected process but is larger
6362 consider_knote
= TRUE
;
6365 } else if (level
== 0) {
6367 * Pressure back to normal.
6369 if ((curr_task_importance
> selected_task_importance
) ||
6370 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6372 consider_knote
= TRUE
;
6376 if (consider_knote
) {
6377 resident_max
= resident_size
;
6379 selected_task_importance
= curr_task_importance
;
6380 consider_knote
= FALSE
; /* reset for the next candidate */
6383 /* There was no candidate with enough resident memory to scavenge */
6384 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p
->p_pid
, resident_size
);
6391 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);
6392 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
);
6398 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
6399 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6400 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6402 uint64_t next_warning_notification_sent_at_ts
= 0;
6403 uint64_t next_critical_notification_sent_at_ts
= 0;
6406 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
6408 struct knote
*kn_max
= NULL
;
6409 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
6410 pid_t target_pid
= -1;
6411 struct klist dispatch_klist
= { NULL
};
6412 proc_t target_proc
= PROC_NULL
;
6413 struct task
*task
= NULL
;
6414 boolean_t found_candidate
= FALSE
;
6416 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
6417 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
6418 boolean_t smoothing_window_started
= FALSE
;
6419 struct timeval smoothing_window_start_tstamp
= {0, 0};
6420 struct timeval curr_tstamp
= {0, 0};
6421 int elapsed_msecs
= 0;
6422 uint64_t curr_ts
= mach_absolute_time();
6425 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
6427 int idle_kill_counter
= 0;
6430 * On desktop we take this opportunity to free up memory pressure
6431 * by immediately killing idle exitable processes. We use a delay
6432 * to avoid overkill. And we impose a max counter as a fail safe
6433 * in case daemons re-launch too fast.
6435 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
6436 if (memorystatus_idle_exit_from_VM() == FALSE
) {
6437 /* No idle exitable processes left to kill */
6440 idle_kill_counter
++;
6442 if (memorystatus_manual_testing_on
== TRUE
) {
6444 * Skip the delay when testing
6445 * the pressure notification scheme.
6448 delay(1000000); /* 1 second */
6451 #endif /* !CONFIG_JETSAM */
6453 if (level_snapshot
!= kVMPressureNormal
) {
6456 * Check to see if we are still in the 'resting' period
6457 * after having notified all clients interested in
6458 * a particular pressure level.
6461 level_snapshot
= memorystatus_vm_pressure_level
;
6463 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6465 if (curr_ts
< next_warning_notification_sent_at_ts
) {
6466 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6467 return KERN_SUCCESS
;
6469 } else if (level_snapshot
== kVMPressureCritical
) {
6471 if (curr_ts
< next_critical_notification_sent_at_ts
) {
6472 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6473 return KERN_SUCCESS
;
6481 * There is a race window here. But it's not clear
6482 * how much we benefit from having extra synchronization.
6484 level_snapshot
= memorystatus_vm_pressure_level
;
6486 if (prev_level_snapshot
> level_snapshot
) {
6488 * Pressure decreased? Let's take a little breather
6489 * and see if this condition stays.
6491 if (smoothing_window_started
== FALSE
) {
6493 smoothing_window_started
= TRUE
;
6494 microuptime(&smoothing_window_start_tstamp
);
6497 microuptime(&curr_tstamp
);
6498 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
6499 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6501 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
6503 delay(INTER_NOTIFICATION_DELAY
);
6508 prev_level_snapshot
= level_snapshot
;
6509 smoothing_window_started
= FALSE
;
6511 memorystatus_klist_lock();
6512 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
6514 if (kn_max
== NULL
) {
6515 memorystatus_klist_unlock();
6518 * No more level-based clients to notify.
6520 * Start the 'resting' window within which clients will not be re-notified.
6523 if (level_snapshot
!= kVMPressureNormal
) {
6524 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6525 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6526 next_warning_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6528 memorystatus_klist_reset_all_for_level(kVMPressureWarning
);
6531 if (level_snapshot
== kVMPressureCritical
) {
6532 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6533 next_critical_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6535 memorystatus_klist_reset_all_for_level(kVMPressureCritical
);
6538 return KERN_FAILURE
;
6541 target_proc
= knote_get_kq(kn_max
)->kq_p
;
6544 if (target_proc
!= proc_ref_locked(target_proc
)) {
6545 target_proc
= PROC_NULL
;
6547 memorystatus_klist_unlock();
6552 target_pid
= target_proc
->p_pid
;
6554 task
= (struct task
*)(target_proc
->task
);
6556 if (level_snapshot
!= kVMPressureNormal
) {
6558 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6560 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, 0, kVMPressureWarning
) == TRUE
) {
6561 found_candidate
= TRUE
;
6564 if (level_snapshot
== kVMPressureCritical
) {
6566 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, 0, kVMPressureCritical
) == TRUE
) {
6567 found_candidate
= TRUE
;
6572 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6574 task_clear_has_been_notified(task
, kVMPressureWarning
);
6575 task_clear_has_been_notified(task
, kVMPressureCritical
);
6577 found_candidate
= TRUE
;
6581 if (found_candidate
== FALSE
) {
6582 proc_rele(target_proc
);
6583 memorystatus_klist_unlock();
6587 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
6589 int knote_pressure_level
= convert_internal_pressure_level_to_dispatch_level(level_snapshot
);
6591 if (is_knote_registered_modify_task_pressure_bits(kn_cur
, knote_pressure_level
, task
, 0, level_snapshot
) == TRUE
) {
6592 proc_t knote_proc
= knote_get_kq(kn_cur
)->kq_p
;
6593 pid_t knote_pid
= knote_proc
->p_pid
;
6594 if (knote_pid
== target_pid
) {
6595 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
6596 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
6601 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
6603 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
6604 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
6605 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
6608 memorystatus_klist_unlock();
6610 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
6611 proc_rele(target_proc
);
6613 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
6617 if (memorystatus_manual_testing_on
== TRUE
) {
6619 * Testing out the pressure notification scheme.
6620 * No need for delays etc.
6624 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
6626 unsigned int page_delta
= 0;
6627 unsigned int skip_delay_page_threshold
= 0;
6629 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
6631 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
6632 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
6634 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
6636 * We are nearing the critcal mark fast and can't afford to wait between
6641 #endif /* CONFIG_JETSAM */
6643 if (sleep_interval
) {
6644 delay(sleep_interval
);
6649 return KERN_SUCCESS
;
6653 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
6655 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6657 switch (internal_pressure_level
) {
6659 case kVMPressureNormal
:
6661 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6665 case kVMPressureWarning
:
6666 case kVMPressureUrgent
:
6668 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
6672 case kVMPressureCritical
:
6674 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
6682 return dispatch_level
;
6686 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
6688 #pragma unused(arg1, arg2, oidp)
6689 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
6691 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
6694 #if DEBUG || DEVELOPMENT
6696 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
,
6697 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6699 #else /* DEBUG || DEVELOPMENT */
6701 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6702 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6704 #endif /* DEBUG || DEVELOPMENT */
6706 extern int memorystatus_purge_on_warning
;
6707 extern int memorystatus_purge_on_critical
;
6710 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
6712 #pragma unused(arg1, arg2)
6716 int pressure_level
= 0;
6717 int trigger_request
= 0;
6720 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
6721 if (error
|| !req
->newptr
) {
6725 memorystatus_manual_testing_on
= TRUE
;
6727 trigger_request
= (level
>> 16) & 0xFFFF;
6728 pressure_level
= (level
& 0xFFFF);
6730 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
6731 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
6734 switch (pressure_level
) {
6735 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
6736 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
6737 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
6744 * The pressure level is being set from user-space.
6745 * And user-space uses the constants in sys/event.h
6746 * So we translate those events to our internal levels here.
6748 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6750 memorystatus_manual_testing_level
= kVMPressureNormal
;
6753 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
6755 memorystatus_manual_testing_level
= kVMPressureWarning
;
6756 force_purge
= memorystatus_purge_on_warning
;
6758 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
6760 memorystatus_manual_testing_level
= kVMPressureCritical
;
6761 force_purge
= memorystatus_purge_on_critical
;
6764 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
6766 /* purge according to the new pressure level */
6767 switch (trigger_request
) {
6768 case TEST_PURGEABLE_TRIGGER_ONE
:
6769 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
6770 if (force_purge
== 0) {
6771 /* no purging requested */
6774 vm_purgeable_object_purge_one_unlocked(force_purge
);
6776 case TEST_PURGEABLE_TRIGGER_ALL
:
6777 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
6778 if (force_purge
== 0) {
6779 /* no purging requested */
6782 while (vm_purgeable_object_purge_one_unlocked(force_purge
));
6786 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
6787 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
6789 memorystatus_update_vm_pressure(TRUE
);
6792 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
6793 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
6795 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
6800 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6801 memorystatus_manual_testing_on
= FALSE
;
6807 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6808 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
6811 extern int memorystatus_purge_on_warning
;
6812 extern int memorystatus_purge_on_urgent
;
6813 extern int memorystatus_purge_on_critical
;
6815 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_warning
, 0, "");
6816 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_urgent
, 0, "");
6817 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_critical
, 0, "");
6820 #endif /* VM_PRESSURE_EVENTS */
6822 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
6824 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
6826 uint32_t list_count
, i
= 0;
6827 memorystatus_priority_entry_t
*list_entry
;
6830 list_count
= memorystatus_list_count
;
6831 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
6833 /* Just a size check? */
6838 /* Otherwise, validate the size of the buffer */
6839 if (*buffer_size
< *list_size
) {
6843 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
6848 memset(*list_ptr
, 0, *list_size
);
6850 *buffer_size
= *list_size
;
6853 list_entry
= *list_ptr
;
6857 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6858 while (p
&& (*list_size
< *buffer_size
)) {
6859 list_entry
->pid
= p
->p_pid
;
6860 list_entry
->priority
= p
->p_memstat_effectivepriority
;
6861 list_entry
->user_data
= p
->p_memstat_userdata
;
6864 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
6865 * Background limits are described via the inactive limit slots.
6866 * So, here, the cached limit should always be valid.
6869 if (p
->p_memstat_memlimit
<= 0) {
6870 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
6872 list_entry
->limit
= p
->p_memstat_memlimit
;
6875 list_entry
->state
= memorystatus_build_state(p
);
6878 *list_size
+= sizeof(memorystatus_priority_entry_t
);
6880 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6885 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
6891 memorystatus_cmd_get_priority_list(user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
6893 boolean_t size_only
;
6894 memorystatus_priority_entry_t
*list
= NULL
;
6897 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
6899 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
6905 error
= copyout(list
, buffer
, list_size
);
6909 *retval
= list_size
;
6914 kfree(list
, buffer_size
);
6923 memorystatus_clear_errors(void)
6928 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
6932 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6934 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
6935 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
6937 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6942 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
6946 memorystatus_update_levels_locked(boolean_t critical_only
) {
6948 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
6951 * If there's an entry in the first bucket, we have idle processes.
6954 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
6955 if (first_bucket
->count
) {
6956 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
6958 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6960 * The critical threshold must never exceed the pressure threshold
6962 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6966 #if DEBUG || DEVELOPMENT
6967 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6968 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6970 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6972 * The critical threshold must never exceed the pressure threshold
6974 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6979 if (memorystatus_jetsam_policy
& kPolicyMoreFree
) {
6980 memorystatus_available_pages_critical
+= memorystatus_policy_more_free_offset_pages
;
6983 if (critical_only
) {
6987 #if VM_PRESSURE_EVENTS
6988 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
6989 #if DEBUG || DEVELOPMENT
6990 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6991 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6998 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
7000 #pragma unused(arg1, arg2, oidp)
7001 int error
= 0, more_free
= 0;
7004 * TODO: Enable this privilege check?
7006 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
7011 error
= sysctl_handle_int(oidp
, &more_free
, 0, req
);
7012 if (error
|| !req
->newptr
)
7015 if ((more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == kPolicyMoreFree
)) ||
7016 (!more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == 0))) {
7019 * No change in state.
7027 memorystatus_jetsam_policy
|= kPolicyMoreFree
;
7029 memorystatus_jetsam_policy
&= ~kPolicyMoreFree
;
7032 memorystatus_update_levels_locked(TRUE
);
7038 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_policy_more_free
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
7039 0, 0, &sysctl_kern_memorystatus_policy_more_free
, "I", "");
7042 * Get the at_boot snapshot
7045 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7046 size_t input_size
= *snapshot_size
;
7049 * The at_boot snapshot has no entry list.
7051 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
7058 * Validate the size of the snapshot buffer
7060 if (input_size
< *snapshot_size
) {
7065 * Update the notification_time only
7067 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
7068 *snapshot
= &memorystatus_at_boot_snapshot
;
7070 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
7071 (long)input_size
, (long)*snapshot_size
, 0);
7076 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7077 size_t input_size
= *snapshot_size
;
7078 uint32_t ods_list_count
= memorystatus_list_count
;
7079 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
7081 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
7088 * Validate the size of the snapshot buffer.
7089 * This is inherently racey. May want to revisit
7090 * this error condition and trim the output when
7093 if (input_size
< *snapshot_size
) {
7098 * Allocate and initialize a snapshot buffer.
7100 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
7105 memset(ods
, 0, *snapshot_size
);
7108 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
7112 * Return the kernel allocated, on_demand buffer.
7113 * The caller of this routine will copy the data out
7114 * to user space and then free the kernel allocated
7119 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7120 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
7126 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7127 size_t input_size
= *snapshot_size
;
7129 if (memorystatus_jetsam_snapshot_count
> 0) {
7130 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
7139 if (input_size
< *snapshot_size
) {
7143 *snapshot
= memorystatus_jetsam_snapshot
;
7145 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7146 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
7153 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
7155 boolean_t size_only
;
7156 boolean_t is_default_snapshot
= FALSE
;
7157 boolean_t is_on_demand_snapshot
= FALSE
;
7158 boolean_t is_at_boot_snapshot
= FALSE
;
7159 memorystatus_jetsam_snapshot_t
*snapshot
;
7161 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
7165 is_default_snapshot
= TRUE
;
7166 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
7168 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7170 * Unsupported bit set in flag.
7175 if ((flags
& (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) ==
7176 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7178 * Can't have both set at the same time.
7183 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
7184 is_on_demand_snapshot
= TRUE
;
7186 * When not requesting the size only, the following call will allocate
7187 * an on_demand snapshot buffer, which is freed below.
7189 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
7191 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
7192 is_at_boot_snapshot
= TRUE
;
7193 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
7196 * Invalid flag setting.
7207 * Copy the data out to user space and clear the snapshot buffer.
7208 * If working with the jetsam snapshot,
7209 * clearing the buffer means, reset the count.
7210 * If working with an on_demand snapshot
7211 * clearing the buffer means, free it.
7212 * If working with the at_boot snapshot
7213 * there is nothing to clear or update.
7216 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
7217 if (is_default_snapshot
) {
7219 * The jetsam snapshot is never freed, its count is simply reset.
7222 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
7223 memorystatus_jetsam_snapshot_last_timestamp
= 0;
7228 if (is_on_demand_snapshot
) {
7230 * The on_demand snapshot is always freed,
7231 * even if the copyout failed.
7234 kfree(snapshot
, buffer_size
);
7240 *retval
= buffer_size
;
7247 * Routine: memorystatus_cmd_grp_set_properties
7248 * Purpose: Update properties for a group of processes.
7250 * Supported Properties:
7252 * Move each process out of its effective priority
7253 * band and into a new priority band.
7254 * Maintains relative order from lowest to highest priority.
7255 * In single band, maintains relative order from head to tail.
7257 * eg: before [effectivepriority | pid]
7259 * [17 | p55, p67, p19 ]
7264 * after [ new band | pid]
7265 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7267 * Returns: 0 on success, else non-zero.
7269 * Caveat: We know there is a race window regarding recycled pids.
7270 * A process could be killed before the kernel can act on it here.
7271 * If a pid cannot be found in any of the jetsam priority bands,
7272 * then we simply ignore it. No harm.
7273 * But, if the pid has been recycled then it could be an issue.
7274 * In that scenario, we might move an unsuspecting process to the new
7275 * priority band. It's not clear how the kernel can safeguard
7276 * against this, but it would be an extremely rare case anyway.
7277 * The caller of this api might avoid such race conditions by
7278 * ensuring that the processes passed in the pid list are suspended.
7282 /* This internal structure can expand when we add support for more properties */
7283 typedef struct memorystatus_internal_properties
7286 int32_t priority
; /* see memorytstatus_priority_entry_t : priority */
7287 } memorystatus_internal_properties_t
;
7291 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7293 #pragma unused (flags)
7296 * We only handle setting priority
7301 memorystatus_priority_entry_t
*entries
= NULL
;
7302 uint32_t entry_count
= 0;
7304 /* This will be the ordered proc list */
7305 memorystatus_internal_properties_t
*table
= NULL
;
7306 size_t table_size
= 0;
7307 uint32_t table_count
= 0;
7310 uint32_t bucket_index
= 0;
7311 boolean_t head_insert
;
7312 int32_t new_priority
;
7317 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0) || ((buffer_size
% sizeof(memorystatus_priority_entry_t
)) != 0)) {
7322 entry_count
= (buffer_size
/ sizeof(memorystatus_priority_entry_t
));
7323 if ((entries
= (memorystatus_priority_entry_t
*)kalloc(buffer_size
)) == NULL
) {
7328 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_START
, entry_count
, 0, 0, 0, 0);
7330 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
7334 /* Verify sanity of input priorities */
7335 for (i
=0; i
< entry_count
; i
++) {
7336 if (entries
[i
].priority
== -1) {
7337 /* Use as shorthand for default priority */
7338 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
7339 } else if ((entries
[i
].priority
== system_procs_aging_band
) || (entries
[i
].priority
== applications_aging_band
)) {
7340 /* Both the aging bands are reserved for internal use;
7341 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
7342 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
7343 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7344 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7346 /* Deal with this later */
7347 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
7354 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
7355 if ( (table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
7359 memset(table
, 0, table_size
);
7363 * For each jetsam bucket entry, spin through the input property list.
7364 * When a matching pid is found, populate an adjacent table with the
7365 * appropriate proc pointer and new property values.
7366 * This traversal automatically preserves order from lowest
7367 * to highest priority.
7374 /* Create the ordered table */
7375 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
7376 while (p
&& (table_count
< entry_count
)) {
7377 for (i
=0; i
< entry_count
; i
++ ) {
7378 if (p
->p_pid
== entries
[i
].pid
) {
7379 /* Build the table data */
7380 table
[table_count
].proc
= p
;
7381 table
[table_count
].priority
= entries
[i
].priority
;
7386 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
7389 /* We now have ordered list of procs ready to move */
7390 for (i
=0; i
< table_count
; i
++) {
7394 /* Allow head inserts -- but relative order is now */
7395 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7396 new_priority
= JETSAM_PRIORITY_IDLE
;
7399 new_priority
= table
[i
].priority
;
7400 head_insert
= false;
7404 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7409 * Take appropriate steps if moving proc out of
7410 * either of the aging bands.
7412 if ((p
->p_memstat_effectivepriority
== system_procs_aging_band
) || (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
7413 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7416 memorystatus_update_priority_locked(p
, new_priority
, head_insert
, false);
7422 * if (table_count != entry_count)
7423 * then some pids were not found in a jetsam band.
7424 * harmless but interesting...
7426 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_END
, entry_count
, table_count
, 0, 0, 0);
7430 kfree(entries
, buffer_size
);
7432 kfree(table
, table_size
);
7439 * This routine is used to update a process's jetsam priority position and stored user_data.
7440 * It is not used for the setting of memory limits, which is why the last 6 args to the
7441 * memorystatus_update() call are 0 or FALSE.
7445 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7447 memorystatus_priority_properties_t mpp_entry
;
7449 /* Validate inputs */
7450 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
7454 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
7464 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7469 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
, FALSE
);
7477 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7479 memorystatus_memlimit_properties_t mmp_entry
;
7481 /* Validate inputs */
7482 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7486 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
7489 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
7496 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7497 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7498 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
7499 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7500 * to the task's ledgers via task_set_phys_footprint_limit().
7503 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7505 memorystatus_memlimit_properties_t mmp_entry
;
7507 /* Validate inputs */
7508 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7512 memset (&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
7514 proc_t p
= proc_find(pid
);
7520 * Get the active limit and attributes.
7521 * No locks taken since we hold a reference to the proc.
7524 if (p
->p_memstat_memlimit_active
> 0 ) {
7525 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
7527 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
7530 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
7531 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7535 * Get the inactive limit and attributes
7537 if (p
->p_memstat_memlimit_inactive
<= 0) {
7538 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
7540 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
7542 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
7543 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7547 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
7554 * SPI for kbd - pr24956468
7555 * This is a very simple snapshot that calculates how much a
7556 * process's phys_footprint exceeds a specific memory limit.
7557 * Only the inactive memory limit is supported for now.
7558 * The delta is returned as bytes in excess or zero.
7561 memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7563 uint64_t footprint_in_bytes
= 0;
7564 uint64_t delta_in_bytes
= 0;
7565 int32_t memlimit_mb
= 0;
7566 uint64_t memlimit_bytes
= 0;
7568 /* Validate inputs */
7569 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(uint64_t)) || (flags
!= 0)) {
7573 proc_t p
= proc_find(pid
);
7579 * Get the inactive limit.
7580 * No locks taken since we hold a reference to the proc.
7583 if (p
->p_memstat_memlimit_inactive
<= 0) {
7584 task_convert_phys_footprint_limit(-1, &memlimit_mb
);
7586 memlimit_mb
= p
->p_memstat_memlimit_inactive
;
7589 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
7593 memlimit_bytes
= memlimit_mb
* 1024 * 1024; /* MB to bytes */
7596 * Computed delta always returns >= 0 bytes
7598 if (footprint_in_bytes
> memlimit_bytes
) {
7599 delta_in_bytes
= footprint_in_bytes
- memlimit_bytes
;
7602 error
= copyout(&delta_in_bytes
, buffer
, sizeof(delta_in_bytes
));
7609 memorystatus_cmd_get_pressure_status(int32_t *retval
) {
7612 /* Need privilege for check */
7613 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
7618 /* Inherently racy, so it's not worth taking a lock here */
7619 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7625 memorystatus_get_pressure_status_kdp() {
7626 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7630 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
7632 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
7633 * So, with 2-level HWM preserving previous behavior will map as follows.
7634 * - treat the limit passed in as both an active and inactive limit.
7635 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
7637 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
7638 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
7639 * - so mapping is (active/non-fatal, inactive/non-fatal)
7641 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
7642 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
7643 * - so mapping is (active/fatal, inactive/fatal)
7647 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
) {
7649 memorystatus_memlimit_properties_t entry
;
7651 entry
.memlimit_active
= high_water_mark
;
7652 entry
.memlimit_active_attr
= 0;
7653 entry
.memlimit_inactive
= high_water_mark
;
7654 entry
.memlimit_inactive_attr
= 0;
7656 if (is_fatal_limit
== TRUE
) {
7657 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7658 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7661 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
7666 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
) {
7668 int32_t memlimit_active
;
7669 boolean_t memlimit_active_is_fatal
;
7670 int32_t memlimit_inactive
;
7671 boolean_t memlimit_inactive_is_fatal
;
7672 uint32_t valid_attrs
= 0;
7675 proc_t p
= proc_find(pid
);
7681 * Check for valid attribute flags.
7683 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
7684 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
7688 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
7694 * Setup the active memlimit properties
7696 memlimit_active
= entry
->memlimit_active
;
7697 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7698 memlimit_active_is_fatal
= TRUE
;
7700 memlimit_active_is_fatal
= FALSE
;
7704 * Setup the inactive memlimit properties
7706 memlimit_inactive
= entry
->memlimit_inactive
;
7707 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7708 memlimit_inactive_is_fatal
= TRUE
;
7710 memlimit_inactive_is_fatal
= FALSE
;
7714 * Setting a limit of <= 0 implies that the process has no
7715 * high-water-mark and has no per-task-limit. That means
7716 * the system_wide task limit is in place, which by the way,
7720 if (memlimit_active
<= 0) {
7722 * Enforce the fatal system_wide task limit while process is active.
7724 memlimit_active
= -1;
7725 memlimit_active_is_fatal
= TRUE
;
7728 if (memlimit_inactive
<= 0) {
7730 * Enforce the fatal system_wide task limit while process is inactive.
7732 memlimit_inactive
= -1;
7733 memlimit_inactive_is_fatal
= TRUE
;
7739 * Store the active limit variants in the proc.
7741 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
7744 * Store the inactive limit variants in the proc.
7746 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
7749 * Enforce appropriate limit variant by updating the cached values
7750 * and writing the ledger.
7751 * Limit choice is based on process active/inactive state.
7754 if (memorystatus_highwater_enabled
) {
7756 boolean_t use_active
;
7758 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
7759 * Background limits are described via the inactive limit slots.
7762 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
7763 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
7766 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
7770 /* Enforce the limit by writing to the ledgers */
7771 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
;
7773 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
7774 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
7775 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
7776 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
7777 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit
, proc_t
, p
, int32_t, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1));
7787 * Returns the jetsam priority (effective or requested) of the process
7788 * associated with this task.
7791 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
7794 if (effective_priority
) {
7795 return p
->p_memstat_effectivepriority
;
7797 return p
->p_memstat_requestedpriority
;
7803 #endif /* CONFIG_JETSAM */
7806 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
) {
7808 os_reason_t jetsam_reason
= OS_REASON_NULL
;
7812 #pragma unused(jetsam_reason)
7815 /* Need to be root or have entitlement */
7816 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
7823 * Do not enforce it for snapshots.
7825 if (args
->command
!= MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
) {
7826 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
7832 switch (args
->command
) {
7833 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
7834 error
= memorystatus_cmd_get_priority_list(args
->buffer
, args
->buffersize
, ret
);
7837 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
7838 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7840 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
7841 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7843 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
7844 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7846 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS
:
7847 error
= memorystatus_cmd_get_memlimit_excess_np(args
->pid
, args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7849 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
7850 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7852 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
7853 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7855 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
7856 error
= memorystatus_cmd_get_pressure_status(ret
);
7858 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
7860 * This call does not distinguish between active and inactive limits.
7861 * Default behavior in 2-level HWM world is to set both.
7862 * Non-fatal limit is also assumed for both.
7864 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
7866 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
7868 * This call does not distinguish between active and inactive limits.
7869 * Default behavior in 2-level HWM world is to set both.
7870 * Fatal limit is also assumed for both.
7872 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
7875 #if DEVELOPMENT || DEBUG
7876 case MEMORYSTATUS_CMD_TEST_JETSAM
:
7877 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_GENERIC
);
7878 if (jetsam_reason
== OS_REASON_NULL
) {
7879 printf("memorystatus_control: failed to allocate jetsam reason\n");
7882 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
, jetsam_reason
) ? 0 : EINVAL
;
7884 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
7885 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
7887 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
7888 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
7890 #else /* DEVELOPMENT || DEBUG */
7891 #pragma unused(jetsam_reason)
7892 #endif /* DEVELOPMENT || DEBUG */
7893 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE
:
7894 if (memorystatus_aggressive_jetsam_lenient_allowed
== FALSE
) {
7895 #if DEVELOPMENT || DEBUG
7896 printf("Enabling Lenient Mode\n");
7897 #endif /* DEVELOPMENT || DEBUG */
7899 memorystatus_aggressive_jetsam_lenient_allowed
= TRUE
;
7900 memorystatus_aggressive_jetsam_lenient
= TRUE
;
7904 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE
:
7905 #if DEVELOPMENT || DEBUG
7906 printf("Disabling Lenient mode\n");
7907 #endif /* DEVELOPMENT || DEBUG */
7908 memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
7909 memorystatus_aggressive_jetsam_lenient
= FALSE
;
7912 #endif /* CONFIG_JETSAM */
7913 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
7914 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
7915 error
= memorystatus_low_mem_privileged_listener(args
->command
);
7919 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
:
7920 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
:
7921 error
= memorystatus_update_inactive_jetsam_priority_band(args
->pid
, args
->command
, args
->flags
? TRUE
: FALSE
);
7923 #endif /* CONFIG_JETSAM */
7935 filt_memorystatusattach(struct knote
*kn
)
7939 kn
->kn_flags
|= EV_CLEAR
;
7940 error
= memorystatus_knote_register(kn
);
7942 kn
->kn_flags
= EV_ERROR
;
7943 kn
->kn_data
= error
;
7949 filt_memorystatusdetach(struct knote
*kn
)
7951 memorystatus_knote_unregister(kn
);
7955 filt_memorystatus(struct knote
*kn __unused
, long hint
)
7959 case kMemorystatusNoPressure
:
7960 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
7961 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
7964 case kMemorystatusPressure
:
7965 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
7966 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
7967 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
7969 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
7971 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
7972 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
7976 case kMemorystatusLowSwap
:
7977 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
7978 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
7982 case kMemorystatusProcLimitWarn
:
7983 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
7984 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7988 case kMemorystatusProcLimitCritical
:
7989 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
7990 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
8000 if (kn
->kn_fflags
!= 0) {
8001 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
8002 pid_t knote_pid
= knote_proc
->p_pid
;
8004 printf("filt_memorystatus: sending kn 0x%lx (event 0x%x) for pid (%d)\n",
8005 (unsigned long)kn
, kn
->kn_fflags
, knote_pid
);
8009 return (kn
->kn_fflags
!= 0);
8013 filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
8016 int prev_kn_sfflags
= 0;
8018 memorystatus_klist_lock();
8021 * copy in new kevent settings
8022 * (saving the "desired" data and fflags).
8025 prev_kn_sfflags
= kn
->kn_sfflags
;
8026 kn
->kn_sfflags
= (kev
->fflags
& EVFILT_MEMORYSTATUS_ALL_MASK
);
8029 * Only on desktop do we restrict notifications to
8030 * one per active/inactive state (soft limits only).
8032 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8034 * Is there previous state to preserve?
8036 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8038 * This knote was previously interested in proc_limit_warn,
8039 * so yes, preserve previous state.
8041 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
8042 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8044 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
8045 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8049 * This knote was not previously interested in proc_limit_warn,
8050 * but it is now. Set both states.
8052 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8053 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8057 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8059 * Is there previous state to preserve?
8061 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8063 * This knote was previously interested in proc_limit_critical,
8064 * so yes, preserve previous state.
8066 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
8067 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8069 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
8070 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8074 * This knote was not previously interested in proc_limit_critical,
8075 * but it is now. Set both states.
8077 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8078 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8082 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
8083 kn
->kn_udata
= kev
->udata
;
8086 * reset the output flags based on a
8087 * combination of the old events and
8088 * the new desired event list.
8090 //kn->kn_fflags &= kn->kn_sfflags;
8092 res
= (kn
->kn_fflags
!= 0);
8094 memorystatus_klist_unlock();
8100 filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
8102 #pragma unused(data)
8105 memorystatus_klist_lock();
8106 res
= (kn
->kn_fflags
!= 0);
8108 *kev
= kn
->kn_kevent
;
8109 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
8113 memorystatus_klist_unlock();
8119 memorystatus_klist_lock(void) {
8120 lck_mtx_lock(&memorystatus_klist_mutex
);
8124 memorystatus_klist_unlock(void) {
8125 lck_mtx_unlock(&memorystatus_klist_mutex
);
8129 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
) {
8130 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
8131 klist_init(&memorystatus_klist
);
8135 memorystatus_knote_register(struct knote
*kn
) {
8138 memorystatus_klist_lock();
8141 * Support only userspace visible flags.
8143 if ((kn
->kn_sfflags
& EVFILT_MEMORYSTATUS_ALL_MASK
) == kn
->kn_sfflags
) {
8145 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8146 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8147 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8150 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8151 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8152 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8155 KNOTE_ATTACH(&memorystatus_klist
, kn
);
8161 memorystatus_klist_unlock();
8167 memorystatus_knote_unregister(struct knote
*kn __unused
) {
8168 memorystatus_klist_lock();
8169 KNOTE_DETACH(&memorystatus_klist
, kn
);
8170 memorystatus_klist_unlock();
8175 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
8177 memorystatus_issue_pressure_kevent(boolean_t pressured
) {
8178 memorystatus_klist_lock();
8179 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
8180 memorystatus_klist_unlock();
8183 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
8187 /* Coalition support */
8189 /* sorting info for a particular priority bucket */
8190 typedef struct memstat_sort_info
{
8191 coalition_t msi_coal
;
8192 uint64_t msi_page_count
;
8195 } memstat_sort_info_t
;
8198 * qsort from smallest page count to largest page count
8200 * return < 0 for a < b
8204 static int memstat_asc_cmp(const void *a
, const void *b
)
8206 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
8207 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
8209 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
8213 * Return the number of pids rearranged during this sort.
8216 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
8218 #define MAX_SORT_PIDS 80
8219 #define MAX_COAL_LEADERS 10
8221 unsigned int b
= bucket_index
;
8225 coalition_t coal
= COALITION_NULL
;
8227 int total_pids_moved
= 0;
8231 * The system is typically under memory pressure when in this
8232 * path, hence, we want to avoid dynamic memory allocation.
8234 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
8235 pid_t pid_list
[MAX_SORT_PIDS
];
8237 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8242 * Clear the array that holds coalition leader information
8244 for (i
=0; i
< MAX_COAL_LEADERS
; i
++) {
8245 leaders
[i
].msi_coal
= COALITION_NULL
;
8246 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
8247 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
8248 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
8251 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8253 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
8254 if (nleaders
< MAX_COAL_LEADERS
) {
8255 int coal_ntasks
= 0;
8256 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
8257 leaders
[nleaders
].msi_coal
= coal
;
8258 leaders
[nleaders
].msi_page_count
= coal_page_count
;
8259 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
8260 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
8264 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8265 * Abandoned coalitions will linger at the tail of the priority band
8266 * when this sort session ends.
8267 * TODO: should this be an assert?
8269 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
8270 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
8274 p
=memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8277 if (nleaders
== 0) {
8278 /* Nothing to sort */
8283 * Sort the coalition leader array, from smallest coalition page count
8284 * to largest coalition page count. When inserted in the priority bucket,
8285 * smallest coalition is handled first, resulting in the last to be jetsammed.
8288 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
8292 for (i
= 0; i
< nleaders
; i
++) {
8293 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8294 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
8295 leaders
[i
].msi_ntasks
);
8300 * During coalition sorting, processes in a priority band are rearranged
8301 * by being re-inserted at the head of the queue. So, when handling a
8302 * list, the first process that gets moved to the head of the queue,
8303 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8305 * So, for example, the coalition leader is expected to jetsam last,
8306 * after its coalition members. Therefore, the coalition leader is
8307 * inserted at the head of the queue first.
8309 * After processing a coalition, the jetsam order is as follows:
8310 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8314 * Coalition members are rearranged in the priority bucket here,
8315 * based on their coalition role.
8317 total_pids_moved
= 0;
8318 for (i
=0; i
< nleaders
; i
++) {
8320 /* a bit of bookkeeping */
8323 /* Coalition leaders are jetsammed last, so move into place first */
8324 pid_list
[0] = leaders
[i
].msi_pid
;
8325 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
8327 /* xpc services should jetsam after extensions */
8328 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
8329 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8332 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8333 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8336 /* extensions should jetsam after unmarked processes */
8337 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
8338 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8341 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8342 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8345 /* undefined coalition members should be the first to jetsam */
8346 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
8347 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8350 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8351 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8355 if (pids_moved
== leaders
[i
].msi_ntasks
) {
8357 * All the pids in the coalition were found in this band.
8359 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
8360 pids_moved
, leaders
[i
].msi_ntasks
);
8361 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
8363 * Apparently new coalition members showed up during the sort?
8365 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
8366 pids_moved
, leaders
[i
].msi_ntasks
);
8369 * Apparently not all the pids in the coalition were found in this band?
8371 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
8372 pids_moved
, leaders
[i
].msi_ntasks
);
8376 total_pids_moved
+= pids_moved
;
8380 return(total_pids_moved
);
8385 * Traverse a list of pids, searching for each within the priority band provided.
8386 * If pid is found, move it to the front of the priority band.
8387 * Never searches outside the priority band provided.
8390 * bucket_index - jetsam priority band.
8391 * pid_list - pointer to a list of pids.
8392 * list_sz - number of pids in the list.
8394 * Pid list ordering is important in that,
8395 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8396 * The sort_order is set by the coalition default.
8399 * the number of pids found and hence moved within the priority band.
8402 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
8404 memstat_bucket_t
*current_bucket
;
8408 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
8412 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8416 current_bucket
= &memstat_bucket
[bucket_index
];
8417 for (i
=0; i
< list_sz
; i
++) {
8418 unsigned int b
= bucket_index
;
8420 proc_t aProc
= NULL
;
8424 list_index
= ((list_sz
- 1) - i
);
8425 aPid
= pid_list
[list_index
];
8427 /* never search beyond bucket_index provided */
8428 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8430 if (p
->p_pid
== aPid
) {
8434 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8437 if (aProc
== NULL
) {
8438 /* pid not found in this band, just skip it */
8441 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
8442 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
8448 #endif /* CONFIG_JETSAM */