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 * We use this flag to signal if we have any HWM offenders
640 * on the system. This way we can reduce the number of wakeups
641 * of the memorystatus_thread when the system is between the
642 * "pressure" and "critical" threshold.
644 * The (re-)setting of this variable is done without any locks
645 * or synchronization simply because it is not possible (currently)
646 * to keep track of HWM offenders that drop down below their memory
647 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
648 * by allowing the unguarded modification of this variable.
650 boolean_t memorystatus_hwm_candidates
= 0;
652 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
653 #endif /* CONFIG_MEMORYSTATUS */
655 #endif /* VM_PRESSURE_EVENTS */
658 #if DEVELOPMENT || DEBUG
660 lck_grp_attr_t
*disconnect_page_mappings_lck_grp_attr
;
661 lck_grp_t
*disconnect_page_mappings_lck_grp
;
662 static lck_mtx_t disconnect_page_mappings_mutex
;
671 boolean_t memorystatus_freeze_enabled
= FALSE
;
672 int memorystatus_freeze_wakeup
= 0;
674 lck_grp_attr_t
*freezer_lck_grp_attr
;
675 lck_grp_t
*freezer_lck_grp
;
676 static lck_mtx_t freezer_mutex
;
678 static inline boolean_t
memorystatus_can_freeze_processes(void);
679 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
681 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
684 static unsigned int memorystatus_freeze_threshold
= 0;
686 static unsigned int memorystatus_freeze_pages_min
= 0;
687 static unsigned int memorystatus_freeze_pages_max
= 0;
689 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
691 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
694 static uint64_t memorystatus_freeze_count
= 0;
695 static uint64_t memorystatus_freeze_pageouts
= 0;
698 static throttle_interval_t throttle_intervals
[] = {
699 { 60, 8, 0, 0, { 0, 0 }, FALSE
}, /* 1 hour intermediate interval, 8x burst */
700 { 24 * 60, 1, 0, 0, { 0, 0 }, FALSE
}, /* 24 hour long interval, no burst */
703 static uint64_t memorystatus_freeze_throttle_count
= 0;
705 static unsigned int memorystatus_suspended_footprint_total
= 0; /* pages */
707 extern uint64_t vm_swap_get_free_space(void);
709 static boolean_t
memorystatus_freeze_update_throttle();
711 #endif /* CONFIG_FREEZE */
715 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
717 #if DEVELOPMENT || DEBUG
719 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
722 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index
)
726 int ledger_limit
= 0;
727 unsigned int b
= bucket_index
;
728 boolean_t traverse_all_buckets
= FALSE
;
730 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
731 traverse_all_buckets
= TRUE
;
734 traverse_all_buckets
= FALSE
;
739 * footprint reported in [pages / MB ]
740 * limits reported as:
741 * L-limit proc's Ledger limit
742 * C-limit proc's Cached limit, should match Ledger
743 * A-limit proc's Active limit
744 * IA-limit proc's Inactive limit
745 * F==Fatal, NF==NonFatal
748 printf("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64
);
749 printf("bucket [pid] [pages / MB] [state] [EP / RP] dirty deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
750 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
752 bytes
= get_task_phys_footprint(p
->task
);
753 task_get_phys_footprint_limit(p
->task
, &ledger_limit
);
754 printf("%2d [%5d] [%5lld /%3lldMB] 0x%-8x [%2d / %2d] 0x%-3x %10lld [%3d / %3d%s / %3d%s / %3d%s] %s\n",
756 (bytes
/ PAGE_SIZE_64
), /* task's footprint converted from bytes to pages */
757 (bytes
/ (1024ULL * 1024ULL)), /* task's footprint converted from bytes to MB */
758 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
760 p
->p_memstat_memlimit
,
761 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
762 p
->p_memstat_memlimit_active
,
763 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
764 p
->p_memstat_memlimit_inactive
,
765 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
766 (*p
->p_name
? p
->p_name
: "unknown"));
767 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
769 printf("memorystatus_debug_dump ***END***\n");
773 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
775 #pragma unused(oidp, arg2)
776 int bucket_index
= 0;
778 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
779 if (error
|| !req
->newptr
) {
782 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
783 if (error
|| !req
->newptr
) {
786 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
788 * All jetsam buckets will be dumped.
792 * Only a single bucket will be dumped.
797 memorystatus_debug_dump_bucket_locked(bucket_index
);
799 memorystatus_debug_dump_this_bucket
= bucket_index
;
804 * Debug aid to look at jetsam buckets and proc jetsam fields.
805 * Use this sysctl to act on a particular jetsam bucket.
806 * Writing the sysctl triggers the dump.
807 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
810 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", "");
813 /* Debug aid to aid determination of limit */
816 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
818 #pragma unused(oidp, arg2)
821 int error
, enable
= 0;
822 boolean_t use_active
; /* use the active limit and active limit attributes */
825 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
826 if (error
|| !req
->newptr
) {
830 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
831 if (error
|| !req
->newptr
) {
835 if (!(enable
== 0 || enable
== 1)) {
841 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
843 use_active
= proc_jetsam_state_is_active_locked(p
);
847 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
848 * Background limits are described via the inactive limit slots.
851 if (use_active
== TRUE
) {
852 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
854 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
859 * Disabling limits does not touch the stored variants.
860 * Set the cached limit fields to system_wide defaults.
862 p
->p_memstat_memlimit
= -1;
863 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
868 * Enforce the cached limit by writing to the ledger.
870 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
872 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
875 memorystatus_highwater_enabled
= enable
;
883 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
885 #if VM_PRESSURE_EVENTS
888 * This routine is used for targeted notifications regardless of system memory pressure
889 * and regardless of whether or not the process has already been notified.
890 * It bypasses and has no effect on the only-one-notification per soft-limit policy.
892 * "memnote" is the current user.
896 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
898 #pragma unused(arg1, arg2)
900 int error
= 0, pid
= 0;
901 struct knote
*kn
= NULL
;
902 boolean_t found_knote
= FALSE
;
903 int fflags
= 0; /* filter flags for EVFILT_MEMORYSTATUS */
906 error
= sysctl_handle_quad(oidp
, &value
, 0, req
);
907 if (error
|| !req
->newptr
)
911 * Find the pid in the low 32 bits of value passed in.
913 pid
= (int)(value
& 0xFFFFFFFF);
916 * Find notification in the high 32 bits of the value passed in.
918 fflags
= (int)((value
>> 32) & 0xFFFFFFFF);
921 * For backwards compatibility, when no notification is
922 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
925 fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
926 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
930 * See event.h ... fflags for EVFILT_MEMORYSTATUS
932 if (!((fflags
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
)||
933 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) ||
934 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) ||
935 (fflags
== NOTE_MEMORYSTATUS_LOW_SWAP
) ||
936 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) ||
937 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
))) {
939 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags
);
945 * Forcibly send pid a memorystatus notification.
948 memorystatus_klist_lock();
950 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
951 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
952 pid_t knote_pid
= knote_proc
->p_pid
;
954 if (knote_pid
== pid
) {
956 * Forcibly send this pid a memorystatus notification.
958 kn
->kn_fflags
= fflags
;
964 KNOTE(&memorystatus_klist
, 0);
965 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value
, fflags
, pid
);
968 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value
, fflags
, pid
);
972 memorystatus_klist_unlock();
977 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_QUAD
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
978 0, 0, &sysctl_memorystatus_vm_pressure_send
, "Q", "");
980 #endif /* VM_PRESSURE_EVENTS */
984 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
986 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
987 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
988 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
989 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
990 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_policy_more_free_offset_pages
, CTLFLAG_RW
, &memorystatus_policy_more_free_offset_pages
, 0, "");
992 /* Diagnostic code */
995 kJetsamDiagnosticModeNone
= 0,
996 kJetsamDiagnosticModeAll
= 1,
997 kJetsamDiagnosticModeStopAtFirstActive
= 2,
998 kJetsamDiagnosticModeCount
999 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
1001 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
1004 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1006 #pragma unused(arg1, arg2)
1008 const char *diagnosticStrings
[] = {
1009 "jetsam: diagnostic mode: resetting critical level.",
1010 "jetsam: diagnostic mode: will examine all processes",
1011 "jetsam: diagnostic mode: will stop at first active process"
1014 int error
, val
= jetsam_diagnostic_mode
;
1015 boolean_t changed
= FALSE
;
1017 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
1018 if (error
|| !req
->newptr
)
1020 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
1021 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
1027 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
1028 jetsam_diagnostic_mode
= val
;
1030 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
1032 switch (jetsam_diagnostic_mode
) {
1033 case kJetsamDiagnosticModeNone
:
1034 /* Already cleared */
1036 case kJetsamDiagnosticModeAll
:
1037 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
1039 case kJetsamDiagnosticModeStopAtFirstActive
:
1040 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
1043 /* Already validated */
1047 memorystatus_update_levels_locked(FALSE
);
1054 printf("%s\n", diagnosticStrings
[val
]);
1060 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
|CTLFLAG_ANYBODY
,
1061 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
1063 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
1065 #if VM_PRESSURE_EVENTS
1067 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
1069 #endif /* VM_PRESSURE_EVENTS */
1071 #endif /* CONFIG_JETSAM */
1075 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
1077 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
1079 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
1080 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
1082 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_count
, "");
1083 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
1084 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_throttle_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_count
, "");
1085 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
1087 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
1088 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
1090 #define VM_PAGES_FOR_ALL_PROCS (2)
1092 * Manual trigger of freeze and thaw for dev / debug kernels only.
1095 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1097 #pragma unused(arg1, arg2)
1101 if (memorystatus_freeze_enabled
== FALSE
) {
1105 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1106 if (error
|| !req
->newptr
)
1109 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1110 vm_pageout_anonymous_pages();
1115 lck_mtx_lock(&freezer_mutex
);
1119 uint32_t purgeable
, wired
, clean
, dirty
;
1121 uint32_t max_pages
= 0;
1123 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1125 unsigned int avail_swap_space
= 0; /* in pages. */
1128 * Freezer backed by the compressor and swap file(s)
1129 * while will hold compressed data.
1131 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
1133 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
1137 * We only have the compressor without any swap.
1139 max_pages
= UINT32_MAX
- 1;
1142 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
1148 lck_mtx_unlock(&freezer_mutex
);
1152 lck_mtx_unlock(&freezer_mutex
);
1156 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1157 0, 0, &sysctl_memorystatus_freeze
, "I", "");
1160 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1162 #pragma unused(arg1, arg2)
1167 if (memorystatus_freeze_enabled
== FALSE
) {
1171 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1172 if (error
|| !req
->newptr
)
1175 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1176 do_fastwake_warmup_all();
1181 error
= task_thaw(p
->task
);
1193 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1194 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
1196 #endif /* CONFIG_FREEZE */
1198 #endif /* DEVELOPMENT || DEBUG */
1200 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
1203 thread_t
*new_thread
);
1205 #if DEVELOPMENT || DEBUG
1208 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1210 #pragma unused(arg1, arg2)
1211 int error
= 0, pid
= 0;
1214 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1215 if (error
|| !req
->newptr
)
1218 lck_mtx_lock(&disconnect_page_mappings_mutex
);
1221 vm_pageout_disconnect_all_pages();
1226 error
= task_disconnect_page_mappings(p
->task
);
1235 lck_mtx_unlock(&disconnect_page_mappings_mutex
);
1240 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_disconnect_page_mappings
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1241 0, 0, &sysctl_memorystatus_disconnect_page_mappings
, "I", "");
1243 #endif /* DEVELOPMENT || DEBUG */
1249 * Picks the sorting routine for a given jetsam priority band.
1252 * bucket_index - jetsam priority band to be sorted.
1253 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1254 * Currently sort_order is only meaningful when handling
1261 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
1263 int coal_sort_order
;
1266 * Verify the jetsam priority
1268 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1272 #if DEVELOPMENT || DEBUG
1273 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1274 coal_sort_order
= COALITION_SORT_DEFAULT
;
1276 coal_sort_order
= sort_order
; /* only used for testing scenarios */
1279 /* Verify default */
1280 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1281 coal_sort_order
= COALITION_SORT_DEFAULT
;
1288 switch (bucket_index
) {
1289 case JETSAM_PRIORITY_FOREGROUND
:
1290 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
1292 * Fall back to per process sorting when zero coalitions are found.
1294 memorystatus_sort_by_largest_process_locked(bucket_index
);
1298 memorystatus_sort_by_largest_process_locked(bucket_index
);
1307 * Sort processes by size for a single jetsam bucket.
1310 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
1312 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
1313 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
1314 uint32_t pages
= 0, max_pages
= 0;
1315 memstat_bucket_t
*current_bucket
;
1317 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1321 current_bucket
= &memstat_bucket
[bucket_index
];
1323 p
= TAILQ_FIRST(¤t_bucket
->list
);
1326 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1331 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
1332 /* traversing list until we find next largest process */
1334 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1335 if (pages
> max_pages
) {
1341 if (prev_max_proc
!= max_proc
) {
1342 /* found a larger process, place it in the list */
1343 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1344 if (insert_after_proc
== NULL
) {
1345 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1347 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1349 prev_max_proc
= max_proc
;
1352 insert_after_proc
= max_proc
;
1354 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1358 #endif /* CONFIG_JETSAM */
1360 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
) {
1361 memstat_bucket_t
*current_bucket
;
1364 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1368 current_bucket
= &memstat_bucket
[*bucket_index
];
1369 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1370 if (!next_p
&& search
) {
1371 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1372 current_bucket
= &memstat_bucket
[*bucket_index
];
1373 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1380 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
) {
1381 memstat_bucket_t
*current_bucket
;
1384 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1388 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1389 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1390 current_bucket
= &memstat_bucket
[*bucket_index
];
1391 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1397 __private_extern__
void
1398 memorystatus_init(void)
1400 thread_t thread
= THREAD_NULL
;
1401 kern_return_t result
;
1405 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1406 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1409 #if DEVELOPMENT || DEBUG
1410 disconnect_page_mappings_lck_grp_attr
= lck_grp_attr_alloc_init();
1411 disconnect_page_mappings_lck_grp
= lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr
);
1413 lck_mtx_init(&disconnect_page_mappings_mutex
, disconnect_page_mappings_lck_grp
, NULL
);
1416 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
1417 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
1420 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1421 TAILQ_INIT(&memstat_bucket
[i
].list
);
1422 memstat_bucket
[i
].count
= 0;
1425 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1427 /* Apply overrides */
1428 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1429 if (delta_percentage
== 0) {
1430 delta_percentage
= 5;
1432 assert(delta_percentage
< 100);
1433 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1434 assert(critical_threshold_percentage
< 100);
1435 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1436 assert(idle_offset_percentage
< 100);
1437 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1438 assert(pressure_threshold_percentage
< 100);
1439 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1440 assert(freeze_threshold_percentage
< 100);
1442 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy
,
1443 sizeof (jetsam_aging_policy
))) {
1445 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy
,
1446 sizeof(jetsam_aging_policy
))) {
1448 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1452 if (jetsam_aging_policy
> kJetsamAgingPolicyMax
) {
1453 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1456 switch (jetsam_aging_policy
) {
1458 case kJetsamAgingPolicyNone
:
1459 system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
1460 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1463 case kJetsamAgingPolicyLegacy
:
1465 * Legacy behavior where some daemons get a 10s protection once
1466 * AND only before the first clean->dirty->clean transition before
1467 * going into IDLE band.
1469 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1470 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1473 case kJetsamAgingPolicySysProcsReclaimedFirst
:
1474 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1475 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1478 case kJetsamAgingPolicyAppsReclaimedFirst
:
1479 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1480 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1488 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1489 * band and must be below it in priority. This is so that we don't have to make
1490 * our 'aging' code worry about a mix of processes, some of which need to age
1491 * and some others that need to stay elevated in the jetsam bands.
1493 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> system_procs_aging_band
);
1494 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> applications_aging_band
);
1497 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1498 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof (memorystatus_idle_snapshot
))) {
1499 /* ...no boot-arg, so check the device tree */
1500 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1503 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1504 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1505 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1506 memorystatus_policy_more_free_offset_pages
= (policy_more_free_offset_percentage
/ delta_percentage
) * memorystatus_delta
;
1508 memorystatus_jetsam_snapshot_max
= maxproc
;
1509 memorystatus_jetsam_snapshot
=
1510 (memorystatus_jetsam_snapshot_t
*)kalloc(sizeof(memorystatus_jetsam_snapshot_t
) +
1511 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
1512 if (!memorystatus_jetsam_snapshot
) {
1513 panic("Could not allocate memorystatus_jetsam_snapshot");
1516 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
1518 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
1520 /* No contention at this point */
1521 memorystatus_update_levels_locked(FALSE
);
1523 /* Jetsam Loop Detection */
1524 if (max_mem
<= (512 * 1024 * 1024)) {
1525 /* 512 MB devices */
1526 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
1528 /* 1GB and larger devices */
1529 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
1534 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1537 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &thread
);
1538 if (result
== KERN_SUCCESS
) {
1539 thread_deallocate(thread
);
1541 panic("Could not create memorystatus_thread");
1545 /* Centralised for the purposes of allowing panic-on-jetsam */
1547 vm_run_compactor(void);
1550 * The jetsam no frills kill call
1551 * Return: 0 on success
1552 * error code on failure (EINVAL...)
1555 jetsam_do_kill(proc_t p
, int jetsam_flags
, os_reason_t jetsam_reason
) {
1557 error
= exit_with_reason(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
, jetsam_reason
);
1562 * Wrapper for processes exiting with memorystatus details
1565 memorystatus_do_kill(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
) {
1568 __unused pid_t victim_pid
= p
->p_pid
;
1570 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
1571 victim_pid
, cause
, vm_page_free_count
, 0, 0);
1573 DTRACE_MEMORYSTATUS3(memorystatus_do_kill
, proc_t
, p
, os_reason_t
, jetsam_reason
, uint32_t, cause
);
1574 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1575 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
1576 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
1579 #pragma unused(cause)
1581 int jetsam_flags
= P_LTERM_JETSAM
;
1583 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
1584 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
1585 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
1586 case kMemorystatusKilledVMThrashing
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
1587 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
1588 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
1589 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
1591 error
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
1593 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
1594 victim_pid
, cause
, vm_page_free_count
, error
, 0);
1598 return (error
== 0);
1606 memorystatus_check_levels_locked(void) {
1609 memorystatus_update_levels_locked(TRUE
);
1614 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1615 * For an application: that means no longer in the FG band
1616 * For a daemon: that means no longer in its 'requested' jetsam priority band
1620 memorystatus_update_inactive_jetsam_priority_band(pid_t pid
, uint32_t op_flags
, boolean_t effective_now
)
1623 boolean_t enable
= FALSE
;
1626 if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
) {
1628 } else if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
) {
1637 if ((enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) ||
1638 (!enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == 0))) {
1640 * No change in state.
1648 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1649 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1651 if (effective_now
) {
1652 if (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1653 if(memorystatus_highwater_enabled
) {
1655 * Process is about to transition from
1656 * inactive --> active
1657 * assign active state
1660 boolean_t use_active
= TRUE
;
1661 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
1662 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
1664 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_ELEVATED_INACTIVE
, FALSE
, FALSE
);
1667 if (isProcessInAgingBands(p
)) {
1668 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1673 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1674 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1676 if (effective_now
) {
1677 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1678 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1681 if (isProcessInAgingBands(p
)) {
1682 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1700 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
1703 uint64_t current_time
= 0, idle_delay_time
= 0;
1704 int demote_prio_band
= 0;
1705 memstat_bucket_t
*demotion_bucket
;
1707 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1709 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1711 current_time
= mach_absolute_time();
1715 demote_prio_band
= JETSAM_PRIORITY_IDLE
+ 1;
1717 for (; demote_prio_band
< JETSAM_PRIORITY_MAX
; demote_prio_band
++) {
1719 if (demote_prio_band
!= system_procs_aging_band
&& demote_prio_band
!= applications_aging_band
)
1722 demotion_bucket
= &memstat_bucket
[demote_prio_band
];
1723 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1726 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
1728 assert(p
->p_memstat_idledeadline
);
1730 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
1732 if (current_time
>= p
->p_memstat_idledeadline
) {
1734 if ((isSysProc(p
) &&
1735 ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) != P_DIRTY_IDLE_EXIT_ENABLED
)) || /* system proc marked dirty*/
1736 task_has_assertions((struct task
*)(p
->task
))) { /* has outstanding assertions which might indicate outstanding work too */
1737 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1739 p
->p_memstat_idledeadline
+= idle_delay_time
;
1740 p
= TAILQ_NEXT(p
, p_memstat_list
);
1744 proc_t next_proc
= NULL
;
1746 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
1747 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1749 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false, true);
1756 // No further candidates
1763 memorystatus_reschedule_idle_demotion_locked();
1767 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
1771 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
1773 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1774 boolean_t present_in_apps_aging_bucket
= FALSE
;
1775 uint64_t idle_delay_time
= 0;
1777 if (jetsam_aging_policy
== kJetsamAgingPolicyNone
) {
1781 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
1783 * This process isn't going to be making the trip to the lower bands.
1788 if (isProcessInAgingBands(p
)){
1790 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1791 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) != P_DIRTY_AGING_IN_PROGRESS
);
1794 if (isSysProc(p
) && system_procs_aging_band
) {
1795 present_in_sysprocs_aging_bucket
= TRUE
;
1797 } else if (isApp(p
) && applications_aging_band
) {
1798 present_in_apps_aging_bucket
= TRUE
;
1802 assert(!present_in_sysprocs_aging_bucket
);
1803 assert(!present_in_apps_aging_bucket
);
1805 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",
1806 p
->p_pid
, p
->p_memstat_dirty
, set_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1809 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
1812 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1815 p
->p_memstat_dirty
|= P_DIRTY_AGING_IN_PROGRESS
;
1816 p
->p_memstat_idledeadline
= mach_absolute_time() + idle_delay_time
;
1819 assert(p
->p_memstat_idledeadline
);
1821 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== FALSE
) {
1822 memorystatus_scheduled_idle_demotions_sysprocs
++;
1824 } else if (isApp(p
) && present_in_apps_aging_bucket
== FALSE
) {
1825 memorystatus_scheduled_idle_demotions_apps
++;
1830 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
1832 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1833 boolean_t present_in_apps_aging_bucket
= FALSE
;
1835 if (!system_procs_aging_band
&& !applications_aging_band
) {
1839 if ((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0) {
1843 if (isProcessInAgingBands(p
)) {
1845 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1846 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == P_DIRTY_AGING_IN_PROGRESS
);
1849 if (isSysProc(p
) && system_procs_aging_band
) {
1850 assert(p
->p_memstat_effectivepriority
== system_procs_aging_band
);
1851 assert(p
->p_memstat_idledeadline
);
1852 present_in_sysprocs_aging_bucket
= TRUE
;
1854 } else if (isApp(p
) && applications_aging_band
) {
1855 assert(p
->p_memstat_effectivepriority
== applications_aging_band
);
1856 assert(p
->p_memstat_idledeadline
);
1857 present_in_apps_aging_bucket
= TRUE
;
1861 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1862 p
->p_pid
, clear_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1866 p
->p_memstat_idledeadline
= 0;
1867 p
->p_memstat_dirty
&= ~P_DIRTY_AGING_IN_PROGRESS
;
1870 if (isSysProc(p
) &&present_in_sysprocs_aging_bucket
== TRUE
) {
1871 memorystatus_scheduled_idle_demotions_sysprocs
--;
1872 assert(memorystatus_scheduled_idle_demotions_sysprocs
>= 0);
1874 } else if (isApp(p
) && present_in_apps_aging_bucket
== TRUE
) {
1875 memorystatus_scheduled_idle_demotions_apps
--;
1876 assert(memorystatus_scheduled_idle_demotions_apps
>= 0);
1879 assert((memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
) >= 0);
1883 memorystatus_reschedule_idle_demotion_locked(void) {
1884 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
)) {
1885 if (memstat_idle_demotion_deadline
) {
1886 /* Transitioned 1->0, so cancel next call */
1887 thread_call_cancel(memorystatus_idle_demotion_call
);
1888 memstat_idle_demotion_deadline
= 0;
1891 memstat_bucket_t
*demotion_bucket
;
1892 proc_t p
= NULL
, p1
= NULL
, p2
= NULL
;
1894 if (system_procs_aging_band
) {
1896 demotion_bucket
= &memstat_bucket
[system_procs_aging_band
];
1897 p1
= TAILQ_FIRST(&demotion_bucket
->list
);
1902 if (applications_aging_band
) {
1904 demotion_bucket
= &memstat_bucket
[applications_aging_band
];
1905 p2
= TAILQ_FIRST(&demotion_bucket
->list
);
1908 p
= (p1
->p_memstat_idledeadline
> p2
->p_memstat_idledeadline
) ? p2
: p1
;
1910 p
= (p1
== NULL
) ? p2
: p1
;
1918 assert(p
&& p
->p_memstat_idledeadline
);
1919 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
){
1920 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
1921 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
1932 memorystatus_add(proc_t p
, boolean_t locked
)
1934 memstat_bucket_t
*bucket
;
1936 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
1942 DTRACE_MEMORYSTATUS2(memorystatus_add
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
);
1944 /* Processes marked internal do not have priority tracked */
1945 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1949 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1951 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
1952 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
- 1);
1954 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
1955 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
- 1);
1957 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
1959 * Entering the idle band.
1960 * Record idle start time.
1962 p
->p_memstat_idle_start
= mach_absolute_time();
1965 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
1968 memorystatus_list_count
++;
1970 memorystatus_check_levels_locked();
1982 * Moves a process from one jetsam bucket to another.
1983 * which changes the LRU position of the process.
1985 * Monitors transition between buckets and if necessary
1986 * will update cached memory limits accordingly.
1988 * skip_demotion_check:
1989 * - if the 'jetsam aging policy' is NOT 'legacy':
1990 * When this flag is TRUE, it means we are going
1991 * to age the ripe processes out of the aging bands and into the
1992 * IDLE band and apply their inactive memory limits.
1994 * - if the 'jetsam aging policy' is 'legacy':
1995 * When this flag is TRUE, it might mean the above aging mechanism
1997 * It might be that we have a process that has used up its 'idle deferral'
1998 * stay that is given to it once per lifetime. And in this case, the process
1999 * won't be going through any aging codepaths. But we still need to apply
2000 * the right inactive limits and so we explicitly set this to TRUE if the
2001 * new priority for the process is the IDLE band.
2004 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
)
2006 memstat_bucket_t
*old_bucket
, *new_bucket
;
2008 assert(priority
< MEMSTAT_BUCKET_COUNT
);
2010 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2011 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2015 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2016 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, head_insert
? "head" : "tail");
2018 DTRACE_MEMORYSTATUS3(memorystatus_update_priority
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
, int, priority
);
2020 #if DEVELOPMENT || DEBUG
2021 if (priority
== JETSAM_PRIORITY_IDLE
&& /* if the process is on its way into the IDLE band */
2022 skip_demotion_check
== FALSE
&& /* and it isn't via the path that will set the INACTIVE memlimits */
2023 (p
->p_memstat_dirty
& P_DIRTY_TRACK
) && /* and it has 'DIRTY' tracking enabled */
2024 ((p
->p_memstat_memlimit
!= p
->p_memstat_memlimit_inactive
) || /* and we notice that the current limit isn't the right value (inactive) */
2025 ((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) */
2026 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 */
2027 #endif /* DEVELOPMENT || DEBUG */
2029 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2031 if (skip_demotion_check
== FALSE
) {
2035 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2036 * the processes from the aging bands and balancing the demotion counts.
2037 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2040 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2041 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2043 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2045 } else if (isApp(p
)) {
2048 * Check to see if the application is being lowered in jetsam priority. If so, and:
2049 * - it has an 'elevated inactive jetsam band' attribute, then put it in the JETSAM_PRIORITY_ELEVATED_INACTIVE band.
2050 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2053 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2054 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2057 if (applications_aging_band
) {
2058 if (p
->p_memstat_effectivepriority
== applications_aging_band
) {
2059 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions_apps
+ 1));
2062 if ((jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) && (priority
<= applications_aging_band
)) {
2063 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2064 priority
= applications_aging_band
;
2065 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2072 if ((system_procs_aging_band
&& (priority
== system_procs_aging_band
)) || (applications_aging_band
&& (priority
== applications_aging_band
))) {
2073 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2076 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
2077 old_bucket
->count
--;
2079 new_bucket
= &memstat_bucket
[priority
];
2081 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
2083 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
2084 new_bucket
->count
++;
2086 if (memorystatus_highwater_enabled
) {
2088 boolean_t use_active
;
2091 * If cached limit data is updated, then the limits
2092 * will be enforced by writing to the ledgers.
2094 boolean_t ledger_update_needed
= TRUE
;
2097 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
2098 * Background limits are described via the inactive limit slots.
2100 * Here, we must update the cached memory limit if the task
2101 * is transitioning between:
2102 * active <--> inactive
2105 * dirty <--> clean is ignored
2107 * We bypass non-idle processes that have opted into dirty tracking because
2108 * a move between buckets does not imply a transition between the
2109 * dirty <--> clean state.
2112 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2114 if (skip_demotion_check
== TRUE
&& priority
== JETSAM_PRIORITY_IDLE
) {
2115 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2118 ledger_update_needed
= FALSE
;
2121 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
2123 * inactive --> active
2125 * assign active state
2127 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2130 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
2132 * active --> inactive
2134 * assign inactive state
2136 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2140 * The transition between jetsam priority buckets apparently did
2141 * not affect active/inactive state.
2142 * This is not unusual... especially during startup when
2143 * processes are getting established in their respective bands.
2145 ledger_update_needed
= FALSE
;
2149 * Enforce the new limits by writing to the ledger
2151 if (ledger_update_needed
) {
2152 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
2154 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2155 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2156 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
2157 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2162 * Record idle start or idle delta.
2164 if (p
->p_memstat_effectivepriority
== priority
) {
2166 * This process is not transitioning between
2167 * jetsam priority buckets. Do nothing.
2169 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2172 * Transitioning out of the idle priority bucket.
2173 * Record idle delta.
2175 assert(p
->p_memstat_idle_start
!= 0);
2176 now
= mach_absolute_time();
2177 if (now
> p
->p_memstat_idle_start
) {
2178 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2180 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
2182 * Transitioning into the idle priority bucket.
2183 * Record idle start.
2185 p
->p_memstat_idle_start
= mach_absolute_time();
2188 p
->p_memstat_effectivepriority
= priority
;
2190 #if CONFIG_SECLUDED_MEMORY
2191 if (secluded_for_apps
&&
2192 task_could_use_secluded_mem(p
->task
)) {
2193 task_set_can_use_secluded_mem(
2195 (priority
>= JETSAM_PRIORITY_FOREGROUND
));
2197 #endif /* CONFIG_SECLUDED_MEMORY */
2199 memorystatus_check_levels_locked();
2204 * Description: Update the jetsam priority and memory limit attributes for a given process.
2207 * p init this process's jetsam information.
2208 * priority The jetsam priority band
2209 * user_data user specific data, unused by the kernel
2210 * effective guards against race if process's update already occurred
2211 * update_memlimit When true we know this is the init step via the posix_spawn path.
2213 * memlimit_active Value in megabytes; The monitored footprint level while the
2214 * process is active. Exceeding it may result in termination
2215 * based on it's associated fatal flag.
2217 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2218 * this describes whether or not it should be immediately fatal.
2220 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2221 * process is inactive. Exceeding it may result in termination
2222 * based on it's associated fatal flag.
2224 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2225 * this describes whether or not it should be immediatly fatal.
2227 * memlimit_background This process has a high-water-mark while in the background.
2228 * No longer meaningful. Background limits are described via
2229 * the inactive slots. Flag is ignored.
2232 * Returns: 0 Success
2237 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
2238 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
2239 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
,
2240 __unused boolean_t memlimit_background
)
2243 boolean_t head_insert
= false;
2245 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
);
2247 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
2249 if (priority
== -1) {
2250 /* Use as shorthand for default priority */
2251 priority
= JETSAM_PRIORITY_DEFAULT
;
2252 } else if ((priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
2253 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2254 priority
= JETSAM_PRIORITY_IDLE
;
2255 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
2256 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2257 priority
= JETSAM_PRIORITY_IDLE
;
2259 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
2267 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2269 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
2272 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
2276 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
2278 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2285 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
2286 p
->p_memstat_userdata
= user_data
;
2287 p
->p_memstat_requestedpriority
= priority
;
2289 if (update_memlimit
) {
2291 boolean_t use_active
;
2294 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2295 * Forked processes do not come through this path, so no ledger limits exist.
2296 * (That's why forked processes can consume unlimited memory.)
2299 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2300 p
->p_pid
, priority
, p
->p_memstat_dirty
,
2301 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2302 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2304 if (memlimit_background
) {
2307 * With 2-level HWM support, we no longer honor P_MEMSTAT_MEMLIMIT_BACKGROUND.
2308 * Background limits are described via the inactive limit slots.
2311 // p->p_memstat_state |= P_MEMSTAT_MEMLIMIT_BACKGROUND;
2313 #if DEVELOPMENT || DEBUG
2314 printf("memorystatus_update: WARNING %s[%d] set unused flag P_MEMSTAT_MEMLIMIT_BACKGROUND [A==%dMB %s] [IA==%dMB %s]\n",
2315 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
,
2316 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2317 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2318 #endif /* DEVELOPMENT || DEBUG */
2321 if (memlimit_active
<= 0) {
2323 * This process will have a system_wide task limit when active.
2324 * System_wide task limit is always fatal.
2325 * It's quite common to see non-fatal flag passed in here.
2326 * It's not an error, we just ignore it.
2330 * For backward compatibility with some unexplained launchd behavior,
2331 * we allow a zero sized limit. But we still enforce system_wide limit
2332 * when written to the ledgers.
2335 if (memlimit_active
< 0) {
2336 memlimit_active
= -1; /* enforces system_wide task limit */
2338 memlimit_active_is_fatal
= TRUE
;
2341 if (memlimit_inactive
<= 0) {
2343 * This process will have a system_wide task limit when inactive.
2344 * System_wide task limit is always fatal.
2347 memlimit_inactive
= -1;
2348 memlimit_inactive_is_fatal
= TRUE
;
2352 * Initialize the active limit variants for this process.
2354 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
2357 * Initialize the inactive limit variants for this process.
2359 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
2362 * Initialize the cached limits for target process.
2363 * When the target process is dirty tracked, it's typically
2364 * in a clean state. Non dirty tracked processes are
2365 * typically active (Foreground or above).
2366 * But just in case, we don't make assumptions...
2369 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2370 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2373 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2378 * Enforce the cached limit by writing to the ledger.
2380 if (memorystatus_highwater_enabled
) {
2382 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, use_active
, is_fatal
);
2384 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2385 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2386 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
2387 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2392 * We can't add to the aging bands buckets here.
2393 * But, we could be removing it from those buckets.
2394 * Check and take appropriate steps if so.
2397 if (isProcessInAgingBands(p
)) {
2399 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2400 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2402 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
&& priority
== JETSAM_PRIORITY_IDLE
) {
2404 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2405 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2406 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2407 * is any other aging policy, then we don't need to worry because all processes
2408 * will go through the aging bands and then the demotion thread will take care to
2409 * move them into the IDLE band and apply the required limits.
2411 memorystatus_update_priority_locked(p
, priority
, head_insert
, TRUE
);
2415 memorystatus_update_priority_locked(p
, priority
, head_insert
, FALSE
);
2421 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
2427 memorystatus_remove(proc_t p
, boolean_t locked
)
2430 memstat_bucket_t
*bucket
;
2431 boolean_t reschedule
= FALSE
;
2433 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
2439 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2441 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2443 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2445 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
);
2448 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2450 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
);
2458 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2459 uint64_t now
= mach_absolute_time();
2460 if (now
> p
->p_memstat_idle_start
) {
2461 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2465 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
2468 memorystatus_list_count
--;
2470 /* If awaiting demotion to the idle band, clean up */
2472 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2473 memorystatus_reschedule_idle_demotion_locked();
2476 memorystatus_check_levels_locked();
2479 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
2480 memorystatus_frozen_count
--;
2483 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
2484 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
2485 memorystatus_suspended_count
--;
2503 * Validate dirty tracking flags with process state.
2509 * The proc_list_lock is held by the caller.
2513 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
) {
2514 /* See that the process isn't marked for termination */
2515 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
2519 /* Idle exit requires that process be tracked */
2520 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
2521 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2525 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2526 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
2527 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2531 /* Deferral is only relevant if idle exit is specified */
2532 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
2533 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
2541 memorystatus_update_idle_priority_locked(proc_t p
) {
2544 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
2546 assert(isSysProc(p
));
2548 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2550 priority
= (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) ? system_procs_aging_band
: JETSAM_PRIORITY_IDLE
;
2552 priority
= p
->p_memstat_requestedpriority
;
2555 if (priority
!= p
->p_memstat_effectivepriority
) {
2557 if ((jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) &&
2558 (priority
== JETSAM_PRIORITY_IDLE
)) {
2561 * This process is on its way into the IDLE band. The system is
2562 * using 'legacy' jetsam aging policy. That means, this process
2563 * has already used up its idle-deferral aging time that is given
2564 * once per its lifetime. So we need to set the INACTIVE limits
2565 * explicitly because it won't be going through the demotion paths
2566 * that take care to apply the limits appropriately.
2568 memorystatus_update_priority_locked(p
, priority
, false, true);
2571 memorystatus_update_priority_locked(p
, priority
, false, false);
2577 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
2578 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2579 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2580 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2582 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2583 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2584 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2585 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2586 * band. The deferral can be cleared early by clearing the appropriate flag.
2588 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2589 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2590 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2594 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
) {
2595 unsigned int old_dirty
;
2596 boolean_t reschedule
= FALSE
;
2597 boolean_t already_deferred
= FALSE
;
2598 boolean_t defer_now
= FALSE
;
2601 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
2602 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
2606 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2608 * Process is on its way out.
2614 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2619 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
2624 old_dirty
= p
->p_memstat_dirty
;
2626 /* These bits are cumulative, as per <rdar://problem/11159924> */
2627 if (pcontrol
& PROC_DIRTY_TRACK
) {
2628 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
2631 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
2632 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
2635 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2636 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
2639 if (old_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2640 already_deferred
= TRUE
;
2644 /* This can be set and cleared exactly once. */
2645 if (pcontrol
& PROC_DIRTY_DEFER
) {
2647 if ( !(old_dirty
& P_DIRTY_DEFER
)) {
2648 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
2654 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2655 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
2656 defer_now
? "Y" : "N",
2657 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
2660 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
2661 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
2662 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2664 if (defer_now
&& !already_deferred
) {
2667 * Request to defer a clean process that's idle-exit enabled
2668 * and not already in the jetsam deferred band. Most likely a
2671 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2674 } else if (!defer_now
) {
2677 * The process isn't asking for the 'aging' facility.
2678 * Could be that it is:
2681 if (already_deferred
) {
2683 * already in the aging bands. Traditionally,
2684 * some processes have tried to use this to
2685 * opt out of the 'aging' facility.
2688 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2691 * agnostic to the 'aging' facility. In that case,
2692 * we'll go ahead and opt it in because this is likely
2693 * a new launch (clean process, dirty tracking enabled)
2696 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2705 * We are trying to operate on a dirty process. Dirty processes have to
2706 * be removed from the deferred band. The question is do we reset the
2707 * deferred state or not?
2709 * This could be a legal request like:
2710 * - this process had opted into the 'aging' band
2711 * - but it's now dirty and requests to opt out.
2712 * In this case, we remove the process from the band and reset its
2713 * state too. It'll opt back in properly when needed.
2715 * OR, this request could be a user-space bug. E.g.:
2716 * - this process had opted into the 'aging' band when clean
2717 * - and, then issues another request to again put it into the band except
2718 * this time the process is dirty.
2719 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
2720 * the deferred band with its state intact. So our request below is no-op.
2721 * But we do it here anyways for coverage.
2723 * memorystatus_update_idle_priority_locked()
2724 * single-mindedly treats a dirty process as "cannot be in the aging band".
2727 if (!defer_now
&& already_deferred
) {
2728 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2732 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2734 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2739 memorystatus_update_idle_priority_locked(p
);
2742 memorystatus_reschedule_idle_demotion_locked();
2754 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
) {
2756 boolean_t kill
= false;
2757 boolean_t reschedule
= FALSE
;
2758 boolean_t was_dirty
= FALSE
;
2759 boolean_t now_dirty
= FALSE
;
2761 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2762 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
2766 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2768 * Process is on its way out.
2774 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2779 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2782 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2783 /* Dirty tracking not enabled */
2785 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2787 * Process is set to be terminated and we're attempting to mark it dirty.
2788 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2792 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
2793 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
2794 /* Mark the process as having been dirtied at some point */
2795 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
2796 memorystatus_dirty_count
++;
2798 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
2799 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
2800 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2801 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2803 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2804 /* Kill previously terminated processes if set clean */
2807 p
->p_memstat_dirty
&= ~flag
;
2808 memorystatus_dirty_count
--;
2820 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2823 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
2824 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
2826 /* Manage idle exit deferral, if applied */
2827 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2830 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
2831 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
2833 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
2834 * in that band on it's way to IDLE.
2837 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2839 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2841 * The process will move from its aging band to its higher requested
2844 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2846 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2851 * Process is back from "dirty" to "clean".
2854 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) {
2855 if (mach_absolute_time() >= p
->p_memstat_idledeadline
) {
2857 * The process' deadline has expired. It currently
2858 * does not reside in any of the aging buckets.
2860 * It's on its way to the JETSAM_PRIORITY_IDLE
2861 * bucket via memorystatus_update_idle_priority_locked()
2864 * So all we need to do is reset all the state on the
2865 * process that's related to the aging bucket i.e.
2866 * the AGING_IN_PROGRESS flag and the timer deadline.
2869 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2873 * It still has some protection window left and so
2874 * we just re-arm the timer without modifying any
2875 * state on the process iff it still wants into that band.
2878 if (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2879 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
2885 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2891 memorystatus_update_idle_priority_locked(p
);
2893 if (memorystatus_highwater_enabled
) {
2894 boolean_t ledger_update_needed
= TRUE
;
2895 boolean_t use_active
;
2898 * We are in this path because this process transitioned between
2899 * dirty <--> clean state. Update the cached memory limits.
2902 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2906 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2908 ledger_update_needed
= TRUE
;
2911 * process is clean...but if it has opted into pressured-exit
2912 * we don't apply the INACTIVE limit till the process has aged
2913 * out and is entering the IDLE band.
2914 * See memorystatus_update_priority_locked() for that.
2917 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
2918 ledger_update_needed
= FALSE
;
2920 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2922 ledger_update_needed
= TRUE
;
2927 * Enforce the new limits by writing to the ledger.
2929 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
2930 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
2931 * We aren't traversing the jetsam bucket list here, so we should be safe.
2932 * See rdar://21394491.
2935 if (ledger_update_needed
&& proc_ref_locked(p
) == p
) {
2937 if (p
->p_memstat_memlimit
> 0) {
2938 ledger_limit
= p
->p_memstat_memlimit
;
2943 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, use_active
, is_fatal
);
2945 proc_rele_locked(p
);
2947 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
2948 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2949 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
2950 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2955 /* If the deferral state changed, reschedule the demotion timer */
2957 memorystatus_reschedule_idle_demotion_locked();
2962 if (proc_ref_locked(p
) == p
) {
2964 psignal(p
, SIGKILL
);
2966 proc_rele_locked(p
);
2977 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
) {
2981 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2983 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
2987 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2989 * Process is on its way out.
2995 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3000 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
3001 /* Dirty tracking not enabled */
3006 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
)) == 0) {
3011 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
3012 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
3015 /* This can be set and cleared exactly once. */
3016 if (pcontrol
& PROC_DIRTY_DEFER
) {
3018 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
3020 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER
;
3022 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3023 memorystatus_update_idle_priority_locked(p
);
3024 memorystatus_reschedule_idle_demotion_locked();
3036 memorystatus_dirty_get(proc_t p
) {
3041 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3042 ret
|= PROC_DIRTY_TRACKED
;
3043 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3044 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
3046 if (p
->p_memstat_dirty
& P_DIRTY
) {
3047 ret
|= PROC_DIRTY_IS_DIRTY
;
3049 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
3050 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
3060 memorystatus_on_terminate(proc_t p
) {
3065 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3067 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
3068 /* Clean; mark as terminated and issue SIGKILL */
3071 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3081 memorystatus_on_suspend(proc_t p
)
3085 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3089 p
->p_memstat_suspendedfootprint
= pages
;
3090 memorystatus_suspended_footprint_total
+= pages
;
3091 memorystatus_suspended_count
++;
3093 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
3098 memorystatus_on_resume(proc_t p
)
3108 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
3110 memorystatus_frozen_count
--;
3111 p
->p_memstat_state
|= P_MEMSTAT_PRIOR_THAW
;
3114 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
3115 memorystatus_suspended_count
--;
3120 p
->p_memstat_state
&= ~(P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
);
3126 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
3127 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3133 memorystatus_on_inactivity(proc_t p
)
3137 /* Wake the freeze thread */
3138 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
3143 * The proc_list_lock is held by the caller.
3146 memorystatus_build_state(proc_t p
) {
3147 uint32_t snapshot_state
= 0;
3150 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3151 snapshot_state
|= kMemorystatusSuspended
;
3153 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
3154 snapshot_state
|= kMemorystatusFrozen
;
3156 if (p
->p_memstat_state
& P_MEMSTAT_PRIOR_THAW
) {
3157 snapshot_state
|= kMemorystatusWasThawed
;
3161 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3162 snapshot_state
|= kMemorystatusTracked
;
3164 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3165 snapshot_state
|= kMemorystatusSupportsIdleExit
;
3167 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3168 snapshot_state
|= kMemorystatusDirty
;
3171 return snapshot_state
;
3177 kill_idle_exit_proc(void)
3179 proc_t p
, victim_p
= PROC_NULL
;
3180 uint64_t current_time
;
3181 boolean_t killed
= FALSE
;
3183 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3185 /* Pick next idle exit victim. */
3186 current_time
= mach_absolute_time();
3188 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_IDLE_EXIT
);
3189 if (jetsam_reason
== OS_REASON_NULL
) {
3190 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3195 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
3197 /* No need to look beyond the idle band */
3198 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
3202 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
|P_DIRTY_IS_DIRTY
|P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
3203 if (current_time
>= p
->p_memstat_idledeadline
) {
3204 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3205 victim_p
= proc_ref_locked(p
);
3210 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
3216 printf("memorystatus_thread: idle exiting pid %d [%s]\n", victim_p
->p_pid
, (*victim_p
->p_name
? victim_p
->p_name
: "(unknown)"));
3217 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
, jetsam_reason
);
3218 proc_rele(victim_p
);
3220 os_reason_free(jetsam_reason
);
3229 memorystatus_thread_wake(void) {
3230 thread_wakeup((event_t
)&memorystatus_wakeup
);
3232 #endif /* CONFIG_JETSAM */
3234 extern void vm_pressure_response(void);
3237 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
3240 assert_wait_timeout(&memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, 1000 * NSEC_PER_USEC
);
3242 assert_wait(&memorystatus_wakeup
, THREAD_UNINT
);
3245 return thread_block(continuation
);
3249 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
3251 static boolean_t is_vm_privileged
= FALSE
;
3254 boolean_t post_snapshot
= FALSE
;
3255 uint32_t errors
= 0;
3256 uint32_t hwm_kill
= 0;
3257 boolean_t sort_flag
= TRUE
;
3258 boolean_t corpse_list_purged
= FALSE
;
3260 /* Jetsam Loop Detection - locals */
3261 memstat_bucket_t
*bucket
;
3262 int jld_bucket_count
= 0;
3263 struct timeval jld_now_tstamp
= {0,0};
3264 uint64_t jld_now_msecs
= 0;
3265 int elevated_bucket_count
= 0;
3267 /* Jetsam Loop Detection - statics */
3268 static uint64_t jld_timestamp_msecs
= 0;
3269 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
3270 static int jld_idle_kills
= 0; /* Number of procs killed during eval period */
3271 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
3272 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3275 if (is_vm_privileged
== FALSE
) {
3277 * It's the first time the thread has run, so just mark the thread as privileged and block.
3278 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
3280 thread_wire(host_priv_self(), current_thread(), TRUE
);
3281 is_vm_privileged
= TRUE
;
3283 if (vm_restricted_to_single_processor
== TRUE
)
3284 thread_vm_bind_group_add();
3286 memorystatus_thread_block(0, memorystatus_thread
);
3291 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
3292 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
,0);
3295 * Jetsam aware version.
3297 * The VM pressure notification thread is working it's way through clients in parallel.
3299 * So, while the pressure notification thread is targeting processes in order of
3300 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
3301 * any processes that have exceeded their highwater mark.
3303 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
3304 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
3306 while (is_thrashing(kill_under_pressure_cause
) ||
3307 memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3311 uint64_t jetsam_reason_code
= JETSAM_REASON_INVALID
;
3312 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3314 cause
= kill_under_pressure_cause
;
3316 case kMemorystatusKilledFCThrashing
:
3317 jetsam_reason_code
= JETSAM_REASON_MEMORY_FCTHRASHING
;
3319 case kMemorystatusKilledVMThrashing
:
3320 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMTHRASHING
;
3322 case kMemorystatusKilledVMPageShortage
:
3325 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMPAGESHORTAGE
;
3326 cause
= kMemorystatusKilledVMPageShortage
;
3331 killed
= memorystatus_kill_hiwat_proc(&errors
);
3334 post_snapshot
= TRUE
;
3337 memorystatus_hwm_candidates
= FALSE
;
3340 /* No highwater processes to kill. Continue or stop for now? */
3341 if (!is_thrashing(kill_under_pressure_cause
) &&
3342 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
3344 * We are _not_ out of pressure but we are above the critical threshold and there's:
3345 * - no compressor thrashing
3346 * - no more HWM processes left.
3347 * For now, don't kill any other processes.
3350 if (hwm_kill
== 0) {
3351 memorystatus_thread_wasted_wakeup
++;
3357 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, jetsam_reason_code
);
3358 if (jetsam_reason
== OS_REASON_NULL
) {
3359 printf("memorystatus_thread: failed to allocate jetsam reason\n");
3362 if (memorystatus_jld_enabled
== TRUE
) {
3365 * Jetsam Loop Detection: attempt to detect
3366 * rapid daemon relaunches in the lower bands.
3369 microuptime(&jld_now_tstamp
);
3372 * Ignore usecs in this calculation.
3373 * msecs granularity is close enough.
3375 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
3378 switch (jetsam_aging_policy
) {
3379 case kJetsamAgingPolicyLegacy
:
3380 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3381 jld_bucket_count
= bucket
->count
;
3382 bucket
= &memstat_bucket
[JETSAM_PRIORITY_AGING_BAND1
];
3383 jld_bucket_count
+= bucket
->count
;
3385 case kJetsamAgingPolicySysProcsReclaimedFirst
:
3386 case kJetsamAgingPolicyAppsReclaimedFirst
:
3387 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3388 jld_bucket_count
= bucket
->count
;
3389 bucket
= &memstat_bucket
[system_procs_aging_band
];
3390 jld_bucket_count
+= bucket
->count
;
3391 bucket
= &memstat_bucket
[applications_aging_band
];
3392 jld_bucket_count
+= bucket
->count
;
3394 case kJetsamAgingPolicyNone
:
3396 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3397 jld_bucket_count
= bucket
->count
;
3401 bucket
= &memstat_bucket
[JETSAM_PRIORITY_ELEVATED_INACTIVE
];
3402 elevated_bucket_count
= bucket
->count
;
3407 * memorystatus_jld_eval_period_msecs is a tunable
3408 * memorystatus_jld_eval_aggressive_count is a tunable
3409 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
3411 if ( (jld_bucket_count
== 0) ||
3412 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
3415 * Refresh evaluation parameters
3417 jld_timestamp_msecs
= jld_now_msecs
;
3418 jld_idle_kill_candidates
= jld_bucket_count
;
3420 jld_eval_aggressive_count
= 0;
3421 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3424 if (jld_idle_kills
> jld_idle_kill_candidates
) {
3425 jld_eval_aggressive_count
++;
3427 #if DEVELOPMENT || DEBUG
3428 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
3429 jld_eval_aggressive_count
,
3430 jld_timestamp_msecs
,
3432 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
3433 jld_eval_aggressive_count
,
3434 jld_idle_kill_candidates
,
3436 #endif /* DEVELOPMENT || DEBUG */
3438 if ((jld_eval_aggressive_count
== memorystatus_jld_eval_aggressive_count
) &&
3439 (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3441 * If we reach this aggressive cycle, corpses might be causing memory pressure.
3442 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
3443 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
3445 task_purge_all_corpses();
3446 corpse_list_purged
= TRUE
;
3448 else if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
3450 * Bump up the jetsam priority limit (eg: the bucket index)
3451 * Enforce bucket index sanity.
3453 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
3454 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
3456 * Do nothing. Stick with the default level.
3459 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
3463 /* Visit elevated processes first */
3464 while (elevated_bucket_count
) {
3466 elevated_bucket_count
--;
3469 * memorystatus_kill_elevated_process() drops a reference,
3470 * so take another one so we can continue to use this exit reason
3471 * even after it returns.
3474 os_reason_ref(jetsam_reason
);
3475 killed
= memorystatus_kill_elevated_process(
3476 kMemorystatusKilledVMThrashing
,
3478 jld_eval_aggressive_count
,
3482 post_snapshot
= TRUE
;
3483 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3485 * Still under pressure.
3486 * Find another pinned processes.
3494 * No pinned processes left to kill.
3495 * Abandon elevated band.
3502 * memorystatus_kill_top_process_aggressive() drops a reference,
3503 * so take another one so we can continue to use this exit reason
3504 * even after it returns
3506 os_reason_ref(jetsam_reason
);
3507 killed
= memorystatus_kill_top_process_aggressive(
3509 kMemorystatusKilledVMThrashing
,
3511 jld_eval_aggressive_count
,
3512 jld_priority_band_max
,
3516 /* Always generate logs after aggressive kill */
3517 post_snapshot
= TRUE
;
3525 * memorystatus_kill_top_process() drops a reference,
3526 * so take another one so we can continue to use this exit reason
3527 * even after it returns
3529 os_reason_ref(jetsam_reason
);
3532 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, jetsam_reason
, &priority
, &errors
);
3537 * Don't generate logs for steady-state idle-exit kills,
3538 * unless it is overridden for debug or by the device
3541 if ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
) {
3542 post_snapshot
= TRUE
;
3545 /* Jetsam Loop Detection */
3546 if (memorystatus_jld_enabled
== TRUE
) {
3547 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
3551 * We've reached into bands beyond idle deferred.
3552 * We make no attempt to monitor them
3557 if ((priority
>= JETSAM_PRIORITY_UI_SUPPORT
) && (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3559 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
3560 * then we attempt to relieve pressure by purging corpse memory.
3562 task_purge_all_corpses();
3563 corpse_list_purged
= TRUE
;
3568 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3570 * Still under pressure and unable to kill a process - purge corpse memory
3572 if (total_corpses_count
> 0) {
3573 task_purge_all_corpses();
3574 corpse_list_purged
= TRUE
;
3577 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3579 * Still under pressure and unable to kill a process - panic
3581 panic("memorystatus_jetsam_thread: no victim! available pages:%d\n", memorystatus_available_pages
);
3588 * We do not want to over-kill when thrashing has been detected.
3589 * To avoid that, we reset the flag here and notify the
3592 if (is_thrashing(kill_under_pressure_cause
)) {
3593 kill_under_pressure_cause
= 0;
3594 vm_thrashing_jetsam_done();
3597 os_reason_free(jetsam_reason
);
3600 kill_under_pressure_cause
= 0;
3603 memorystatus_clear_errors();
3606 #if VM_PRESSURE_EVENTS
3608 * LD: We used to target the foreground process first and foremost here.
3609 * Now, we target all processes, starting from the non-suspended, background
3610 * processes first. We will target foreground too.
3612 * memorystatus_update_vm_pressure(TRUE);
3614 //vm_pressure_response();
3617 if (post_snapshot
) {
3619 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3620 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
3621 uint64_t timestamp_now
= mach_absolute_time();
3622 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3623 memorystatus_jetsam_snapshot
->js_gencount
++;
3624 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3625 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3627 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3630 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3638 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
3639 memorystatus_available_pages
, 0, 0, 0, 0);
3641 #else /* CONFIG_JETSAM */
3644 * Jetsam not enabled
3647 #endif /* CONFIG_JETSAM */
3649 memorystatus_thread_block(0, memorystatus_thread
);
3655 * when an idle-exitable proc was killed
3657 * when there are no more idle-exitable procs found
3658 * when the attempt to kill an idle-exitable proc failed
3660 boolean_t
memorystatus_idle_exit_from_VM(void) {
3661 return(kill_idle_exit_proc());
3663 #endif /* !CONFIG_JETSAM */
3666 * Callback invoked when allowable physical memory footprint exceeded
3667 * (dirty pages + IOKit mappings)
3669 * This is invoked for both advisory, non-fatal per-task high watermarks,
3670 * as well as the fatal task memory limits.
3673 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3675 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3677 proc_t p
= current_proc();
3679 #if VM_PRESSURE_EVENTS
3680 if (warning
== TRUE
) {
3682 * This is a warning path which implies that the current process is close, but has
3683 * not yet exceeded its per-process memory limit.
3685 if (memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, FALSE
/* not exceeded */) != TRUE
) {
3686 /* Print warning, since it's possible that task has not registered for pressure notifications */
3687 printf("task_exceeded_footprint: failed to warn the current task (%d exiting, or no handler registered?).\n", p
->p_pid
);
3691 #endif /* VM_PRESSURE_EVENTS */
3693 if (memlimit_is_fatal
) {
3695 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
3696 * has violated either the system-wide per-task memory limit OR its own task limit.
3698 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_PERPROCESSLIMIT
);
3699 if (jetsam_reason
== NULL
) {
3700 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
3701 } else if (corpse_for_fatal_memkill
!= 0) {
3702 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
3703 jetsam_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
3706 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
, jetsam_reason
) != TRUE
) {
3707 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
3711 * HWM offender exists. Done without locks or synchronization.
3712 * See comment near its declaration for more details.
3714 memorystatus_hwm_candidates
= TRUE
;
3716 #if VM_PRESSURE_EVENTS
3718 * The current process is not in the warning path.
3719 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
3720 * Failure to send note is ignored here.
3722 (void)memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, TRUE
/* exceeded */);
3724 #endif /* VM_PRESSURE_EVENTS */
3729 memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3731 proc_t p
= current_proc();
3734 * The limit violation is logged here, but only once per process per limit.
3735 * Soft memory limit is a non-fatal high-water-mark
3736 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
3739 printf("process %d (%s) exceeded physical memory footprint, the %s%sMemoryLimit of %d MB\n",
3740 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"), (memlimit_is_active
? "Active" : "Inactive"),
3741 (memlimit_is_fatal
? "Hard" : "Soft"), max_footprint_mb
);
3749 * Evaluates active vs. inactive process state.
3750 * Processes that opt into dirty tracking are evaluated
3751 * based on clean vs dirty state.
3753 * clean ==> inactive
3755 * Process that do not opt into dirty tracking are
3756 * evalulated based on priority level.
3757 * Foreground or above ==> active
3758 * Below Foreground ==> inactive
3760 * Return: TRUE if active
3765 proc_jetsam_state_is_active_locked(proc_t p
) {
3767 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3769 * process has opted into dirty tracking
3770 * active state is based on dirty vs. clean
3772 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3775 * implies active state
3781 * implies inactive state
3785 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
3787 * process is Foreground or higher
3788 * implies active state
3793 * process found below Foreground
3794 * implies inactive state
3801 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3805 uint32_t errors
= 0;
3807 if (victim_pid
== -1) {
3808 /* No pid, so kill first process */
3809 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, jetsam_reason
, NULL
, &errors
);
3811 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3815 memorystatus_clear_errors();
3819 /* Fire off snapshot notification */
3821 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3822 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
3823 uint64_t timestamp_now
= mach_absolute_time();
3824 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3825 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3826 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3828 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3831 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3838 #else /* !CONFIG_JETSAM */
3840 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3842 #endif /* CONFIG_JETSAM */
3848 * Jetsam a specific process.
3851 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3854 uint64_t killtime
= 0;
3856 clock_usec_t tv_usec
;
3859 /* TODO - add a victim queue and push this into the main jetsam thread */
3861 p
= proc_find(victim_pid
);
3863 os_reason_free(jetsam_reason
);
3870 if (memorystatus_jetsam_snapshot_count
== 0) {
3871 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3874 killtime
= mach_absolute_time();
3875 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3876 tv_msec
= tv_usec
/ 1000;
3878 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
3882 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3883 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3884 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, memorystatus_available_pages
);
3885 #else /* !CONFIG_JETSAM */
3888 killtime
= mach_absolute_time();
3889 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3890 tv_msec
= tv_usec
/ 1000;
3891 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d)\n",
3892 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3893 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
);
3894 #endif /* CONFIG_JETSAM */
3896 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
3904 * Toggle the P_MEMSTAT_TERMINATED state.
3905 * Takes the proc_list_lock.
3908 proc_memstat_terminated(proc_t p
, boolean_t set
)
3910 #if DEVELOPMENT || DEBUG
3914 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3916 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3921 #pragma unused(p, set)
3925 #endif /* DEVELOPMENT || DEBUG */
3932 * This is invoked when cpulimits have been exceeded while in fatal mode.
3933 * The jetsam_flags do not apply as those are for memory related kills.
3934 * We call this routine so that the offending process is killed with
3935 * a non-zero exit status.
3938 jetsam_on_ledger_cpulimit_exceeded(void)
3941 int jetsam_flags
= 0; /* make it obvious */
3942 proc_t p
= current_proc();
3943 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3945 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
3946 p
->p_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"));
3948 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_CPULIMIT
);
3949 if (jetsam_reason
== OS_REASON_NULL
) {
3950 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
3953 retval
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
3956 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
3961 memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
)
3966 *count
= get_task_memory_region_count(task
);
3970 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
3977 pages
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
3978 assert(((uint32_t)pages
) == pages
);
3979 *footprint
= (uint32_t)pages
;
3981 if (max_footprint
) {
3982 pages
= (get_task_phys_footprint_max(task
) / PAGE_SIZE_64
);
3983 assert(((uint32_t)pages
) == pages
);
3984 *max_footprint
= (uint32_t)pages
;
3986 if (max_footprint_lifetime
) {
3987 pages
= (get_task_resident_max(task
) / PAGE_SIZE_64
);
3988 assert(((uint32_t)pages
) == pages
);
3989 *max_footprint_lifetime
= (uint32_t)pages
;
3991 if (purgeable_pages
) {
3992 pages
= (get_task_purgeable_size(task
) / PAGE_SIZE_64
);
3993 assert(((uint32_t)pages
) == pages
);
3994 *purgeable_pages
= (uint32_t)pages
;
3999 memorystatus_get_task_phys_footprint_page_counts(task_t task
,
4000 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
4001 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
4002 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
4003 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
)
4007 if (internal_pages
) {
4008 *internal_pages
= (get_task_internal(task
) / PAGE_SIZE_64
);
4011 if (internal_compressed_pages
) {
4012 *internal_compressed_pages
= (get_task_internal_compressed(task
) / PAGE_SIZE_64
);
4015 if (purgeable_nonvolatile_pages
) {
4016 *purgeable_nonvolatile_pages
= (get_task_purgeable_nonvolatile(task
) / PAGE_SIZE_64
);
4019 if (purgeable_nonvolatile_compressed_pages
) {
4020 *purgeable_nonvolatile_compressed_pages
= (get_task_purgeable_nonvolatile_compressed(task
) / PAGE_SIZE_64
);
4023 if (alternate_accounting_pages
) {
4024 *alternate_accounting_pages
= (get_task_alternate_accounting(task
) / PAGE_SIZE_64
);
4027 if (alternate_accounting_compressed_pages
) {
4028 *alternate_accounting_compressed_pages
= (get_task_alternate_accounting_compressed(task
) / PAGE_SIZE_64
);
4031 if (iokit_mapped_pages
) {
4032 *iokit_mapped_pages
= (get_task_iokit_mapped(task
) / PAGE_SIZE_64
);
4035 if (page_table_pages
) {
4036 *page_table_pages
= (get_task_page_table(task
) / PAGE_SIZE_64
);
4041 * This routine only acts on the global jetsam event snapshot.
4042 * Updating the process's entry can race when the memorystatus_thread
4043 * has chosen to kill a process that is racing to exit on another core.
4046 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
)
4048 memorystatus_jetsam_snapshot_entry_t
*entry
= NULL
;
4049 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4050 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4054 if (memorystatus_jetsam_snapshot_count
== 0) {
4056 * No active snapshot.
4063 * Sanity check as this routine should only be called
4064 * from a jetsam kill path.
4066 assert(kill_cause
!= 0 && killtime
!= 0);
4068 snapshot
= memorystatus_jetsam_snapshot
;
4069 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4071 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
4072 if (snapshot_list
[i
].pid
== p
->p_pid
) {
4074 entry
= &snapshot_list
[i
];
4076 if (entry
->killed
|| entry
->jse_killtime
) {
4078 * We apparently raced on the exit path
4079 * for this process, as it's snapshot entry
4080 * has already recorded a kill.
4082 assert(entry
->killed
&& entry
->jse_killtime
);
4087 * Update the entry we just found in the snapshot.
4090 entry
->killed
= kill_cause
;
4091 entry
->jse_killtime
= killtime
;
4092 entry
->jse_gencount
= snapshot
->js_gencount
;
4093 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
;
4096 * If a process has moved between bands since snapshot was
4097 * initialized, then likely these fields changed too.
4099 if (entry
->priority
!= p
->p_memstat_effectivepriority
) {
4101 strlcpy(entry
->name
, p
->p_name
, sizeof(entry
->name
));
4102 entry
->priority
= p
->p_memstat_effectivepriority
;
4103 entry
->state
= memorystatus_build_state(p
);
4104 entry
->user_data
= p
->p_memstat_userdata
;
4105 entry
->fds
= p
->p_fd
->fd_nfiles
;
4109 * Always update the page counts on a kill.
4113 uint32_t max_pages
= 0;
4114 uint32_t max_pages_lifetime
= 0;
4115 uint32_t purgeable_pages
= 0;
4117 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4118 entry
->pages
= (uint64_t)pages
;
4119 entry
->max_pages
= (uint64_t)max_pages
;
4120 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4121 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4123 uint64_t internal_pages
= 0;
4124 uint64_t internal_compressed_pages
= 0;
4125 uint64_t purgeable_nonvolatile_pages
= 0;
4126 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4127 uint64_t alternate_accounting_pages
= 0;
4128 uint64_t alternate_accounting_compressed_pages
= 0;
4129 uint64_t iokit_mapped_pages
= 0;
4130 uint64_t page_table_pages
= 0;
4132 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4133 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4134 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4135 &iokit_mapped_pages
, &page_table_pages
);
4137 entry
->jse_internal_pages
= internal_pages
;
4138 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4139 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4140 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4141 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4142 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4143 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4144 entry
->jse_page_table_pages
= page_table_pages
;
4146 uint64_t region_count
= 0;
4147 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4148 entry
->jse_memory_region_count
= region_count
;
4154 if (entry
== NULL
) {
4156 * The entry was not found in the snapshot, so the process must have
4157 * launched after the snapshot was initialized.
4158 * Let's try to append the new entry.
4160 if (memorystatus_jetsam_snapshot_count
< memorystatus_jetsam_snapshot_max
) {
4162 * A populated snapshot buffer exists
4163 * and there is room to init a new entry.
4165 assert(memorystatus_jetsam_snapshot_count
== snapshot
->entry_count
);
4167 unsigned int next
= memorystatus_jetsam_snapshot_count
;
4169 if(memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[next
], (snapshot
->js_gencount
)) == TRUE
) {
4171 entry
= &snapshot_list
[next
];
4172 entry
->killed
= kill_cause
;
4173 entry
->jse_killtime
= killtime
;
4175 snapshot
->entry_count
= ++next
;
4176 memorystatus_jetsam_snapshot_count
= next
;
4178 if (memorystatus_jetsam_snapshot_count
>= memorystatus_jetsam_snapshot_max
) {
4180 * We just used the last slot in the snapshot buffer.
4181 * We only want to log it once... so we do it here
4182 * when we notice we've hit the max.
4184 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
4185 memorystatus_jetsam_snapshot_count
);
4192 if (entry
== NULL
) {
4194 * If we reach here, the snapshot buffer could not be updated.
4195 * Most likely, the buffer is full, in which case we would have
4196 * logged a warning in the previous call.
4198 * For now, we will stop appending snapshot entries.
4199 * When the buffer is consumed, the snapshot state will reset.
4202 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
4203 p
->p_pid
, p
->p_memstat_effectivepriority
, memorystatus_jetsam_snapshot_count
);
4209 void memorystatus_pages_update(unsigned int pages_avail
)
4211 memorystatus_available_pages
= pages_avail
;
4213 #if VM_PRESSURE_EVENTS
4215 * Since memorystatus_available_pages changes, we should
4216 * re-evaluate the pressure levels on the system and
4217 * check if we need to wake the pressure thread.
4218 * We also update memorystatus_level in that routine.
4220 vm_pressure_response();
4222 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
4224 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
4225 memorystatus_thread_wake();
4228 #else /* VM_PRESSURE_EVENTS */
4230 boolean_t critical
, delta
;
4232 if (!memorystatus_delta
) {
4236 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
4237 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
4238 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
4240 if (critical
|| delta
) {
4241 unsigned int total_pages
;
4243 total_pages
= (unsigned int) atop_64(max_mem
);
4244 #if CONFIG_SECLUDED_MEMORY
4245 total_pages
-= vm_page_secluded_count
;
4246 #endif /* CONFIG_SECLUDED_MEMORY */
4247 memorystatus_level
= memorystatus_available_pages
* 100 / total_pages
;
4248 memorystatus_thread_wake();
4250 #endif /* VM_PRESSURE_EVENTS */
4254 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
)
4257 clock_usec_t tv_usec
;
4259 uint32_t max_pages
= 0;
4260 uint32_t max_pages_lifetime
= 0;
4261 uint32_t purgeable_pages
= 0;
4262 uint64_t internal_pages
= 0;
4263 uint64_t internal_compressed_pages
= 0;
4264 uint64_t purgeable_nonvolatile_pages
= 0;
4265 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4266 uint64_t alternate_accounting_pages
= 0;
4267 uint64_t alternate_accounting_compressed_pages
= 0;
4268 uint64_t iokit_mapped_pages
= 0;
4269 uint64_t page_table_pages
=0;
4270 uint64_t region_count
= 0;
4271 uint64_t cids
[COALITION_NUM_TYPES
];
4273 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
4275 entry
->pid
= p
->p_pid
;
4276 strlcpy(&entry
->name
[0], p
->p_name
, sizeof(entry
->name
));
4277 entry
->priority
= p
->p_memstat_effectivepriority
;
4279 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4280 entry
->pages
= (uint64_t)pages
;
4281 entry
->max_pages
= (uint64_t)max_pages
;
4282 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4283 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4285 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4286 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4287 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4288 &iokit_mapped_pages
, &page_table_pages
);
4290 entry
->jse_internal_pages
= internal_pages
;
4291 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4292 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4293 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4294 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4295 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4296 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4297 entry
->jse_page_table_pages
= page_table_pages
;
4299 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4300 entry
->jse_memory_region_count
= region_count
;
4302 entry
->state
= memorystatus_build_state(p
);
4303 entry
->user_data
= p
->p_memstat_userdata
;
4304 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
4305 entry
->fds
= p
->p_fd
->fd_nfiles
;
4307 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
4308 entry
->cpu_time
.tv_sec
= tv_sec
;
4309 entry
->cpu_time
.tv_usec
= tv_usec
;
4311 assert(p
->p_stats
!= NULL
);
4312 entry
->jse_starttime
= p
->p_stats
->ps_start
; /* abstime process started */
4313 entry
->jse_killtime
= 0; /* abstime jetsam chose to kill process */
4314 entry
->killed
= 0; /* the jetsam kill cause */
4315 entry
->jse_gencount
= gencount
; /* indicates a pass through jetsam thread, when process was targeted to be killed */
4317 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
; /* Most recent timespan spent in idle-band */
4319 proc_coalitionids(p
, cids
);
4320 entry
->jse_coalition_jetsam_id
= cids
[COALITION_TYPE_JETSAM
];
4326 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
4328 kern_return_t kr
= KERN_SUCCESS
;
4329 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
4330 vm_statistics64_data_t vm_stat
;
4332 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
) != KERN_SUCCESS
)) {
4333 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
4334 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
4336 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
4337 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
4338 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
4339 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
4340 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
4341 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
4343 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
4344 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
4345 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
4346 snapshot
->stats
.compressions
= vm_stat
.compressions
;
4347 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
4348 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
4349 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
4354 * Collect vm statistics at boot.
4355 * Called only once (see kern_exec.c)
4356 * Data can be consumed at any time.
4359 memorystatus_init_at_boot_snapshot() {
4360 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
4361 memorystatus_at_boot_snapshot
.entry_count
= 0;
4362 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
4363 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
4367 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
4370 unsigned int b
= 0, i
= 0;
4372 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4373 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4374 unsigned int snapshot_max
= 0;
4378 * This is an on_demand snapshot
4380 snapshot
= od_snapshot
;
4381 snapshot_list
= od_snapshot
->entries
;
4382 snapshot_max
= ods_list_count
;
4385 * This is a jetsam event snapshot
4387 snapshot
= memorystatus_jetsam_snapshot
;
4388 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4389 snapshot_max
= memorystatus_jetsam_snapshot_max
;
4393 * Init the snapshot header information
4395 memorystatus_init_snapshot_vmstats(snapshot
);
4396 snapshot
->snapshot_time
= mach_absolute_time();
4397 snapshot
->notification_time
= 0;
4398 snapshot
->js_gencount
= 0;
4400 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
4403 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
4405 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
], snapshot
->js_gencount
)) {
4409 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",
4411 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],
4412 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]);
4414 if (++i
== snapshot_max
) {
4419 snapshot
->entry_count
= i
;
4422 /* update the system buffer count */
4423 memorystatus_jetsam_snapshot_count
= i
;
4427 #if DEVELOPMENT || DEBUG
4430 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
) {
4432 memorystatus_jetsam_panic_options_t debug
;
4434 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
4438 ret
= copyin(buffer
, &debug
, buffer_size
);
4443 /* Panic bits match kMemorystatusKilled* enum */
4444 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
4446 /* Copyout new value */
4447 debug
.data
= memorystatus_jetsam_panic_debug
;
4448 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
4454 * Triggers a sort_order on a specified jetsam priority band.
4455 * This is for testing only, used to force a path through the sort
4459 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
) {
4463 unsigned int bucket_index
= 0;
4465 if (priority
== -1) {
4466 /* Use as shorthand for default priority */
4467 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
4469 bucket_index
= (unsigned int)priority
;
4472 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
4477 #endif /* DEVELOPMENT || DEBUG */
4480 * Jetsam the first process in the queue.
4483 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
,
4484 int32_t *priority
, uint32_t *errors
)
4487 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4488 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4492 uint64_t killtime
= 0;
4494 clock_usec_t tv_usec
;
4497 #ifndef CONFIG_FREEZE
4501 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4502 memorystatus_available_pages
, 0, 0, 0, 0);
4505 if (sort_flag
== TRUE
) {
4506 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4511 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4513 #if DEVELOPMENT || DEBUG
4515 int procSuspendedForDiagnosis
;
4516 #endif /* DEVELOPMENT || DEBUG */
4519 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4521 #if DEVELOPMENT || DEBUG
4522 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4523 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4524 #endif /* DEVELOPMENT || DEBUG */
4527 aPid_ep
= p
->p_memstat_effectivepriority
;
4529 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4530 continue; /* with lock held */
4533 #if DEVELOPMENT || DEBUG
4534 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4535 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4538 #endif /* DEVELOPMENT || DEBUG */
4540 if (cause
== kMemorystatusKilledVnodes
)
4543 * If the system runs out of vnodes, we systematically jetsam
4544 * processes in hopes of stumbling onto a vnode gain that helps
4545 * the system recover. The process that happens to trigger
4546 * this path has no known relationship to the vnode consumption.
4547 * We attempt to safeguard that process e.g: do not jetsam it.
4550 if (p
== current_proc()) {
4551 /* do not jetsam the current process */
4558 boolean_t reclaim_proc
= !(p
->p_memstat_state
& (P_MEMSTAT_LOCKED
| P_MEMSTAT_NORECLAIM
));
4559 if (any
|| reclaim_proc
) {
4571 * Capture a snapshot if none exists and:
4572 * - priority was not requested (this is something other than an ambient kill)
4573 * - the priority was requested *and* the targeted process is not at idle priority
4575 if ((memorystatus_jetsam_snapshot_count
== 0) &&
4576 (memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (aPid_ep
!= JETSAM_PRIORITY_IDLE
))))) {
4577 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4578 new_snapshot
= TRUE
;
4582 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4583 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4584 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4585 * acquisition of the proc lock.
4587 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4589 killtime
= mach_absolute_time();
4590 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4591 tv_msec
= tv_usec
/ 1000;
4593 #if DEVELOPMENT || DEBUG
4594 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && activeProcess
) {
4595 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
4596 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_level
);
4597 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
4598 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
4599 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
4600 jetsam_diagnostic_suspended_one_active_proc
= 1;
4601 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
4604 p
= proc_ref_locked(p
);
4607 task_suspend(p
->task
);
4609 *priority
= aPid_ep
;
4617 #endif /* DEVELOPMENT || DEBUG */
4619 /* Shift queue, update stats */
4620 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4622 if (proc_ref_locked(p
) == p
) {
4624 printf("%lu.%02d memorystatus: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4625 (unsigned long)tv_sec
, tv_msec
,
4626 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing top process pid"),
4627 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4628 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4631 * memorystatus_do_kill() drops a reference, so take another one so we can
4632 * continue to use this exit reason even after memorystatus_do_kill()
4635 os_reason_ref(jetsam_reason
);
4637 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4642 *priority
= aPid_ep
;
4650 * Failure - first unwind the state,
4651 * then fall through to restart the search.
4654 proc_rele_locked(p
);
4655 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4656 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4661 * Failure - restart the search.
4663 * We might have raced with "p" exiting on another core, resulting in no
4664 * ref on "p". Or, we may have failed to kill "p".
4666 * Either way, we fall thru to here, leaving the proc in the
4667 * P_MEMSTAT_TERMINATED state.
4669 * And, we hold the the proc_list_lock at this point.
4673 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4681 os_reason_free(jetsam_reason
);
4683 /* Clear snapshot if freshly captured and no target was found */
4684 if (new_snapshot
&& !killed
) {
4686 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4690 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4691 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4697 * Jetsam aggressively
4700 memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
,
4701 int32_t priority_max
, uint32_t *errors
)
4704 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4705 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4708 int32_t aPid_ep
= 0;
4709 unsigned int memorystatus_level_snapshot
= 0;
4710 uint64_t killtime
= 0;
4712 clock_usec_t tv_usec
;
4717 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4718 memorystatus_available_pages
, priority_max
, 0, 0, 0);
4720 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4724 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4726 #if DEVELOPMENT || DEBUG
4728 int procSuspendedForDiagnosis
;
4729 #endif /* DEVELOPMENT || DEBUG */
4731 if ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
) {
4734 * We have raced with next_p running on another core, as it has
4735 * moved to a different jetsam priority band. This means we have
4736 * lost our place in line while traversing the jetsam list. We
4737 * attempt to recover by rewinding to the beginning of the band
4738 * we were already traversing. By doing this, we do not guarantee
4739 * that no process escapes this aggressive march, but we can make
4740 * skipping an entire range of processes less likely. (PR-21069019)
4743 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding %s moved from band %d --> %d\n",
4744 aggr_count
, (*next_p
->p_name
? next_p
->p_name
: "unknown"), i
, next_p
->p_memstat_effectivepriority
);
4746 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4751 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4753 if (p
->p_memstat_effectivepriority
> priority_max
) {
4755 * Bail out of this killing spree if we have
4756 * reached beyond the priority_max jetsam band.
4757 * That is, we kill up to and through the
4758 * priority_max jetsam band.
4764 #if DEVELOPMENT || DEBUG
4765 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4766 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4767 #endif /* DEVELOPMENT || DEBUG */
4770 aPid_ep
= p
->p_memstat_effectivepriority
;
4772 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4776 #if DEVELOPMENT || DEBUG
4777 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4778 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4781 #endif /* DEVELOPMENT || DEBUG */
4784 * Capture a snapshot if none exists.
4786 if (memorystatus_jetsam_snapshot_count
== 0) {
4787 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4788 new_snapshot
= TRUE
;
4792 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4793 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4794 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4795 * acquisition of the proc lock.
4797 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4799 killtime
= mach_absolute_time();
4800 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4801 tv_msec
= tv_usec
/ 1000;
4803 /* Shift queue, update stats */
4804 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4807 * In order to kill the target process, we will drop the proc_list_lock.
4808 * To guaranteee that p and next_p don't disappear out from under the lock,
4809 * we must take a ref on both.
4810 * If we cannot get a reference, then it's likely we've raced with
4811 * that process exiting on another core.
4813 if (proc_ref_locked(p
) == p
) {
4815 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
4819 * We must have raced with next_p exiting on another core.
4820 * Recover by getting the next eligible process in the band.
4823 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
4824 aggr_count
, next_p
->p_pid
, (*next_p
->p_name
? next_p
->p_name
: "(unknown)"));
4827 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
4832 printf("%lu.%01d memorystatus: aggressive%d: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4833 (unsigned long)tv_sec
, tv_msec
, aggr_count
,
4834 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing pid"),
4835 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4836 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4838 memorystatus_level_snapshot
= memorystatus_level
;
4841 * memorystatus_do_kill() drops a reference, so take another one so we can
4842 * continue to use this exit reason even after memorystatus_do_kill()
4845 os_reason_ref(jetsam_reason
);
4846 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4856 * Continue the killing spree.
4860 proc_rele_locked(next_p
);
4863 if (aPid_ep
== JETSAM_PRIORITY_FOREGROUND
&& memorystatus_aggressive_jetsam_lenient
== TRUE
) {
4864 if (memorystatus_level
> memorystatus_level_snapshot
&& ((memorystatus_level
- memorystatus_level_snapshot
) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD
)) {
4865 #if DEVELOPMENT || DEBUG
4866 printf("Disabling Lenient mode after one-time deployment.\n");
4867 #endif /* DEVELOPMENT || DEBUG */
4868 memorystatus_aggressive_jetsam_lenient
= FALSE
;
4877 * Failure - first unwind the state,
4878 * then fall through to restart the search.
4881 proc_rele_locked(p
);
4883 proc_rele_locked(next_p
);
4885 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4886 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4892 * Failure - restart the search at the beginning of
4893 * the band we were already traversing.
4895 * We might have raced with "p" exiting on another core, resulting in no
4896 * ref on "p". Or, we may have failed to kill "p".
4898 * Either way, we fall thru to here, leaving the proc in the
4899 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
4901 * And, we hold the the proc_list_lock at this point.
4904 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4910 os_reason_free(jetsam_reason
);
4912 /* Clear snapshot if freshly captured and no target was found */
4913 if (new_snapshot
&& (kill_count
== 0)) {
4914 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4917 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4918 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4920 if (kill_count
> 0) {
4929 memorystatus_kill_hiwat_proc(uint32_t *errors
)
4932 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4933 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4937 uint64_t killtime
= 0;
4939 clock_usec_t tv_usec
;
4941 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4942 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
4943 memorystatus_available_pages
, 0, 0, 0, 0);
4945 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_HIGHWATER
);
4946 if (jetsam_reason
== OS_REASON_NULL
) {
4947 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
4952 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4954 uint64_t footprint_in_bytes
= 0;
4955 uint64_t memlimit_in_bytes
= 0;
4959 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4962 aPid_ep
= p
->p_memstat_effectivepriority
;
4964 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4968 /* skip if no limit set */
4969 if (p
->p_memstat_memlimit
<= 0) {
4975 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
4976 * Background limits are described via the inactive limit slots.
4977 * Their fatal/non-fatal setting will drive whether or not to be
4978 * considered in this kill path.
4981 /* skip if a currently inapplicable limit is encountered */
4982 if ((p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_BACKGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
4986 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
4987 memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
4988 skip
= (footprint_in_bytes
<= memlimit_in_bytes
);
4990 #if DEVELOPMENT || DEBUG
4991 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
4992 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
4996 #endif /* DEVELOPMENT || DEBUG */
5000 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5011 #if DEVELOPMENT || DEBUG
5012 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5013 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing",
5014 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5015 (footprint_in_bytes
/ (1024ULL * 1024ULL)), /* converted bytes to MB */
5016 p
->p_memstat_memlimit
);
5017 #endif /* DEVELOPMENT || DEBUG */
5019 if (memorystatus_jetsam_snapshot_count
== 0) {
5020 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5021 new_snapshot
= TRUE
;
5024 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5026 killtime
= mach_absolute_time();
5027 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5028 tv_msec
= tv_usec
/ 1000;
5030 #if DEVELOPMENT || DEBUG
5031 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5032 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid
, memorystatus_available_pages
);
5033 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
5034 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
5036 p
= proc_ref_locked(p
);
5039 task_suspend(p
->task
);
5046 #endif /* DEVELOPMENT || DEBUG */
5048 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledHiwat
, killtime
);
5050 if (proc_ref_locked(p
) == p
) {
5053 printf("%lu.%02d memorystatus: jetsam killing pid %d [%s] (highwater %d) - memorystatus_available_pages: %d\n",
5054 (unsigned long)tv_sec
, tv_msec
, aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), aPid_ep
, memorystatus_available_pages
);
5057 * memorystatus_do_kill drops a reference, so take another one so we can
5058 * continue to use this exit reason even after memorystatus_do_kill()
5061 os_reason_ref(jetsam_reason
);
5063 killed
= memorystatus_do_kill(p
, kMemorystatusKilledHiwat
, jetsam_reason
);
5073 * Failure - first unwind the state,
5074 * then fall through to restart the search.
5077 proc_rele_locked(p
);
5078 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5079 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5084 * Failure - restart the search.
5086 * We might have raced with "p" exiting on another core, resulting in no
5087 * ref on "p". Or, we may have failed to kill "p".
5089 * Either way, we fall thru to here, leaving the proc in the
5090 * P_MEMSTAT_TERMINATED state.
5092 * And, we hold the the proc_list_lock at this point.
5096 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5104 os_reason_free(jetsam_reason
);
5106 /* Clear snapshot if freshly captured and no target was found */
5107 if (new_snapshot
&& !killed
) {
5109 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5113 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
5114 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5120 * Jetsam a process pinned in the elevated band.
5122 * Return: true -- at least one pinned process was jetsammed
5123 * false -- no pinned process was jetsammed
5126 memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
)
5129 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5130 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5132 unsigned int i
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
5134 uint64_t killtime
= 0;
5136 clock_usec_t tv_usec
;
5140 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5141 memorystatus_available_pages
, 0, 0, 0, 0);
5145 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5149 next_p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
5152 aPid_ep
= p
->p_memstat_effectivepriority
;
5155 * Only pick a process pinned in this elevated band
5157 if (!(p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
5161 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5166 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5171 #if DEVELOPMENT || DEBUG
5172 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
5174 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5175 memorystatus_available_pages
);
5176 #endif /* DEVELOPMENT || DEBUG */
5178 if (memorystatus_jetsam_snapshot_count
== 0) {
5179 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5180 new_snapshot
= TRUE
;
5183 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5185 killtime
= mach_absolute_time();
5186 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5187 tv_msec
= tv_usec
/ 1000;
5189 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5191 if (proc_ref_locked(p
) == p
) {
5195 printf("%lu.%01d memorystatus: elevated%d: jetsam killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
5196 (unsigned long)tv_sec
, tv_msec
,
5198 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5199 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
5202 * memorystatus_do_kill drops a reference, so take another one so we can
5203 * continue to use this exit reason even after memorystatus_do_kill()
5206 os_reason_ref(jetsam_reason
);
5207 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5217 * Failure - first unwind the state,
5218 * then fall through to restart the search.
5221 proc_rele_locked(p
);
5222 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5223 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5228 * Failure - restart the search.
5230 * We might have raced with "p" exiting on another core, resulting in no
5231 * ref on "p". Or, we may have failed to kill "p".
5233 * Either way, we fall thru to here, leaving the proc in the
5234 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
5236 * And, we hold the the proc_list_lock at this point.
5239 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5245 os_reason_free(jetsam_reason
);
5247 /* Clear snapshot if freshly captured and no target was found */
5248 if (new_snapshot
&& (kill_count
== 0)) {
5250 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5254 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5255 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5261 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
) {
5263 * TODO: allow a general async path
5265 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
5266 * add the appropriate exit reason code mapping.
5268 if ((victim_pid
!= -1) || (cause
!= kMemorystatusKilledVMPageShortage
&& cause
!= kMemorystatusKilledVMThrashing
&&
5269 cause
!= kMemorystatusKilledFCThrashing
)) {
5273 kill_under_pressure_cause
= cause
;
5274 memorystatus_thread_wake();
5279 memorystatus_kill_on_VM_page_shortage(boolean_t async
) {
5281 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
5283 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMPAGESHORTAGE
);
5284 if (jetsam_reason
== OS_REASON_NULL
) {
5285 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
5288 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
, jetsam_reason
);
5293 memorystatus_kill_on_VM_thrashing(boolean_t async
) {
5295 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing
);
5297 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMTHRASHING
);
5298 if (jetsam_reason
== OS_REASON_NULL
) {
5299 printf("memorystatus_kill_on_VM_thrashing -- sync: failed to allocate jetsam reason\n");
5302 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing
, jetsam_reason
);
5307 memorystatus_kill_on_FC_thrashing(boolean_t async
) {
5311 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
5313 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_FCTHRASHING
);
5314 if (jetsam_reason
== OS_REASON_NULL
) {
5315 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
5318 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
, jetsam_reason
);
5323 memorystatus_kill_on_vnode_limit(void) {
5324 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_VNODE
);
5325 if (jetsam_reason
== OS_REASON_NULL
) {
5326 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
5329 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
, jetsam_reason
);
5332 #endif /* CONFIG_JETSAM */
5336 __private_extern__
void
5337 memorystatus_freeze_init(void)
5339 kern_return_t result
;
5342 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
5343 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
5345 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
5347 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
5348 if (result
== KERN_SUCCESS
) {
5349 thread_deallocate(thread
);
5351 panic("Could not create memorystatus_freeze_thread");
5356 * Synchronously freeze the passed proc. Called with a reference to the proc held.
5358 * Returns EINVAL or the value returned by task_freeze().
5361 memorystatus_freeze_process_sync(proc_t p
)
5365 boolean_t memorystatus_freeze_swap_low
= FALSE
;
5367 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5368 memorystatus_available_pages
, 0, 0, 0, 0);
5370 lck_mtx_lock(&freezer_mutex
);
5376 if (memorystatus_freeze_enabled
== FALSE
) {
5380 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5384 if (memorystatus_freeze_update_throttle()) {
5385 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
5386 memorystatus_freeze_throttle_count
++;
5393 uint32_t purgeable
, wired
, clean
, dirty
, state
;
5394 uint32_t max_pages
, pages
, i
;
5398 state
= p
->p_memstat_state
;
5400 /* Ensure the process is eligible for freezing */
5401 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5406 /* Only freeze processes meeting our minimum resident page criteria */
5407 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5408 if (pages
< memorystatus_freeze_pages_min
) {
5413 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5415 unsigned int avail_swap_space
= 0; /* in pages. */
5418 * Freezer backed by the compressor and swap file(s)
5419 * while will hold compressed data.
5421 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5423 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5425 if (max_pages
< memorystatus_freeze_pages_min
) {
5431 * We only have the compressor without any swap.
5433 max_pages
= UINT32_MAX
- 1;
5436 /* Mark as locked temporarily to avoid kill */
5437 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5440 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5442 DTRACE_MEMORYSTATUS6(memorystatus_freeze
, proc_t
, p
, unsigned int, memorystatus_available_pages
, boolean_t
, purgeable
, unsigned int, wired
, uint32_t, clean
, uint32_t, dirty
);
5444 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
5445 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5446 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5447 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5450 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5452 if (ret
== KERN_SUCCESS
) {
5453 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5455 memorystatus_frozen_count
++;
5457 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5459 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5461 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5462 throttle_intervals
[i
].pageouts
+= dirty
;
5466 memorystatus_freeze_pageouts
+= dirty
;
5467 memorystatus_freeze_count
++;
5471 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5478 lck_mtx_unlock(&freezer_mutex
);
5479 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5480 memorystatus_available_pages
, aPid
, 0, 0, 0);
5486 memorystatus_freeze_top_process(boolean_t
*memorystatus_freeze_swap_low
)
5490 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5493 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5494 memorystatus_available_pages
, 0, 0, 0, 0);
5498 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5501 uint32_t purgeable
, wired
, clean
, dirty
;
5504 uint32_t max_pages
= 0;
5508 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5511 state
= p
->p_memstat_state
;
5513 /* Ensure the process is eligible for freezing */
5514 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5515 continue; // with lock held
5518 /* Only freeze processes meeting our minimum resident page criteria */
5519 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5520 if (pages
< memorystatus_freeze_pages_min
) {
5521 continue; // with lock held
5524 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5526 /* Ensure there's enough free space to freeze this process. */
5528 unsigned int avail_swap_space
= 0; /* in pages. */
5531 * Freezer backed by the compressor and swap file(s)
5532 * while will hold compressed data.
5534 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5536 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5538 if (max_pages
< memorystatus_freeze_pages_min
) {
5539 *memorystatus_freeze_swap_low
= TRUE
;
5545 * We only have the compressor pool.
5547 max_pages
= UINT32_MAX
- 1;
5550 /* Mark as locked temporarily to avoid kill */
5551 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5553 p
= proc_ref_locked(p
);
5559 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5561 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
5562 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5563 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5564 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5567 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5570 if (KERN_SUCCESS
== kr
) {
5571 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5573 memorystatus_frozen_count
++;
5575 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5577 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5579 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5580 throttle_intervals
[i
].pageouts
+= dirty
;
5584 memorystatus_freeze_pageouts
+= dirty
;
5585 memorystatus_freeze_count
++;
5589 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5591 /* Return KERN_SUCESS */
5605 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5606 memorystatus_available_pages
, aPid
, 0, 0, 0);
5611 static inline boolean_t
5612 memorystatus_can_freeze_processes(void)
5618 if (memorystatus_suspended_count
) {
5619 uint32_t average_resident_pages
, estimated_processes
;
5621 /* Estimate the number of suspended processes we can fit */
5622 average_resident_pages
= memorystatus_suspended_footprint_total
/ memorystatus_suspended_count
;
5623 estimated_processes
= memorystatus_suspended_count
+
5624 ((memorystatus_available_pages
- memorystatus_available_pages_critical
) / average_resident_pages
);
5626 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
5627 if (estimated_processes
<= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
) {
5628 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_LOW
;
5630 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
5633 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
5634 memorystatus_suspended_count
, average_resident_pages
, estimated_processes
);
5636 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
5651 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
5653 boolean_t can_freeze
= TRUE
;
5655 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
5656 after boot, and is generally is a no-op once we've reached steady state. */
5657 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
5661 /* Check minimum suspended process threshold. */
5662 if (!memorystatus_can_freeze_processes()) {
5665 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT
);
5667 if ( !VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5669 * In-core compressor used for freezing WITHOUT on-disk swap support.
5671 if (vm_compressor_low_on_space()) {
5672 if (*memorystatus_freeze_swap_low
) {
5673 *memorystatus_freeze_swap_low
= TRUE
;
5679 if (*memorystatus_freeze_swap_low
) {
5680 *memorystatus_freeze_swap_low
= FALSE
;
5687 * Freezing WITH on-disk swap support.
5689 * In-core compressor fronts the swap.
5691 if (vm_swap_low_on_space()) {
5692 if (*memorystatus_freeze_swap_low
) {
5693 *memorystatus_freeze_swap_low
= TRUE
;
5705 memorystatus_freeze_update_throttle_interval(mach_timespec_t
*ts
, struct throttle_interval_t
*interval
)
5707 unsigned int freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
5708 if (CMP_MACH_TIMESPEC(ts
, &interval
->ts
) >= 0) {
5709 if (!interval
->max_pageouts
) {
5710 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / (24 * 60)));
5712 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval
->mins
);
5714 interval
->ts
.tv_sec
= interval
->mins
* 60;
5715 interval
->ts
.tv_nsec
= 0;
5716 ADD_MACH_TIMESPEC(&interval
->ts
, ts
);
5717 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
5718 if (interval
->pageouts
> interval
->max_pageouts
) {
5719 interval
->pageouts
-= interval
->max_pageouts
;
5721 interval
->pageouts
= 0;
5723 interval
->throttle
= FALSE
;
5724 } else if (!interval
->throttle
&& interval
->pageouts
>= interval
->max_pageouts
) {
5725 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval
->mins
);
5726 interval
->throttle
= TRUE
;
5729 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
5730 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
5731 interval
->throttle
? "on" : "off");
5735 memorystatus_freeze_update_throttle(void)
5741 boolean_t throttled
= FALSE
;
5743 #if DEVELOPMENT || DEBUG
5744 if (!memorystatus_freeze_throttle_enabled
)
5748 clock_get_system_nanotime(&sec
, &nsec
);
5752 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
5754 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
5755 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
5756 * order to allow for bursts of activity.
5758 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5759 memorystatus_freeze_update_throttle_interval(&ts
, &throttle_intervals
[i
]);
5760 if (throttle_intervals
[i
].throttle
== TRUE
)
5768 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
5770 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
5772 lck_mtx_lock(&freezer_mutex
);
5773 if (memorystatus_freeze_enabled
) {
5774 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5775 /* Only freeze if we've not exceeded our pageout budgets.*/
5776 if (!memorystatus_freeze_update_throttle()) {
5777 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low
);
5779 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
5780 memorystatus_freeze_throttle_count
++; /* Throttled, update stats */
5784 lck_mtx_unlock(&freezer_mutex
);
5786 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
5787 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
5791 sysctl_memorystatus_do_fastwake_warmup_all SYSCTL_HANDLER_ARGS
5793 #pragma unused(oidp, req, arg1, arg2)
5795 /* Need to be root or have entitlement */
5796 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
5800 if (memorystatus_freeze_enabled
== FALSE
) {
5804 do_fastwake_warmup_all();
5809 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_do_fastwake_warmup_all
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
5810 0, 0, &sysctl_memorystatus_do_fastwake_warmup_all
, "I", "");
5812 #endif /* CONFIG_FREEZE */
5814 #if VM_PRESSURE_EVENTS
5816 #if CONFIG_MEMORYSTATUS
5819 memorystatus_send_note(int event_code
, void *data
, size_t data_length
) {
5821 struct kev_msg ev_msg
;
5823 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
5824 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
5825 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
5827 ev_msg
.event_code
= event_code
;
5829 ev_msg
.dv
[0].data_length
= data_length
;
5830 ev_msg
.dv
[0].data_ptr
= data
;
5831 ev_msg
.dv
[1].data_length
= 0;
5833 ret
= kev_post_msg(&ev_msg
);
5835 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
5842 memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t limit_exceeded
) {
5844 boolean_t ret
= FALSE
;
5845 boolean_t found_knote
= FALSE
;
5846 struct knote
*kn
= NULL
;
5847 int send_knote_count
= 0;
5850 * See comment in sysctl_memorystatus_vm_pressure_send.
5853 memorystatus_klist_lock();
5855 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
5856 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
5857 pid_t knote_pid
= knote_proc
->p_pid
;
5859 if (knote_pid
== pid
) {
5861 * By setting the "fflags" here, we are forcing
5862 * a process to deal with the case where it's
5863 * bumping up into its memory limits. If we don't
5864 * do this here, we will end up depending on the
5865 * system pressure snapshot evaluation in
5866 * filt_memorystatus().
5869 if (!limit_exceeded
) {
5872 * Processes on desktop are not expecting to handle a system-wide
5873 * critical or system-wide warning notification from this path.
5874 * Intentionally set only the unambiguous limit warning here.
5876 * If the limit is soft, however, limit this to one notification per
5877 * active/inactive limit (per each registered listener).
5880 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
5884 * Restrict proc_limit_warn notifications when
5885 * non-fatal (soft) limit is at play.
5888 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
5890 * Mark this knote for delivery.
5892 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5894 * And suppress it from future notifications.
5896 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
5900 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
5902 * Mark this knote for delivery.
5904 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5906 * And suppress it from future notifications.
5908 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
5914 * No restriction on proc_limit_warn notifications when
5915 * fatal (hard) limit is at play.
5917 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5923 * Send this notification when a process has exceeded a soft limit,
5926 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
5930 * Restrict critical notifications for soft limits.
5934 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
5936 * Suppress future proc_limit_critical notifications
5937 * for the active soft limit.
5939 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
5940 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
5945 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
5947 * Suppress future proc_limit_critical_notifications
5948 * for the inactive soft limit.
5950 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
5951 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
5957 * We should never be trying to send a critical notification for
5958 * a hard limit... the process would be killed before it could be
5961 panic("Caught sending pid %d a critical warning for a fatal limit.\n", pid
);
5969 if (send_knote_count
> 0) {
5970 KNOTE(&memorystatus_klist
, 0);
5975 memorystatus_klist_unlock();
5981 * Can only be set by the current task on itself.
5984 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
5986 boolean_t set_privilege
= FALSE
;
5988 * Need an entitlement check here?
5990 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
5991 set_privilege
= TRUE
;
5992 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
5993 set_privilege
= FALSE
;
5998 return (task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
));
6002 memorystatus_send_pressure_note(pid_t pid
) {
6003 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
6004 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
6008 memorystatus_send_low_swap_note(void) {
6010 struct knote
*kn
= NULL
;
6012 memorystatus_klist_lock();
6013 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6014 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
6015 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
6016 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
6017 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
6018 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
6019 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
6024 memorystatus_klist_unlock();
6028 memorystatus_bg_pressure_eligible(proc_t p
) {
6029 boolean_t eligible
= FALSE
;
6033 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
6035 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
6036 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
6046 memorystatus_is_foreground_locked(proc_t p
) {
6047 return ((p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
6048 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
));
6052 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
6053 * to access the p_memstat_dirty field.
6056 memorystatus_proc_is_dirty_unsafe(void *v
)
6061 proc_t p
= (proc_t
)v
;
6062 return (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) != 0;
6065 #endif /* CONFIG_MEMORYSTATUS */
6068 * Trigger levels to test the mechanism.
6069 * Can be used via a sysctl.
6071 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
6072 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
6073 #define TEST_PURGEABLE_TRIGGER_ONE 3
6074 #define TEST_PURGEABLE_TRIGGER_ALL 4
6075 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
6076 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
6078 boolean_t memorystatus_manual_testing_on
= FALSE
;
6079 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
6081 extern struct knote
*
6082 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
6085 * This value is the threshold that a process must meet to be considered for scavenging.
6087 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
6089 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
6092 #define VM_PRESSURE_DEBUG(cond, format, ...) \
6094 if (cond) { printf(format, ##__VA_ARGS__); } \
6097 #define VM_PRESSURE_DEBUG(cond, format, ...)
6100 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
6102 void memorystatus_on_pageout_scan_end(void) {
6109 * knote_pressure_level - to check if the knote is registered for this notification level.
6111 * task - task whose bits we'll be modifying
6113 * 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.
6115 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
6120 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
)
6122 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
6124 if (pressure_level_to_clear
&& task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
6126 task_clear_has_been_notified(task
, pressure_level_to_clear
);
6129 task_mark_has_been_notified(task
, pressure_level_to_set
);
6137 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
)
6139 struct knote
*kn
= NULL
;
6141 memorystatus_klist_lock();
6142 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6144 proc_t p
= PROC_NULL
;
6145 struct task
* t
= TASK_NULL
;
6147 p
= knote_get_kq(kn
)->kq_p
;
6149 if (p
!= proc_ref_locked(p
)) {
6156 t
= (struct task
*)(p
->task
);
6158 task_clear_has_been_notified(t
, pressure_level_to_clear
);
6163 memorystatus_klist_unlock();
6166 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
6169 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
);
6172 * Used by the vm_pressure_thread which is
6173 * signalled from within vm_pageout_scan().
6175 static void vm_dispatch_memory_pressure(void);
6176 void consider_vm_pressure_events(void);
6178 void consider_vm_pressure_events(void)
6180 vm_dispatch_memory_pressure();
6182 static void vm_dispatch_memory_pressure(void)
6184 memorystatus_update_vm_pressure(FALSE
);
6187 extern vm_pressure_level_t
6188 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
6191 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
)
6193 struct knote
*kn
= NULL
, *kn_max
= NULL
;
6194 uint64_t resident_max
= 0; /* MB */
6195 struct timeval curr_tstamp
= {0, 0};
6196 int elapsed_msecs
= 0;
6197 int selected_task_importance
= 0;
6198 static int pressure_snapshot
= -1;
6199 boolean_t pressure_increase
= FALSE
;
6201 if (pressure_snapshot
== -1) {
6205 pressure_snapshot
= level
;
6206 pressure_increase
= TRUE
;
6209 if (level
>= pressure_snapshot
) {
6210 pressure_increase
= TRUE
;
6212 pressure_increase
= FALSE
;
6215 pressure_snapshot
= level
;
6218 if (pressure_increase
== TRUE
) {
6220 * We'll start by considering the largest
6221 * unimportant task in our list.
6223 selected_task_importance
= INT_MAX
;
6226 * We'll start by considering the largest
6227 * important task in our list.
6229 selected_task_importance
= 0;
6232 microuptime(&curr_tstamp
);
6234 SLIST_FOREACH(kn
, candidate_list
, kn_selnext
) {
6236 uint64_t resident_size
= 0; /* MB */
6237 proc_t p
= PROC_NULL
;
6238 struct task
* t
= TASK_NULL
;
6239 int curr_task_importance
= 0;
6240 boolean_t consider_knote
= FALSE
;
6241 boolean_t privileged_listener
= FALSE
;
6243 p
= knote_get_kq(kn
)->kq_p
;
6245 if (p
!= proc_ref_locked(p
)) {
6252 #if CONFIG_MEMORYSTATUS
6253 if (target_foreground_process
== TRUE
&& !memorystatus_is_foreground_locked(p
)) {
6255 * Skip process not marked foreground.
6260 #endif /* CONFIG_MEMORYSTATUS */
6262 t
= (struct task
*)(p
->task
);
6264 timevalsub(&curr_tstamp
, &p
->vm_pressure_last_notify_tstamp
);
6265 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6267 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(level
);
6269 if ((kn
->kn_sfflags
& dispatch_level
) == 0) {
6274 #if CONFIG_MEMORYSTATUS
6275 if (target_foreground_process
== FALSE
&& !memorystatus_bg_pressure_eligible(p
)) {
6276 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p
->p_pid
);
6280 #endif /* CONFIG_MEMORYSTATUS */
6282 curr_task_importance
= task_importance_estimate(t
);
6285 * Privileged listeners are only considered in the multi-level pressure scheme
6286 * AND only if the pressure is increasing.
6290 if (task_has_been_notified(t
, level
) == FALSE
) {
6293 * Is this a privileged listener?
6295 if (task_low_mem_privileged_listener(t
, FALSE
, &privileged_listener
) == 0) {
6297 if (privileged_listener
) {
6307 } else if (level
== 0) {
6310 * Task wasn't notified when the pressure was increasing and so
6311 * no need to notify it that the pressure is decreasing.
6313 if ((task_has_been_notified(t
, kVMPressureWarning
) == FALSE
) && (task_has_been_notified(t
, kVMPressureCritical
) == FALSE
)) {
6320 * We don't want a small process to block large processes from
6321 * being notified again. <rdar://problem/7955532>
6323 resident_size
= (get_task_phys_footprint(t
))/(1024*1024ULL); /* MB */
6325 if (resident_size
>= VM_PRESSURE_MINIMUM_RSIZE
) {
6329 * Warning or Critical Pressure.
6331 if (pressure_increase
) {
6332 if ((curr_task_importance
< selected_task_importance
) ||
6333 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6336 * We have found a candidate process which is:
6337 * a) at a lower importance than the current selected process
6339 * b) has importance equal to that of the current selected process but is larger
6342 consider_knote
= TRUE
;
6345 if ((curr_task_importance
> selected_task_importance
) ||
6346 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6349 * We have found a candidate process which is:
6350 * a) at a higher importance than the current selected process
6352 * b) has importance equal to that of the current selected process but is larger
6355 consider_knote
= TRUE
;
6358 } else if (level
== 0) {
6360 * Pressure back to normal.
6362 if ((curr_task_importance
> selected_task_importance
) ||
6363 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6365 consider_knote
= TRUE
;
6369 if (consider_knote
) {
6370 resident_max
= resident_size
;
6372 selected_task_importance
= curr_task_importance
;
6373 consider_knote
= FALSE
; /* reset for the next candidate */
6376 /* There was no candidate with enough resident memory to scavenge */
6377 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p
->p_pid
, resident_size
);
6384 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);
6385 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
);
6391 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
6392 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6393 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6395 uint64_t next_warning_notification_sent_at_ts
= 0;
6396 uint64_t next_critical_notification_sent_at_ts
= 0;
6399 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
6401 struct knote
*kn_max
= NULL
;
6402 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
6403 pid_t target_pid
= -1;
6404 struct klist dispatch_klist
= { NULL
};
6405 proc_t target_proc
= PROC_NULL
;
6406 struct task
*task
= NULL
;
6407 boolean_t found_candidate
= FALSE
;
6409 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
6410 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
6411 boolean_t smoothing_window_started
= FALSE
;
6412 struct timeval smoothing_window_start_tstamp
= {0, 0};
6413 struct timeval curr_tstamp
= {0, 0};
6414 int elapsed_msecs
= 0;
6415 uint64_t curr_ts
= mach_absolute_time();
6418 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
6420 int idle_kill_counter
= 0;
6423 * On desktop we take this opportunity to free up memory pressure
6424 * by immediately killing idle exitable processes. We use a delay
6425 * to avoid overkill. And we impose a max counter as a fail safe
6426 * in case daemons re-launch too fast.
6428 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
6429 if (memorystatus_idle_exit_from_VM() == FALSE
) {
6430 /* No idle exitable processes left to kill */
6433 idle_kill_counter
++;
6435 if (memorystatus_manual_testing_on
== TRUE
) {
6437 * Skip the delay when testing
6438 * the pressure notification scheme.
6441 delay(1000000); /* 1 second */
6444 #endif /* !CONFIG_JETSAM */
6446 if (level_snapshot
!= kVMPressureNormal
) {
6449 * Check to see if we are still in the 'resting' period
6450 * after having notified all clients interested in
6451 * a particular pressure level.
6454 level_snapshot
= memorystatus_vm_pressure_level
;
6456 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6458 if (curr_ts
< next_warning_notification_sent_at_ts
) {
6459 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6460 return KERN_SUCCESS
;
6462 } else if (level_snapshot
== kVMPressureCritical
) {
6464 if (curr_ts
< next_critical_notification_sent_at_ts
) {
6465 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6466 return KERN_SUCCESS
;
6474 * There is a race window here. But it's not clear
6475 * how much we benefit from having extra synchronization.
6477 level_snapshot
= memorystatus_vm_pressure_level
;
6479 if (prev_level_snapshot
> level_snapshot
) {
6481 * Pressure decreased? Let's take a little breather
6482 * and see if this condition stays.
6484 if (smoothing_window_started
== FALSE
) {
6486 smoothing_window_started
= TRUE
;
6487 microuptime(&smoothing_window_start_tstamp
);
6490 microuptime(&curr_tstamp
);
6491 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
6492 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6494 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
6496 delay(INTER_NOTIFICATION_DELAY
);
6501 prev_level_snapshot
= level_snapshot
;
6502 smoothing_window_started
= FALSE
;
6504 memorystatus_klist_lock();
6505 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
6507 if (kn_max
== NULL
) {
6508 memorystatus_klist_unlock();
6511 * No more level-based clients to notify.
6513 * Start the 'resting' window within which clients will not be re-notified.
6516 if (level_snapshot
!= kVMPressureNormal
) {
6517 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6518 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6519 next_warning_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6521 memorystatus_klist_reset_all_for_level(kVMPressureWarning
);
6524 if (level_snapshot
== kVMPressureCritical
) {
6525 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6526 next_critical_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6528 memorystatus_klist_reset_all_for_level(kVMPressureCritical
);
6531 return KERN_FAILURE
;
6534 target_proc
= knote_get_kq(kn_max
)->kq_p
;
6537 if (target_proc
!= proc_ref_locked(target_proc
)) {
6538 target_proc
= PROC_NULL
;
6540 memorystatus_klist_unlock();
6545 target_pid
= target_proc
->p_pid
;
6547 task
= (struct task
*)(target_proc
->task
);
6549 if (level_snapshot
!= kVMPressureNormal
) {
6551 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6553 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, 0, kVMPressureWarning
) == TRUE
) {
6554 found_candidate
= TRUE
;
6557 if (level_snapshot
== kVMPressureCritical
) {
6559 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, 0, kVMPressureCritical
) == TRUE
) {
6560 found_candidate
= TRUE
;
6565 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6567 task_clear_has_been_notified(task
, kVMPressureWarning
);
6568 task_clear_has_been_notified(task
, kVMPressureCritical
);
6570 found_candidate
= TRUE
;
6574 if (found_candidate
== FALSE
) {
6575 proc_rele(target_proc
);
6576 memorystatus_klist_unlock();
6580 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
6582 int knote_pressure_level
= convert_internal_pressure_level_to_dispatch_level(level_snapshot
);
6584 if (is_knote_registered_modify_task_pressure_bits(kn_cur
, knote_pressure_level
, task
, 0, level_snapshot
) == TRUE
) {
6585 proc_t knote_proc
= knote_get_kq(kn_cur
)->kq_p
;
6586 pid_t knote_pid
= knote_proc
->p_pid
;
6587 if (knote_pid
== target_pid
) {
6588 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
6589 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
6594 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
6596 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
6597 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
6598 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
6601 memorystatus_klist_unlock();
6603 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
6604 proc_rele(target_proc
);
6606 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
6610 if (memorystatus_manual_testing_on
== TRUE
) {
6612 * Testing out the pressure notification scheme.
6613 * No need for delays etc.
6617 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
6619 unsigned int page_delta
= 0;
6620 unsigned int skip_delay_page_threshold
= 0;
6622 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
6624 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
6625 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
6627 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
6629 * We are nearing the critcal mark fast and can't afford to wait between
6634 #endif /* CONFIG_JETSAM */
6636 if (sleep_interval
) {
6637 delay(sleep_interval
);
6642 return KERN_SUCCESS
;
6646 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
6648 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6650 switch (internal_pressure_level
) {
6652 case kVMPressureNormal
:
6654 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6658 case kVMPressureWarning
:
6659 case kVMPressureUrgent
:
6661 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
6665 case kVMPressureCritical
:
6667 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
6675 return dispatch_level
;
6679 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
6681 #pragma unused(arg1, arg2, oidp)
6682 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
6684 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
6687 #if DEBUG || DEVELOPMENT
6689 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
,
6690 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6692 #else /* DEBUG || DEVELOPMENT */
6694 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6695 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6697 #endif /* DEBUG || DEVELOPMENT */
6699 extern int memorystatus_purge_on_warning
;
6700 extern int memorystatus_purge_on_critical
;
6703 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
6705 #pragma unused(arg1, arg2)
6709 int pressure_level
= 0;
6710 int trigger_request
= 0;
6713 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
6714 if (error
|| !req
->newptr
) {
6718 memorystatus_manual_testing_on
= TRUE
;
6720 trigger_request
= (level
>> 16) & 0xFFFF;
6721 pressure_level
= (level
& 0xFFFF);
6723 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
6724 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
6727 switch (pressure_level
) {
6728 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
6729 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
6730 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
6737 * The pressure level is being set from user-space.
6738 * And user-space uses the constants in sys/event.h
6739 * So we translate those events to our internal levels here.
6741 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6743 memorystatus_manual_testing_level
= kVMPressureNormal
;
6746 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
6748 memorystatus_manual_testing_level
= kVMPressureWarning
;
6749 force_purge
= memorystatus_purge_on_warning
;
6751 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
6753 memorystatus_manual_testing_level
= kVMPressureCritical
;
6754 force_purge
= memorystatus_purge_on_critical
;
6757 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
6759 /* purge according to the new pressure level */
6760 switch (trigger_request
) {
6761 case TEST_PURGEABLE_TRIGGER_ONE
:
6762 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
6763 if (force_purge
== 0) {
6764 /* no purging requested */
6767 vm_purgeable_object_purge_one_unlocked(force_purge
);
6769 case TEST_PURGEABLE_TRIGGER_ALL
:
6770 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
6771 if (force_purge
== 0) {
6772 /* no purging requested */
6775 while (vm_purgeable_object_purge_one_unlocked(force_purge
));
6779 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
6780 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
6782 memorystatus_update_vm_pressure(TRUE
);
6785 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
6786 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
6788 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
6793 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6794 memorystatus_manual_testing_on
= FALSE
;
6800 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6801 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
6804 extern int memorystatus_purge_on_warning
;
6805 extern int memorystatus_purge_on_urgent
;
6806 extern int memorystatus_purge_on_critical
;
6808 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_warning
, 0, "");
6809 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_urgent
, 0, "");
6810 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_critical
, 0, "");
6813 #endif /* VM_PRESSURE_EVENTS */
6815 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
6817 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
6819 uint32_t list_count
, i
= 0;
6820 memorystatus_priority_entry_t
*list_entry
;
6823 list_count
= memorystatus_list_count
;
6824 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
6826 /* Just a size check? */
6831 /* Otherwise, validate the size of the buffer */
6832 if (*buffer_size
< *list_size
) {
6836 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
6841 memset(*list_ptr
, 0, *list_size
);
6843 *buffer_size
= *list_size
;
6846 list_entry
= *list_ptr
;
6850 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6851 while (p
&& (*list_size
< *buffer_size
)) {
6852 list_entry
->pid
= p
->p_pid
;
6853 list_entry
->priority
= p
->p_memstat_effectivepriority
;
6854 list_entry
->user_data
= p
->p_memstat_userdata
;
6857 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
6858 * Background limits are described via the inactive limit slots.
6859 * So, here, the cached limit should always be valid.
6862 if (p
->p_memstat_memlimit
<= 0) {
6863 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
6865 list_entry
->limit
= p
->p_memstat_memlimit
;
6868 list_entry
->state
= memorystatus_build_state(p
);
6871 *list_size
+= sizeof(memorystatus_priority_entry_t
);
6873 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6878 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
6884 memorystatus_cmd_get_priority_list(user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
6886 boolean_t size_only
;
6887 memorystatus_priority_entry_t
*list
= NULL
;
6890 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
6892 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
6898 error
= copyout(list
, buffer
, list_size
);
6902 *retval
= list_size
;
6907 kfree(list
, buffer_size
);
6916 memorystatus_clear_errors(void)
6921 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
6925 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6927 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
6928 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
6930 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6935 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
6939 memorystatus_update_levels_locked(boolean_t critical_only
) {
6941 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
6944 * If there's an entry in the first bucket, we have idle processes.
6947 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
6948 if (first_bucket
->count
) {
6949 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
6951 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6953 * The critical threshold must never exceed the pressure threshold
6955 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6959 #if DEBUG || DEVELOPMENT
6960 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6961 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6963 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6965 * The critical threshold must never exceed the pressure threshold
6967 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6972 if (memorystatus_jetsam_policy
& kPolicyMoreFree
) {
6973 memorystatus_available_pages_critical
+= memorystatus_policy_more_free_offset_pages
;
6976 if (critical_only
) {
6980 #if VM_PRESSURE_EVENTS
6981 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
6982 #if DEBUG || DEVELOPMENT
6983 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6984 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6991 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
6993 #pragma unused(arg1, arg2, oidp)
6994 int error
= 0, more_free
= 0;
6997 * TODO: Enable this privilege check?
6999 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
7004 error
= sysctl_handle_int(oidp
, &more_free
, 0, req
);
7005 if (error
|| !req
->newptr
)
7008 if ((more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == kPolicyMoreFree
)) ||
7009 (!more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == 0))) {
7012 * No change in state.
7020 memorystatus_jetsam_policy
|= kPolicyMoreFree
;
7022 memorystatus_jetsam_policy
&= ~kPolicyMoreFree
;
7025 memorystatus_update_levels_locked(TRUE
);
7031 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_policy_more_free
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
7032 0, 0, &sysctl_kern_memorystatus_policy_more_free
, "I", "");
7035 * Get the at_boot snapshot
7038 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7039 size_t input_size
= *snapshot_size
;
7042 * The at_boot snapshot has no entry list.
7044 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
7051 * Validate the size of the snapshot buffer
7053 if (input_size
< *snapshot_size
) {
7058 * Update the notification_time only
7060 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
7061 *snapshot
= &memorystatus_at_boot_snapshot
;
7063 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
7064 (long)input_size
, (long)*snapshot_size
, 0);
7069 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7070 size_t input_size
= *snapshot_size
;
7071 uint32_t ods_list_count
= memorystatus_list_count
;
7072 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
7074 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
7081 * Validate the size of the snapshot buffer.
7082 * This is inherently racey. May want to revisit
7083 * this error condition and trim the output when
7086 if (input_size
< *snapshot_size
) {
7091 * Allocate and initialize a snapshot buffer.
7093 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
7098 memset(ods
, 0, *snapshot_size
);
7101 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
7105 * Return the kernel allocated, on_demand buffer.
7106 * The caller of this routine will copy the data out
7107 * to user space and then free the kernel allocated
7112 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7113 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
7119 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7120 size_t input_size
= *snapshot_size
;
7122 if (memorystatus_jetsam_snapshot_count
> 0) {
7123 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
7132 if (input_size
< *snapshot_size
) {
7136 *snapshot
= memorystatus_jetsam_snapshot
;
7138 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7139 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
7146 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
7148 boolean_t size_only
;
7149 boolean_t is_default_snapshot
= FALSE
;
7150 boolean_t is_on_demand_snapshot
= FALSE
;
7151 boolean_t is_at_boot_snapshot
= FALSE
;
7152 memorystatus_jetsam_snapshot_t
*snapshot
;
7154 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
7158 is_default_snapshot
= TRUE
;
7159 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
7161 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7163 * Unsupported bit set in flag.
7168 if ((flags
& (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) ==
7169 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7171 * Can't have both set at the same time.
7176 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
7177 is_on_demand_snapshot
= TRUE
;
7179 * When not requesting the size only, the following call will allocate
7180 * an on_demand snapshot buffer, which is freed below.
7182 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
7184 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
7185 is_at_boot_snapshot
= TRUE
;
7186 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
7189 * Invalid flag setting.
7200 * Copy the data out to user space and clear the snapshot buffer.
7201 * If working with the jetsam snapshot,
7202 * clearing the buffer means, reset the count.
7203 * If working with an on_demand snapshot
7204 * clearing the buffer means, free it.
7205 * If working with the at_boot snapshot
7206 * there is nothing to clear or update.
7209 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
7210 if (is_default_snapshot
) {
7212 * The jetsam snapshot is never freed, its count is simply reset.
7215 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
7216 memorystatus_jetsam_snapshot_last_timestamp
= 0;
7221 if (is_on_demand_snapshot
) {
7223 * The on_demand snapshot is always freed,
7224 * even if the copyout failed.
7227 kfree(snapshot
, buffer_size
);
7233 *retval
= buffer_size
;
7240 * Routine: memorystatus_cmd_grp_set_properties
7241 * Purpose: Update properties for a group of processes.
7243 * Supported Properties:
7245 * Move each process out of its effective priority
7246 * band and into a new priority band.
7247 * Maintains relative order from lowest to highest priority.
7248 * In single band, maintains relative order from head to tail.
7250 * eg: before [effectivepriority | pid]
7252 * [17 | p55, p67, p19 ]
7257 * after [ new band | pid]
7258 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7260 * Returns: 0 on success, else non-zero.
7262 * Caveat: We know there is a race window regarding recycled pids.
7263 * A process could be killed before the kernel can act on it here.
7264 * If a pid cannot be found in any of the jetsam priority bands,
7265 * then we simply ignore it. No harm.
7266 * But, if the pid has been recycled then it could be an issue.
7267 * In that scenario, we might move an unsuspecting process to the new
7268 * priority band. It's not clear how the kernel can safeguard
7269 * against this, but it would be an extremely rare case anyway.
7270 * The caller of this api might avoid such race conditions by
7271 * ensuring that the processes passed in the pid list are suspended.
7275 /* This internal structure can expand when we add support for more properties */
7276 typedef struct memorystatus_internal_properties
7279 int32_t priority
; /* see memorytstatus_priority_entry_t : priority */
7280 } memorystatus_internal_properties_t
;
7284 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7286 #pragma unused (flags)
7289 * We only handle setting priority
7294 memorystatus_priority_entry_t
*entries
= NULL
;
7295 uint32_t entry_count
= 0;
7297 /* This will be the ordered proc list */
7298 memorystatus_internal_properties_t
*table
= NULL
;
7299 size_t table_size
= 0;
7300 uint32_t table_count
= 0;
7303 uint32_t bucket_index
= 0;
7304 boolean_t head_insert
;
7305 int32_t new_priority
;
7310 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0) || ((buffer_size
% sizeof(memorystatus_priority_entry_t
)) != 0)) {
7315 entry_count
= (buffer_size
/ sizeof(memorystatus_priority_entry_t
));
7316 if ((entries
= (memorystatus_priority_entry_t
*)kalloc(buffer_size
)) == NULL
) {
7321 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_START
, entry_count
, 0, 0, 0, 0);
7323 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
7327 /* Verify sanity of input priorities */
7328 for (i
=0; i
< entry_count
; i
++) {
7329 if (entries
[i
].priority
== -1) {
7330 /* Use as shorthand for default priority */
7331 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
7332 } else if ((entries
[i
].priority
== system_procs_aging_band
) || (entries
[i
].priority
== applications_aging_band
)) {
7333 /* Both the aging bands are reserved for internal use;
7334 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
7335 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
7336 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7337 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7339 /* Deal with this later */
7340 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
7347 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
7348 if ( (table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
7352 memset(table
, 0, table_size
);
7356 * For each jetsam bucket entry, spin through the input property list.
7357 * When a matching pid is found, populate an adjacent table with the
7358 * appropriate proc pointer and new property values.
7359 * This traversal automatically preserves order from lowest
7360 * to highest priority.
7367 /* Create the ordered table */
7368 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
7369 while (p
&& (table_count
< entry_count
)) {
7370 for (i
=0; i
< entry_count
; i
++ ) {
7371 if (p
->p_pid
== entries
[i
].pid
) {
7372 /* Build the table data */
7373 table
[table_count
].proc
= p
;
7374 table
[table_count
].priority
= entries
[i
].priority
;
7379 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
7382 /* We now have ordered list of procs ready to move */
7383 for (i
=0; i
< table_count
; i
++) {
7387 /* Allow head inserts -- but relative order is now */
7388 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7389 new_priority
= JETSAM_PRIORITY_IDLE
;
7392 new_priority
= table
[i
].priority
;
7393 head_insert
= false;
7397 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7402 * Take appropriate steps if moving proc out of
7403 * either of the aging bands.
7405 if ((p
->p_memstat_effectivepriority
== system_procs_aging_band
) || (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
7406 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7409 memorystatus_update_priority_locked(p
, new_priority
, head_insert
, false);
7415 * if (table_count != entry_count)
7416 * then some pids were not found in a jetsam band.
7417 * harmless but interesting...
7419 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_END
, entry_count
, table_count
, 0, 0, 0);
7423 kfree(entries
, buffer_size
);
7425 kfree(table
, table_size
);
7432 * This routine is used to update a process's jetsam priority position and stored user_data.
7433 * It is not used for the setting of memory limits, which is why the last 6 args to the
7434 * memorystatus_update() call are 0 or FALSE.
7438 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7440 memorystatus_priority_properties_t mpp_entry
;
7442 /* Validate inputs */
7443 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
7447 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
7457 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7462 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
, FALSE
);
7470 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7472 memorystatus_memlimit_properties_t mmp_entry
;
7474 /* Validate inputs */
7475 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7479 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
7482 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
7489 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7490 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7491 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
7492 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7493 * to the task's ledgers via task_set_phys_footprint_limit().
7496 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7498 memorystatus_memlimit_properties_t mmp_entry
;
7500 /* Validate inputs */
7501 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7505 memset (&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
7507 proc_t p
= proc_find(pid
);
7513 * Get the active limit and attributes.
7514 * No locks taken since we hold a reference to the proc.
7517 if (p
->p_memstat_memlimit_active
> 0 ) {
7518 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
7520 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
7523 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
7524 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7528 * Get the inactive limit and attributes
7530 if (p
->p_memstat_memlimit_inactive
<= 0) {
7531 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
7533 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
7535 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
7536 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7540 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
7547 * SPI for kbd - pr24956468
7548 * This is a very simple snapshot that calculates how much a
7549 * process's phys_footprint exceeds a specific memory limit.
7550 * Only the inactive memory limit is supported for now.
7551 * The delta is returned as bytes in excess or zero.
7554 memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7556 uint64_t footprint_in_bytes
= 0;
7557 uint64_t delta_in_bytes
= 0;
7558 int32_t memlimit_mb
= 0;
7559 uint64_t memlimit_bytes
= 0;
7561 /* Validate inputs */
7562 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(uint64_t)) || (flags
!= 0)) {
7566 proc_t p
= proc_find(pid
);
7572 * Get the inactive limit.
7573 * No locks taken since we hold a reference to the proc.
7576 if (p
->p_memstat_memlimit_inactive
<= 0) {
7577 task_convert_phys_footprint_limit(-1, &memlimit_mb
);
7579 memlimit_mb
= p
->p_memstat_memlimit_inactive
;
7582 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
7586 memlimit_bytes
= memlimit_mb
* 1024 * 1024; /* MB to bytes */
7589 * Computed delta always returns >= 0 bytes
7591 if (footprint_in_bytes
> memlimit_bytes
) {
7592 delta_in_bytes
= footprint_in_bytes
- memlimit_bytes
;
7595 error
= copyout(&delta_in_bytes
, buffer
, sizeof(delta_in_bytes
));
7602 memorystatus_cmd_get_pressure_status(int32_t *retval
) {
7605 /* Need privilege for check */
7606 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
7611 /* Inherently racy, so it's not worth taking a lock here */
7612 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7618 memorystatus_get_pressure_status_kdp() {
7619 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7623 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
7625 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
7626 * So, with 2-level HWM preserving previous behavior will map as follows.
7627 * - treat the limit passed in as both an active and inactive limit.
7628 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
7630 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
7631 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
7632 * - so mapping is (active/non-fatal, inactive/non-fatal)
7634 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
7635 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
7636 * - so mapping is (active/fatal, inactive/fatal)
7640 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
) {
7642 memorystatus_memlimit_properties_t entry
;
7644 entry
.memlimit_active
= high_water_mark
;
7645 entry
.memlimit_active_attr
= 0;
7646 entry
.memlimit_inactive
= high_water_mark
;
7647 entry
.memlimit_inactive_attr
= 0;
7649 if (is_fatal_limit
== TRUE
) {
7650 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7651 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7654 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
7659 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
) {
7661 int32_t memlimit_active
;
7662 boolean_t memlimit_active_is_fatal
;
7663 int32_t memlimit_inactive
;
7664 boolean_t memlimit_inactive_is_fatal
;
7665 uint32_t valid_attrs
= 0;
7668 proc_t p
= proc_find(pid
);
7674 * Check for valid attribute flags.
7676 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
7677 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
7681 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
7687 * Setup the active memlimit properties
7689 memlimit_active
= entry
->memlimit_active
;
7690 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7691 memlimit_active_is_fatal
= TRUE
;
7693 memlimit_active_is_fatal
= FALSE
;
7697 * Setup the inactive memlimit properties
7699 memlimit_inactive
= entry
->memlimit_inactive
;
7700 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7701 memlimit_inactive_is_fatal
= TRUE
;
7703 memlimit_inactive_is_fatal
= FALSE
;
7707 * Setting a limit of <= 0 implies that the process has no
7708 * high-water-mark and has no per-task-limit. That means
7709 * the system_wide task limit is in place, which by the way,
7713 if (memlimit_active
<= 0) {
7715 * Enforce the fatal system_wide task limit while process is active.
7717 memlimit_active
= -1;
7718 memlimit_active_is_fatal
= TRUE
;
7721 if (memlimit_inactive
<= 0) {
7723 * Enforce the fatal system_wide task limit while process is inactive.
7725 memlimit_inactive
= -1;
7726 memlimit_inactive_is_fatal
= TRUE
;
7732 * Store the active limit variants in the proc.
7734 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
7737 * Store the inactive limit variants in the proc.
7739 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
7742 * Enforce appropriate limit variant by updating the cached values
7743 * and writing the ledger.
7744 * Limit choice is based on process active/inactive state.
7747 if (memorystatus_highwater_enabled
) {
7749 boolean_t use_active
;
7751 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
7752 * Background limits are described via the inactive limit slots.
7755 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
7756 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
7759 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
7763 /* Enforce the limit by writing to the ledgers */
7764 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
;
7766 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
7767 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
7768 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
7769 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
7770 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit
, proc_t
, p
, int32_t, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1));
7780 * Returns the jetsam priority (effective or requested) of the process
7781 * associated with this task.
7784 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
7787 if (effective_priority
) {
7788 return p
->p_memstat_effectivepriority
;
7790 return p
->p_memstat_requestedpriority
;
7796 #endif /* CONFIG_JETSAM */
7799 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
) {
7801 os_reason_t jetsam_reason
= OS_REASON_NULL
;
7805 #pragma unused(jetsam_reason)
7808 /* Need to be root or have entitlement */
7809 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
7816 * Do not enforce it for snapshots.
7818 if (args
->command
!= MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
) {
7819 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
7825 switch (args
->command
) {
7826 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
7827 error
= memorystatus_cmd_get_priority_list(args
->buffer
, args
->buffersize
, ret
);
7830 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
7831 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7833 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
7834 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7836 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
7837 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7839 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS
:
7840 error
= memorystatus_cmd_get_memlimit_excess_np(args
->pid
, args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7842 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
7843 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7845 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
7846 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7848 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
7849 error
= memorystatus_cmd_get_pressure_status(ret
);
7851 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
7853 * This call does not distinguish between active and inactive limits.
7854 * Default behavior in 2-level HWM world is to set both.
7855 * Non-fatal limit is also assumed for both.
7857 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
7859 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
7861 * This call does not distinguish between active and inactive limits.
7862 * Default behavior in 2-level HWM world is to set both.
7863 * Fatal limit is also assumed for both.
7865 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
7868 #if DEVELOPMENT || DEBUG
7869 case MEMORYSTATUS_CMD_TEST_JETSAM
:
7870 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_GENERIC
);
7871 if (jetsam_reason
== OS_REASON_NULL
) {
7872 printf("memorystatus_control: failed to allocate jetsam reason\n");
7875 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
, jetsam_reason
) ? 0 : EINVAL
;
7877 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
7878 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
7880 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
7881 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
7883 #else /* DEVELOPMENT || DEBUG */
7884 #pragma unused(jetsam_reason)
7885 #endif /* DEVELOPMENT || DEBUG */
7886 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE
:
7887 if (memorystatus_aggressive_jetsam_lenient_allowed
== FALSE
) {
7888 #if DEVELOPMENT || DEBUG
7889 printf("Enabling Lenient Mode\n");
7890 #endif /* DEVELOPMENT || DEBUG */
7892 memorystatus_aggressive_jetsam_lenient_allowed
= TRUE
;
7893 memorystatus_aggressive_jetsam_lenient
= TRUE
;
7897 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE
:
7898 #if DEVELOPMENT || DEBUG
7899 printf("Disabling Lenient mode\n");
7900 #endif /* DEVELOPMENT || DEBUG */
7901 memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
7902 memorystatus_aggressive_jetsam_lenient
= FALSE
;
7905 #endif /* CONFIG_JETSAM */
7906 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
7907 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
7908 error
= memorystatus_low_mem_privileged_listener(args
->command
);
7912 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
:
7913 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
:
7914 error
= memorystatus_update_inactive_jetsam_priority_band(args
->pid
, args
->command
, args
->flags
? TRUE
: FALSE
);
7916 #endif /* CONFIG_JETSAM */
7928 filt_memorystatusattach(struct knote
*kn
)
7932 kn
->kn_flags
|= EV_CLEAR
;
7933 error
= memorystatus_knote_register(kn
);
7935 kn
->kn_flags
= EV_ERROR
;
7936 kn
->kn_data
= error
;
7942 filt_memorystatusdetach(struct knote
*kn
)
7944 memorystatus_knote_unregister(kn
);
7948 filt_memorystatus(struct knote
*kn __unused
, long hint
)
7952 case kMemorystatusNoPressure
:
7953 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
7954 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
7957 case kMemorystatusPressure
:
7958 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
7959 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
7960 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
7962 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
7964 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
7965 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
7969 case kMemorystatusLowSwap
:
7970 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
7971 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
7975 case kMemorystatusProcLimitWarn
:
7976 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
7977 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7981 case kMemorystatusProcLimitCritical
:
7982 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
7983 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
7993 if (kn
->kn_fflags
!= 0) {
7994 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
7995 pid_t knote_pid
= knote_proc
->p_pid
;
7997 printf("filt_memorystatus: sending kn 0x%lx (event 0x%x) for pid (%d)\n",
7998 (unsigned long)kn
, kn
->kn_fflags
, knote_pid
);
8002 return (kn
->kn_fflags
!= 0);
8006 filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
8009 int prev_kn_sfflags
= 0;
8011 memorystatus_klist_lock();
8014 * copy in new kevent settings
8015 * (saving the "desired" data and fflags).
8018 prev_kn_sfflags
= kn
->kn_sfflags
;
8019 kn
->kn_sfflags
= (kev
->fflags
& EVFILT_MEMORYSTATUS_ALL_MASK
);
8022 * Only on desktop do we restrict notifications to
8023 * one per active/inactive state (soft limits only).
8025 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8027 * Is there previous state to preserve?
8029 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8031 * This knote was previously interested in proc_limit_warn,
8032 * so yes, preserve previous state.
8034 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
8035 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8037 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
8038 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8042 * This knote was not previously interested in proc_limit_warn,
8043 * but it is now. Set both states.
8045 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8046 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8050 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8052 * Is there previous state to preserve?
8054 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8056 * This knote was previously interested in proc_limit_critical,
8057 * so yes, preserve previous state.
8059 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
8060 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8062 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
8063 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8067 * This knote was not previously interested in proc_limit_critical,
8068 * but it is now. Set both states.
8070 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8071 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8075 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
8076 kn
->kn_udata
= kev
->udata
;
8079 * reset the output flags based on a
8080 * combination of the old events and
8081 * the new desired event list.
8083 //kn->kn_fflags &= kn->kn_sfflags;
8085 res
= (kn
->kn_fflags
!= 0);
8087 memorystatus_klist_unlock();
8093 filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
8095 #pragma unused(data)
8098 memorystatus_klist_lock();
8099 res
= (kn
->kn_fflags
!= 0);
8101 *kev
= kn
->kn_kevent
;
8102 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
8106 memorystatus_klist_unlock();
8112 memorystatus_klist_lock(void) {
8113 lck_mtx_lock(&memorystatus_klist_mutex
);
8117 memorystatus_klist_unlock(void) {
8118 lck_mtx_unlock(&memorystatus_klist_mutex
);
8122 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
) {
8123 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
8124 klist_init(&memorystatus_klist
);
8128 memorystatus_knote_register(struct knote
*kn
) {
8131 memorystatus_klist_lock();
8134 * Support only userspace visible flags.
8136 if ((kn
->kn_sfflags
& EVFILT_MEMORYSTATUS_ALL_MASK
) == kn
->kn_sfflags
) {
8138 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8139 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8140 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8143 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8144 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8145 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8148 KNOTE_ATTACH(&memorystatus_klist
, kn
);
8154 memorystatus_klist_unlock();
8160 memorystatus_knote_unregister(struct knote
*kn __unused
) {
8161 memorystatus_klist_lock();
8162 KNOTE_DETACH(&memorystatus_klist
, kn
);
8163 memorystatus_klist_unlock();
8168 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
8170 memorystatus_issue_pressure_kevent(boolean_t pressured
) {
8171 memorystatus_klist_lock();
8172 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
8173 memorystatus_klist_unlock();
8176 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
8180 /* Coalition support */
8182 /* sorting info for a particular priority bucket */
8183 typedef struct memstat_sort_info
{
8184 coalition_t msi_coal
;
8185 uint64_t msi_page_count
;
8188 } memstat_sort_info_t
;
8191 * qsort from smallest page count to largest page count
8193 * return < 0 for a < b
8197 static int memstat_asc_cmp(const void *a
, const void *b
)
8199 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
8200 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
8202 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
8206 * Return the number of pids rearranged during this sort.
8209 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
8211 #define MAX_SORT_PIDS 80
8212 #define MAX_COAL_LEADERS 10
8214 unsigned int b
= bucket_index
;
8218 coalition_t coal
= COALITION_NULL
;
8220 int total_pids_moved
= 0;
8224 * The system is typically under memory pressure when in this
8225 * path, hence, we want to avoid dynamic memory allocation.
8227 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
8228 pid_t pid_list
[MAX_SORT_PIDS
];
8230 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8235 * Clear the array that holds coalition leader information
8237 for (i
=0; i
< MAX_COAL_LEADERS
; i
++) {
8238 leaders
[i
].msi_coal
= COALITION_NULL
;
8239 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
8240 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
8241 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
8244 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8246 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
8247 if (nleaders
< MAX_COAL_LEADERS
) {
8248 int coal_ntasks
= 0;
8249 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
8250 leaders
[nleaders
].msi_coal
= coal
;
8251 leaders
[nleaders
].msi_page_count
= coal_page_count
;
8252 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
8253 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
8257 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8258 * Abandoned coalitions will linger at the tail of the priority band
8259 * when this sort session ends.
8260 * TODO: should this be an assert?
8262 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
8263 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
8267 p
=memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8270 if (nleaders
== 0) {
8271 /* Nothing to sort */
8276 * Sort the coalition leader array, from smallest coalition page count
8277 * to largest coalition page count. When inserted in the priority bucket,
8278 * smallest coalition is handled first, resulting in the last to be jetsammed.
8281 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
8285 for (i
= 0; i
< nleaders
; i
++) {
8286 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8287 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
8288 leaders
[i
].msi_ntasks
);
8293 * During coalition sorting, processes in a priority band are rearranged
8294 * by being re-inserted at the head of the queue. So, when handling a
8295 * list, the first process that gets moved to the head of the queue,
8296 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8298 * So, for example, the coalition leader is expected to jetsam last,
8299 * after its coalition members. Therefore, the coalition leader is
8300 * inserted at the head of the queue first.
8302 * After processing a coalition, the jetsam order is as follows:
8303 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8307 * Coalition members are rearranged in the priority bucket here,
8308 * based on their coalition role.
8310 total_pids_moved
= 0;
8311 for (i
=0; i
< nleaders
; i
++) {
8313 /* a bit of bookkeeping */
8316 /* Coalition leaders are jetsammed last, so move into place first */
8317 pid_list
[0] = leaders
[i
].msi_pid
;
8318 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
8320 /* xpc services should jetsam after extensions */
8321 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
8322 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8325 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8326 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8329 /* extensions should jetsam after unmarked processes */
8330 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
8331 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8334 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8335 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8338 /* undefined coalition members should be the first to jetsam */
8339 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
8340 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8343 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8344 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8348 if (pids_moved
== leaders
[i
].msi_ntasks
) {
8350 * All the pids in the coalition were found in this band.
8352 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
8353 pids_moved
, leaders
[i
].msi_ntasks
);
8354 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
8356 * Apparently new coalition members showed up during the sort?
8358 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
8359 pids_moved
, leaders
[i
].msi_ntasks
);
8362 * Apparently not all the pids in the coalition were found in this band?
8364 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
8365 pids_moved
, leaders
[i
].msi_ntasks
);
8369 total_pids_moved
+= pids_moved
;
8373 return(total_pids_moved
);
8378 * Traverse a list of pids, searching for each within the priority band provided.
8379 * If pid is found, move it to the front of the priority band.
8380 * Never searches outside the priority band provided.
8383 * bucket_index - jetsam priority band.
8384 * pid_list - pointer to a list of pids.
8385 * list_sz - number of pids in the list.
8387 * Pid list ordering is important in that,
8388 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8389 * The sort_order is set by the coalition default.
8392 * the number of pids found and hence moved within the priority band.
8395 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
8397 memstat_bucket_t
*current_bucket
;
8401 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
8405 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8409 current_bucket
= &memstat_bucket
[bucket_index
];
8410 for (i
=0; i
< list_sz
; i
++) {
8411 unsigned int b
= bucket_index
;
8413 proc_t aProc
= NULL
;
8417 list_index
= ((list_sz
- 1) - i
);
8418 aPid
= pid_list
[list_index
];
8420 /* never search beyond bucket_index provided */
8421 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8423 if (p
->p_pid
== aPid
) {
8427 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8430 if (aProc
== NULL
) {
8431 /* pid not found in this band, just skip it */
8434 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
8435 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
8441 #endif /* CONFIG_JETSAM */