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>
39 #include <kern/thread_group.h>
41 #include <IOKit/IOBSD.h>
43 #include <libkern/libkern.h>
44 #include <mach/coalition.h>
45 #include <mach/mach_time.h>
46 #include <mach/task.h>
47 #include <mach/host_priv.h>
48 #include <mach/mach_host.h>
50 #include <pexpert/pexpert.h>
51 #include <sys/coalition.h>
52 #include <sys/kern_event.h>
54 #include <sys/proc_info.h>
55 #include <sys/reason.h>
56 #include <sys/signal.h>
57 #include <sys/signalvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
63 #include <vm/vm_pageout.h>
64 #include <vm/vm_protos.h>
67 #include <vm/vm_map.h>
68 #endif /* CONFIG_FREEZE */
70 #include <sys/kern_memorystatus.h>
72 #include <mach/machine/sdt.h>
73 #include <libkern/section_keywords.h>
75 /* For logging clarity */
76 static const char *memorystatus_kill_cause_name
[] = {
78 "jettisoned" , /* kMemorystatusKilled */
79 "highwater" , /* kMemorystatusKilledHiwat */
80 "vnode-limit" , /* kMemorystatusKilledVnodes */
81 "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
82 "vm-thrashing" , /* kMemorystatusKilledVMThrashing */
83 "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
84 "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
85 "diagnostic" , /* kMemorystatusKilledDiagnostic */
86 "idle-exit" , /* kMemorystatusKilledIdleExit */
87 "zone-map-exhaustion" , /* kMemorystatusKilledZoneMapExhaustion */
91 memorystatus_priority_band_name(int32_t priority
)
94 case JETSAM_PRIORITY_FOREGROUND
:
96 case JETSAM_PRIORITY_AUDIO_AND_ACCESSORY
:
97 return "AUDIO_AND_ACCESSORY";
98 case JETSAM_PRIORITY_CONDUCTOR
:
100 case JETSAM_PRIORITY_HOME
:
102 case JETSAM_PRIORITY_EXECUTIVE
:
104 case JETSAM_PRIORITY_IMPORTANT
:
106 case JETSAM_PRIORITY_CRITICAL
:
113 /* Does cause indicate vm or fc thrashing? */
115 is_reason_thrashing(unsigned cause
)
118 case kMemorystatusKilledVMThrashing
:
119 case kMemorystatusKilledFCThrashing
:
126 /* Is the zone map almost full? */
128 is_reason_zone_map_exhaustion(unsigned cause
)
130 if (cause
== kMemorystatusKilledZoneMapExhaustion
)
136 * Returns the current zone map size and capacity to include in the jetsam snapshot.
137 * Defined in zalloc.c
139 extern void get_zone_map_size(uint64_t *current_size
, uint64_t *capacity
);
142 * Returns the name of the largest zone and its size to include in the jetsam snapshot.
143 * Defined in zalloc.c
145 extern void get_largest_zone_info(char *zone_name
, size_t zone_name_len
, uint64_t *zone_size
);
147 /* These are very verbose printfs(), enable with
148 * MEMORYSTATUS_DEBUG_LOG
150 #if MEMORYSTATUS_DEBUG_LOG
151 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
153 if (cond) { printf(format, ##__VA_ARGS__); } \
156 #define MEMORYSTATUS_DEBUG(cond, format, ...)
160 * Active / Inactive limit support
161 * proc list must be locked
163 * The SET_*** macros are used to initialize a limit
164 * for the first time.
166 * The CACHE_*** macros are use to cache the limit that will
167 * soon be in effect down in the ledgers.
170 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
172 (p)->p_memstat_memlimit_active = (limit); \
174 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
176 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
180 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
182 (p)->p_memstat_memlimit_inactive = (limit); \
184 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
186 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
190 #define CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal) \
192 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
193 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
194 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
197 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
202 #define CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal) \
204 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
205 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
206 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
209 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
215 /* General tunables */
217 unsigned long delta_percentage
= 5;
218 unsigned long critical_threshold_percentage
= 5;
219 unsigned long idle_offset_percentage
= 5;
220 unsigned long pressure_threshold_percentage
= 15;
221 unsigned long freeze_threshold_percentage
= 50;
222 unsigned long policy_more_free_offset_percentage
= 5;
224 /* General memorystatus stuff */
226 struct klist memorystatus_klist
;
227 static lck_mtx_t memorystatus_klist_mutex
;
229 static void memorystatus_klist_lock(void);
230 static void memorystatus_klist_unlock(void);
232 static uint64_t memorystatus_sysprocs_idle_delay_time
= 0;
233 static uint64_t memorystatus_apps_idle_delay_time
= 0;
236 * Memorystatus kevents
239 static int filt_memorystatusattach(struct knote
*kn
, struct kevent_internal_s
*kev
);
240 static void filt_memorystatusdetach(struct knote
*kn
);
241 static int filt_memorystatus(struct knote
*kn
, long hint
);
242 static int filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
243 static int filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
245 SECURITY_READ_ONLY_EARLY(struct filterops
) memorystatus_filtops
= {
246 .f_attach
= filt_memorystatusattach
,
247 .f_detach
= filt_memorystatusdetach
,
248 .f_event
= filt_memorystatus
,
249 .f_touch
= filt_memorystatustouch
,
250 .f_process
= filt_memorystatusprocess
,
254 kMemorystatusNoPressure
= 0x1,
255 kMemorystatusPressure
= 0x2,
256 kMemorystatusLowSwap
= 0x4,
257 kMemorystatusProcLimitWarn
= 0x8,
258 kMemorystatusProcLimitCritical
= 0x10
261 /* Idle guard handling */
263 static int32_t memorystatus_scheduled_idle_demotions_sysprocs
= 0;
264 static int32_t memorystatus_scheduled_idle_demotions_apps
= 0;
266 static thread_call_t memorystatus_idle_demotion_call
;
268 static void memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
);
269 static void memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
);
270 static void memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clean_state
);
271 static void memorystatus_reschedule_idle_demotion_locked(void);
273 static void memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
);
275 int memorystatus_update_priority_for_appnap(proc_t p
, boolean_t is_appnap
);
277 vm_pressure_level_t
convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
279 boolean_t
is_knote_registered_modify_task_pressure_bits(struct knote
*, int, task_t
, vm_pressure_level_t
, vm_pressure_level_t
);
280 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
);
281 void memorystatus_send_low_swap_note(void);
283 int memorystatus_wakeup
= 0;
285 unsigned int memorystatus_level
= 0;
287 static int memorystatus_list_count
= 0;
289 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
291 typedef struct memstat_bucket
{
292 TAILQ_HEAD(, proc
) list
;
296 memstat_bucket_t memstat_bucket
[MEMSTAT_BUCKET_COUNT
];
298 int memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index
);
300 uint64_t memstat_idle_demotion_deadline
= 0;
302 int system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
303 int applications_aging_band
= JETSAM_PRIORITY_IDLE
;
305 #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)))
306 #define isApp(p) (! (p->p_memstat_dirty & P_DIRTY_TRACK))
307 #define isSysProc(p) ((p->p_memstat_dirty & P_DIRTY_TRACK))
309 #define kJetsamAgingPolicyNone (0)
310 #define kJetsamAgingPolicyLegacy (1)
311 #define kJetsamAgingPolicySysProcsReclaimedFirst (2)
312 #define kJetsamAgingPolicyAppsReclaimedFirst (3)
313 #define kJetsamAgingPolicyMax kJetsamAgingPolicyAppsReclaimedFirst
315 unsigned int jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
317 extern int corpse_for_fatal_memkill
;
318 extern unsigned long total_corpses_count(void) __attribute__((pure
));
319 extern void task_purge_all_corpses(void);
320 boolean_t
memorystatus_allowed_vm_map_fork(__unused task_t
);
324 /* Keeping around for future use if we need a utility that can do this OR an app that needs a dynamic adjustment. */
327 sysctl_set_jetsam_aging_policy SYSCTL_HANDLER_ARGS
329 #pragma unused(oidp, arg1, arg2)
331 int error
= 0, val
= 0;
332 memstat_bucket_t
*old_bucket
= 0;
333 int old_system_procs_aging_band
= 0, new_system_procs_aging_band
= 0;
334 int old_applications_aging_band
= 0, new_applications_aging_band
= 0;
335 proc_t p
= NULL
, next_proc
= NULL
;
338 error
= sysctl_io_number(req
, jetsam_aging_policy
, sizeof(int), &val
, NULL
);
339 if (error
|| !req
->newptr
) {
343 if ((val
< 0) || (val
> kJetsamAgingPolicyMax
)) {
344 printf("jetsam: ordering policy sysctl has invalid value - %d\n", val
);
349 * We need to synchronize with any potential adding/removal from aging bands
350 * that might be in progress currently. We use the proc_list_lock() just for
351 * consistency with all the routines dealing with 'aging' processes. We need
352 * a lighterweight lock.
356 old_system_procs_aging_band
= system_procs_aging_band
;
357 old_applications_aging_band
= applications_aging_band
;
361 case kJetsamAgingPolicyNone
:
362 new_system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
363 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
366 case kJetsamAgingPolicyLegacy
:
368 * Legacy behavior where some daemons get a 10s protection once and only before the first clean->dirty->clean transition before going into IDLE band.
370 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
371 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
374 case kJetsamAgingPolicySysProcsReclaimedFirst
:
375 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
376 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
379 case kJetsamAgingPolicyAppsReclaimedFirst
:
380 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
381 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
388 if (old_system_procs_aging_band
&& (old_system_procs_aging_band
!= new_system_procs_aging_band
)) {
390 old_bucket
= &memstat_bucket
[old_system_procs_aging_band
];
391 p
= TAILQ_FIRST(&old_bucket
->list
);
395 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
398 if (new_system_procs_aging_band
== JETSAM_PRIORITY_IDLE
) {
399 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
402 memorystatus_update_priority_locked(p
, new_system_procs_aging_band
, false, true);
410 if (old_applications_aging_band
&& (old_applications_aging_band
!= new_applications_aging_band
)) {
412 old_bucket
= &memstat_bucket
[old_applications_aging_band
];
413 p
= TAILQ_FIRST(&old_bucket
->list
);
417 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
420 if (new_applications_aging_band
== JETSAM_PRIORITY_IDLE
) {
421 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
424 memorystatus_update_priority_locked(p
, new_applications_aging_band
, false, true);
432 jetsam_aging_policy
= val
;
433 system_procs_aging_band
= new_system_procs_aging_band
;
434 applications_aging_band
= new_applications_aging_band
;
441 SYSCTL_PROC(_kern
, OID_AUTO
, set_jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RW
,
442 0, 0, sysctl_set_jetsam_aging_policy
, "I", "Jetsam Aging Policy");
446 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
448 #pragma unused(oidp, arg1, arg2)
450 int error
= 0, val
= 0, old_time_in_secs
= 0;
451 uint64_t old_time_in_ns
= 0;
453 absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time
, &old_time_in_ns
);
454 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
456 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
457 if (error
|| !req
->newptr
) {
461 if ((val
< 0) || (val
> INT32_MAX
)) {
462 printf("jetsam: new idle delay interval has invalid value.\n");
466 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
471 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_sysprocs_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
472 0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time
, "I", "Aging window for system processes");
476 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
478 #pragma unused(oidp, arg1, arg2)
480 int error
= 0, val
= 0, old_time_in_secs
= 0;
481 uint64_t old_time_in_ns
= 0;
483 absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time
, &old_time_in_ns
);
484 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
486 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
487 if (error
|| !req
->newptr
) {
491 if ((val
< 0) || (val
> INT32_MAX
)) {
492 printf("jetsam: new idle delay interval has invalid value.\n");
496 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
501 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_apps_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
502 0, 0, sysctl_jetsam_set_apps_idle_delay_time
, "I", "Aging window for applications");
504 SYSCTL_INT(_kern
, OID_AUTO
, jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RD
, &jetsam_aging_policy
, 0, "");
506 static unsigned int memorystatus_dirty_count
= 0;
508 SYSCTL_INT(_kern
, OID_AUTO
, max_task_pmem
, CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
, &max_task_footprint_mb
, 0, "");
512 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_level
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_level
, 0, "");
514 #endif /* CONFIG_EMBEDDED */
517 memorystatus_get_level(__unused
struct proc
*p
, struct memorystatus_get_level_args
*args
, __unused
int *ret
)
519 user_addr_t level
= 0;
523 if (copyout(&memorystatus_level
, level
, sizeof(memorystatus_level
)) != 0) {
530 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
);
531 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
);
533 static void memorystatus_thread(void *param __unused
, wait_result_t wr __unused
);
537 static int memorystatus_highwater_enabled
= 1; /* Update the cached memlimit data. */
539 static boolean_t
proc_jetsam_state_is_active_locked(proc_t
);
540 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
541 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
544 static int memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
546 static int memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
);
548 static int memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
550 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
);
552 int proc_get_memstat_priority(proc_t
, boolean_t
);
554 static boolean_t memorystatus_idle_snapshot
= 0;
556 unsigned int memorystatus_delta
= 0;
558 /* Jetsam Loop Detection */
559 static boolean_t memorystatus_jld_enabled
= FALSE
; /* Enable jetsam loop detection */
560 static uint32_t memorystatus_jld_eval_period_msecs
= 0; /* Init pass sets this based on device memory size */
561 static int memorystatus_jld_eval_aggressive_count
= 3; /* Raise the priority max after 'n' aggressive loops */
562 static int memorystatus_jld_eval_aggressive_priority_band_max
= 15; /* Kill aggressively up through this band */
565 * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
566 * --- 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.
569 * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
570 * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
572 * - 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.
574 * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
577 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD 25
578 boolean_t memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
579 boolean_t memorystatus_aggressive_jetsam_lenient
= FALSE
;
581 #if DEVELOPMENT || DEBUG
583 * Jetsam Loop Detection tunables.
586 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_period_msecs
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_period_msecs
, 0, "");
587 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_count
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_count
, 0, "");
588 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_priority_band_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_priority_band_max
, 0, "");
589 #endif /* DEVELOPMENT || DEBUG */
591 static uint32_t kill_under_pressure_cause
= 0;
594 * default jetsam snapshot support
596 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot
;
597 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
598 static unsigned int memorystatus_jetsam_snapshot_count
= 0;
599 static unsigned int memorystatus_jetsam_snapshot_max
= 0;
600 static uint64_t memorystatus_jetsam_snapshot_last_timestamp
= 0;
601 static uint64_t memorystatus_jetsam_snapshot_timeout
= 0;
602 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
605 * snapshot support for memstats collected at boot.
607 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot
;
609 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
);
610 static boolean_t
memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
);
611 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
);
613 static void memorystatus_clear_errors(void);
614 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
);
615 static void memorystatus_get_task_phys_footprint_page_counts(task_t task
,
616 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
617 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
618 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
619 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
);
621 static void memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
);
623 static uint32_t memorystatus_build_state(proc_t p
);
624 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
626 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
);
627 static boolean_t
memorystatus_kill_top_process_aggressive(uint32_t cause
, int aggr_count
, int32_t priority_max
, uint32_t *errors
);
628 static boolean_t
memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
);
629 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t *errors
);
631 static boolean_t
memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
);
633 /* Priority Band Sorting Routines */
634 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
);
635 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
);
636 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
);
637 static int memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
);
640 typedef int (*cmpfunc_t
)(const void *a
, const void *b
);
641 extern void qsort(void *a
, size_t n
, size_t es
, cmpfunc_t cmp
);
642 static int memstat_asc_cmp(const void *a
, const void *b
);
646 extern unsigned int vm_page_free_count
;
647 extern unsigned int vm_page_active_count
;
648 extern unsigned int vm_page_inactive_count
;
649 extern unsigned int vm_page_throttled_count
;
650 extern unsigned int vm_page_purgeable_count
;
651 extern unsigned int vm_page_wire_count
;
652 #if CONFIG_SECLUDED_MEMORY
653 extern unsigned int vm_page_secluded_count
;
654 #endif /* CONFIG_SECLUDED_MEMORY */
657 unsigned int memorystatus_available_pages
= (unsigned int)-1;
658 unsigned int memorystatus_available_pages_pressure
= 0;
659 unsigned int memorystatus_available_pages_critical
= 0;
660 static unsigned int memorystatus_available_pages_critical_base
= 0;
661 static unsigned int memorystatus_available_pages_critical_idle_offset
= 0;
663 #if DEVELOPMENT || DEBUG
664 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
666 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
| CTLFLAG_MASKED
| CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
667 #endif /* DEVELOPMENT || DEBUG */
669 static unsigned int memorystatus_jetsam_policy
= kPolicyDefault
;
670 unsigned int memorystatus_policy_more_free_offset_pages
= 0;
671 static void memorystatus_update_levels_locked(boolean_t critical_only
);
672 static unsigned int memorystatus_thread_wasted_wakeup
= 0;
674 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
675 extern void vm_thrashing_jetsam_done(void);
676 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
);
678 int32_t max_kill_priority
= JETSAM_PRIORITY_MAX
;
680 #else /* CONFIG_JETSAM */
682 uint64_t memorystatus_available_pages
= (uint64_t)-1;
683 uint64_t memorystatus_available_pages_pressure
= (uint64_t)-1;
684 uint64_t memorystatus_available_pages_critical
= (uint64_t)-1;
686 int32_t max_kill_priority
= JETSAM_PRIORITY_IDLE
;
687 #endif /* CONFIG_JETSAM */
689 unsigned int memorystatus_frozen_count
= 0;
690 unsigned int memorystatus_suspended_count
= 0;
692 #if VM_PRESSURE_EVENTS
694 boolean_t
memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t exceeded
);
696 vm_pressure_level_t memorystatus_vm_pressure_level
= kVMPressureNormal
;
699 * We use this flag to signal if we have any HWM offenders
700 * on the system. This way we can reduce the number of wakeups
701 * of the memorystatus_thread when the system is between the
702 * "pressure" and "critical" threshold.
704 * The (re-)setting of this variable is done without any locks
705 * or synchronization simply because it is not possible (currently)
706 * to keep track of HWM offenders that drop down below their memory
707 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
708 * by allowing the unguarded modification of this variable.
710 boolean_t memorystatus_hwm_candidates
= 0;
712 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
714 #endif /* VM_PRESSURE_EVENTS */
717 #if DEVELOPMENT || DEBUG
719 lck_grp_attr_t
*disconnect_page_mappings_lck_grp_attr
;
720 lck_grp_t
*disconnect_page_mappings_lck_grp
;
721 static lck_mtx_t disconnect_page_mappings_mutex
;
723 extern boolean_t kill_on_no_paging_space
;
724 #endif /* DEVELOPMENT || DEBUG */
731 boolean_t memorystatus_freeze_enabled
= FALSE
;
732 int memorystatus_freeze_wakeup
= 0;
734 lck_grp_attr_t
*freezer_lck_grp_attr
;
735 lck_grp_t
*freezer_lck_grp
;
736 static lck_mtx_t freezer_mutex
;
738 static inline boolean_t
memorystatus_can_freeze_processes(void);
739 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
741 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
744 static unsigned int memorystatus_freeze_threshold
= 0;
746 static unsigned int memorystatus_freeze_pages_min
= 0;
747 static unsigned int memorystatus_freeze_pages_max
= 0;
749 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
751 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
754 static uint64_t memorystatus_freeze_count
= 0;
755 static uint64_t memorystatus_freeze_pageouts
= 0;
758 static throttle_interval_t throttle_intervals
[] = {
759 { 60, 8, 0, 0, { 0, 0 }, FALSE
}, /* 1 hour intermediate interval, 8x burst */
760 { 24 * 60, 1, 0, 0, { 0, 0 }, FALSE
}, /* 24 hour long interval, no burst */
763 static uint64_t memorystatus_freeze_throttle_count
= 0;
765 static unsigned int memorystatus_suspended_footprint_total
= 0; /* pages */
767 extern uint64_t vm_swap_get_free_space(void);
769 static boolean_t
memorystatus_freeze_update_throttle(void);
771 #endif /* CONFIG_FREEZE */
775 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
777 #if DEVELOPMENT || DEBUG
779 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
782 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index
)
786 int ledger_limit
= 0;
787 unsigned int b
= bucket_index
;
788 boolean_t traverse_all_buckets
= FALSE
;
790 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
791 traverse_all_buckets
= TRUE
;
794 traverse_all_buckets
= FALSE
;
799 * footprint reported in [pages / MB ]
800 * limits reported as:
801 * L-limit proc's Ledger limit
802 * C-limit proc's Cached limit, should match Ledger
803 * A-limit proc's Active limit
804 * IA-limit proc's Inactive limit
805 * F==Fatal, NF==NonFatal
808 printf("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64
);
809 printf("bucket [pid] [pages / MB] [state] [EP / RP] dirty deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
810 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
812 bytes
= get_task_phys_footprint(p
->task
);
813 task_get_phys_footprint_limit(p
->task
, &ledger_limit
);
814 printf("%2d [%5d] [%5lld /%3lldMB] 0x%-8x [%2d / %2d] 0x%-3x %10lld [%3d / %3d%s / %3d%s / %3d%s] %s\n",
816 (bytes
/ PAGE_SIZE_64
), /* task's footprint converted from bytes to pages */
817 (bytes
/ (1024ULL * 1024ULL)), /* task's footprint converted from bytes to MB */
818 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
820 p
->p_memstat_memlimit
,
821 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
822 p
->p_memstat_memlimit_active
,
823 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
824 p
->p_memstat_memlimit_inactive
,
825 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
826 (*p
->p_name
? p
->p_name
: "unknown"));
827 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
829 printf("memorystatus_debug_dump ***END***\n");
833 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
835 #pragma unused(oidp, arg2)
836 int bucket_index
= 0;
838 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
839 if (error
|| !req
->newptr
) {
842 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
843 if (error
|| !req
->newptr
) {
846 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
848 * All jetsam buckets will be dumped.
852 * Only a single bucket will be dumped.
857 memorystatus_debug_dump_bucket_locked(bucket_index
);
859 memorystatus_debug_dump_this_bucket
= bucket_index
;
864 * Debug aid to look at jetsam buckets and proc jetsam fields.
865 * Use this sysctl to act on a particular jetsam bucket.
866 * Writing the sysctl triggers the dump.
867 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
870 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", "");
873 /* Debug aid to aid determination of limit */
876 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
878 #pragma unused(oidp, arg2)
881 int error
, enable
= 0;
882 boolean_t use_active
; /* use the active limit and active limit attributes */
885 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
886 if (error
|| !req
->newptr
) {
890 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
891 if (error
|| !req
->newptr
) {
895 if (!(enable
== 0 || enable
== 1)) {
901 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
903 use_active
= proc_jetsam_state_is_active_locked(p
);
907 if (use_active
== TRUE
) {
908 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
910 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
915 * Disabling limits does not touch the stored variants.
916 * Set the cached limit fields to system_wide defaults.
918 p
->p_memstat_memlimit
= -1;
919 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
924 * Enforce the cached limit by writing to the ledger.
926 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
928 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
931 memorystatus_highwater_enabled
= enable
;
939 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
941 #if VM_PRESSURE_EVENTS
944 * This routine is used for targeted notifications regardless of system memory pressure
945 * and regardless of whether or not the process has already been notified.
946 * It bypasses and has no effect on the only-one-notification per soft-limit policy.
948 * "memnote" is the current user.
952 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
954 #pragma unused(arg1, arg2)
956 int error
= 0, pid
= 0;
957 struct knote
*kn
= NULL
;
958 boolean_t found_knote
= FALSE
;
959 int fflags
= 0; /* filter flags for EVFILT_MEMORYSTATUS */
962 error
= sysctl_handle_quad(oidp
, &value
, 0, req
);
963 if (error
|| !req
->newptr
)
967 * Find the pid in the low 32 bits of value passed in.
969 pid
= (int)(value
& 0xFFFFFFFF);
972 * Find notification in the high 32 bits of the value passed in.
974 fflags
= (int)((value
>> 32) & 0xFFFFFFFF);
977 * For backwards compatibility, when no notification is
978 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
981 fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
982 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
986 * See event.h ... fflags for EVFILT_MEMORYSTATUS
988 if (!((fflags
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
)||
989 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) ||
990 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) ||
991 (fflags
== NOTE_MEMORYSTATUS_LOW_SWAP
) ||
992 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) ||
993 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) ||
994 (((fflags
& NOTE_MEMORYSTATUS_MSL_STATUS
) != 0 &&
995 ((fflags
& ~NOTE_MEMORYSTATUS_MSL_STATUS
) == 0))))) {
997 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags
);
1003 * Forcibly send pid a memorystatus notification.
1006 memorystatus_klist_lock();
1008 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
1009 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
1010 pid_t knote_pid
= knote_proc
->p_pid
;
1012 if (knote_pid
== pid
) {
1014 * Forcibly send this pid a memorystatus notification.
1016 kn
->kn_fflags
= fflags
;
1022 KNOTE(&memorystatus_klist
, 0);
1023 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value
, fflags
, pid
);
1026 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value
, fflags
, pid
);
1030 memorystatus_klist_unlock();
1035 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_QUAD
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1036 0, 0, &sysctl_memorystatus_vm_pressure_send
, "Q", "");
1038 #endif /* VM_PRESSURE_EVENTS */
1040 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
1043 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
1044 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
1045 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
1046 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_policy_more_free_offset_pages
, CTLFLAG_RW
, &memorystatus_policy_more_free_offset_pages
, 0, "");
1048 static unsigned int memorystatus_jetsam_panic_debug
= 0;
1049 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic
= 0;
1051 /* Diagnostic code */
1054 kJetsamDiagnosticModeNone
= 0,
1055 kJetsamDiagnosticModeAll
= 1,
1056 kJetsamDiagnosticModeStopAtFirstActive
= 2,
1057 kJetsamDiagnosticModeCount
1058 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
1060 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
1063 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1065 #pragma unused(arg1, arg2)
1067 const char *diagnosticStrings
[] = {
1068 "jetsam: diagnostic mode: resetting critical level.",
1069 "jetsam: diagnostic mode: will examine all processes",
1070 "jetsam: diagnostic mode: will stop at first active process"
1073 int error
, val
= jetsam_diagnostic_mode
;
1074 boolean_t changed
= FALSE
;
1076 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
1077 if (error
|| !req
->newptr
)
1079 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
1080 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
1086 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
1087 jetsam_diagnostic_mode
= val
;
1089 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
1091 switch (jetsam_diagnostic_mode
) {
1092 case kJetsamDiagnosticModeNone
:
1093 /* Already cleared */
1095 case kJetsamDiagnosticModeAll
:
1096 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
1098 case kJetsamDiagnosticModeStopAtFirstActive
:
1099 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
1102 /* Already validated */
1106 memorystatus_update_levels_locked(FALSE
);
1113 printf("%s\n", diagnosticStrings
[val
]);
1119 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
|CTLFLAG_ANYBODY
,
1120 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
1122 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
1124 #if VM_PRESSURE_EVENTS
1126 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
1128 #endif /* VM_PRESSURE_EVENTS */
1130 #endif /* CONFIG_JETSAM */
1134 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
1136 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
1138 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
1139 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
1141 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_count
, "");
1142 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
1143 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_throttle_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_count
, "");
1144 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
1146 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
1147 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
1149 #define VM_PAGES_FOR_ALL_PROCS (2)
1151 * Manual trigger of freeze and thaw for dev / debug kernels only.
1154 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1156 #pragma unused(arg1, arg2)
1160 if (memorystatus_freeze_enabled
== FALSE
) {
1164 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1165 if (error
|| !req
->newptr
)
1168 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1169 vm_pageout_anonymous_pages();
1174 lck_mtx_lock(&freezer_mutex
);
1178 uint32_t purgeable
, wired
, clean
, dirty
;
1180 uint32_t max_pages
= 0;
1182 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1184 unsigned int avail_swap_space
= 0; /* in pages. */
1187 * Freezer backed by the compressor and swap file(s)
1188 * while will hold compressed data.
1190 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
1192 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
1196 * We only have the compressor without any swap.
1198 max_pages
= UINT32_MAX
- 1;
1201 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
1207 lck_mtx_unlock(&freezer_mutex
);
1211 lck_mtx_unlock(&freezer_mutex
);
1215 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1216 0, 0, &sysctl_memorystatus_freeze
, "I", "");
1219 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1221 #pragma unused(arg1, arg2)
1226 if (memorystatus_freeze_enabled
== FALSE
) {
1230 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1231 if (error
|| !req
->newptr
)
1234 if (pid
== VM_PAGES_FOR_ALL_PROCS
) {
1235 do_fastwake_warmup_all();
1240 error
= task_thaw(p
->task
);
1252 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1253 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
1255 #endif /* CONFIG_FREEZE */
1257 #endif /* DEVELOPMENT || DEBUG */
1259 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
1262 thread_t
*new_thread
);
1264 #if DEVELOPMENT || DEBUG
1267 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1269 #pragma unused(arg1, arg2)
1270 int error
= 0, pid
= 0;
1273 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1274 if (error
|| !req
->newptr
)
1277 lck_mtx_lock(&disconnect_page_mappings_mutex
);
1280 vm_pageout_disconnect_all_pages();
1285 error
= task_disconnect_page_mappings(p
->task
);
1294 lck_mtx_unlock(&disconnect_page_mappings_mutex
);
1299 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_disconnect_page_mappings
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1300 0, 0, &sysctl_memorystatus_disconnect_page_mappings
, "I", "");
1302 #endif /* DEVELOPMENT || DEBUG */
1306 * Picks the sorting routine for a given jetsam priority band.
1309 * bucket_index - jetsam priority band to be sorted.
1310 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1311 * Currently sort_order is only meaningful when handling
1318 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
1320 int coal_sort_order
;
1323 * Verify the jetsam priority
1325 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1329 #if DEVELOPMENT || DEBUG
1330 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1331 coal_sort_order
= COALITION_SORT_DEFAULT
;
1333 coal_sort_order
= sort_order
; /* only used for testing scenarios */
1336 /* Verify default */
1337 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1338 coal_sort_order
= COALITION_SORT_DEFAULT
;
1346 if (memstat_bucket
[bucket_index
].count
== 0) {
1351 switch (bucket_index
) {
1352 case JETSAM_PRIORITY_FOREGROUND
:
1353 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
1355 * Fall back to per process sorting when zero coalitions are found.
1357 memorystatus_sort_by_largest_process_locked(bucket_index
);
1361 memorystatus_sort_by_largest_process_locked(bucket_index
);
1370 * Sort processes by size for a single jetsam bucket.
1373 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
1375 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
1376 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
1377 uint32_t pages
= 0, max_pages
= 0;
1378 memstat_bucket_t
*current_bucket
;
1380 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1384 current_bucket
= &memstat_bucket
[bucket_index
];
1386 p
= TAILQ_FIRST(¤t_bucket
->list
);
1389 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1394 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
1395 /* traversing list until we find next largest process */
1397 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1398 if (pages
> max_pages
) {
1404 if (prev_max_proc
!= max_proc
) {
1405 /* found a larger process, place it in the list */
1406 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1407 if (insert_after_proc
== NULL
) {
1408 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1410 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1412 prev_max_proc
= max_proc
;
1415 insert_after_proc
= max_proc
;
1417 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1421 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
) {
1422 memstat_bucket_t
*current_bucket
;
1425 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1429 current_bucket
= &memstat_bucket
[*bucket_index
];
1430 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1431 if (!next_p
&& search
) {
1432 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1433 current_bucket
= &memstat_bucket
[*bucket_index
];
1434 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1441 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
) {
1442 memstat_bucket_t
*current_bucket
;
1445 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1449 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1450 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1451 current_bucket
= &memstat_bucket
[*bucket_index
];
1452 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1458 __private_extern__
void
1459 memorystatus_init(void)
1461 thread_t thread
= THREAD_NULL
;
1462 kern_return_t result
;
1466 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1467 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1470 #if DEVELOPMENT || DEBUG
1471 disconnect_page_mappings_lck_grp_attr
= lck_grp_attr_alloc_init();
1472 disconnect_page_mappings_lck_grp
= lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr
);
1474 lck_mtx_init(&disconnect_page_mappings_mutex
, disconnect_page_mappings_lck_grp
, NULL
);
1476 if (kill_on_no_paging_space
== TRUE
) {
1477 max_kill_priority
= JETSAM_PRIORITY_MAX
;
1483 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1484 TAILQ_INIT(&memstat_bucket
[i
].list
);
1485 memstat_bucket
[i
].count
= 0;
1487 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1490 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
1491 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
1493 /* Apply overrides */
1494 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1495 if (delta_percentage
== 0) {
1496 delta_percentage
= 5;
1498 assert(delta_percentage
< 100);
1499 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1500 assert(critical_threshold_percentage
< 100);
1501 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1502 assert(idle_offset_percentage
< 100);
1503 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1504 assert(pressure_threshold_percentage
< 100);
1505 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1506 assert(freeze_threshold_percentage
< 100);
1508 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy
,
1509 sizeof (jetsam_aging_policy
))) {
1511 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy
,
1512 sizeof(jetsam_aging_policy
))) {
1514 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1518 if (jetsam_aging_policy
> kJetsamAgingPolicyMax
) {
1519 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1522 switch (jetsam_aging_policy
) {
1524 case kJetsamAgingPolicyNone
:
1525 system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
1526 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1529 case kJetsamAgingPolicyLegacy
:
1531 * Legacy behavior where some daemons get a 10s protection once
1532 * AND only before the first clean->dirty->clean transition before
1533 * going into IDLE band.
1535 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1536 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1539 case kJetsamAgingPolicySysProcsReclaimedFirst
:
1540 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1541 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1544 case kJetsamAgingPolicyAppsReclaimedFirst
:
1545 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1546 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1554 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1555 * band and must be below it in priority. This is so that we don't have to make
1556 * our 'aging' code worry about a mix of processes, some of which need to age
1557 * and some others that need to stay elevated in the jetsam bands.
1559 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> system_procs_aging_band
);
1560 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> applications_aging_band
);
1562 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1563 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof (memorystatus_idle_snapshot
))) {
1564 /* ...no boot-arg, so check the device tree */
1565 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1568 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1569 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1570 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1571 memorystatus_policy_more_free_offset_pages
= (policy_more_free_offset_percentage
/ delta_percentage
) * memorystatus_delta
;
1573 /* Jetsam Loop Detection */
1574 if (max_mem
<= (512 * 1024 * 1024)) {
1575 /* 512 MB devices */
1576 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
1578 /* 1GB and larger devices */
1579 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
1582 memorystatus_jld_enabled
= TRUE
;
1584 /* No contention at this point */
1585 memorystatus_update_levels_locked(FALSE
);
1587 #endif /* CONFIG_JETSAM */
1589 memorystatus_jetsam_snapshot_max
= maxproc
;
1590 memorystatus_jetsam_snapshot
=
1591 (memorystatus_jetsam_snapshot_t
*)kalloc(sizeof(memorystatus_jetsam_snapshot_t
) +
1592 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
1593 if (!memorystatus_jetsam_snapshot
) {
1594 panic("Could not allocate memorystatus_jetsam_snapshot");
1597 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
1599 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
1602 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1605 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &thread
);
1606 if (result
== KERN_SUCCESS
) {
1607 thread_deallocate(thread
);
1609 panic("Could not create memorystatus_thread");
1613 /* Centralised for the purposes of allowing panic-on-jetsam */
1615 vm_run_compactor(void);
1618 * The jetsam no frills kill call
1619 * Return: 0 on success
1620 * error code on failure (EINVAL...)
1623 jetsam_do_kill(proc_t p
, int jetsam_flags
, os_reason_t jetsam_reason
) {
1625 error
= exit_with_reason(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
, jetsam_reason
);
1630 * Wrapper for processes exiting with memorystatus details
1633 memorystatus_do_kill(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
) {
1636 __unused pid_t victim_pid
= p
->p_pid
;
1638 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
1639 victim_pid
, cause
, vm_page_free_count
, 0, 0);
1641 DTRACE_MEMORYSTATUS3(memorystatus_do_kill
, proc_t
, p
, os_reason_t
, jetsam_reason
, uint32_t, cause
);
1642 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1643 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
1644 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
1647 #pragma unused(cause)
1650 if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
1651 printf("memorystatus: killing process %d [%s] in high band %s (%d) - memorystatus_available_pages: %llu\n", p
->p_pid
,
1652 (*p
->p_name
? p
->p_name
: "unknown"),
1653 memorystatus_priority_band_name(p
->p_memstat_effectivepriority
), p
->p_memstat_effectivepriority
,
1654 (uint64_t)memorystatus_available_pages
);
1657 int jetsam_flags
= P_LTERM_JETSAM
;
1659 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
1660 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
1661 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
1662 case kMemorystatusKilledVMThrashing
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
1663 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
1664 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
1665 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
1667 error
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
1669 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
1670 victim_pid
, cause
, vm_page_free_count
, error
, 0);
1674 return (error
== 0);
1682 memorystatus_check_levels_locked(void) {
1685 memorystatus_update_levels_locked(TRUE
);
1686 #else /* CONFIG_JETSAM */
1688 * Nothing to do here currently since we update
1689 * memorystatus_available_pages in vm_pressure_response.
1691 #endif /* CONFIG_JETSAM */
1695 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1696 * For an application: that means no longer in the FG band
1697 * For a daemon: that means no longer in its 'requested' jetsam priority band
1701 memorystatus_update_inactive_jetsam_priority_band(pid_t pid
, uint32_t op_flags
, boolean_t effective_now
)
1704 boolean_t enable
= FALSE
;
1707 if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
) {
1709 } else if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
) {
1718 if ((enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) ||
1719 (!enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == 0))) {
1721 * No change in state.
1729 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1730 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1732 if (effective_now
) {
1733 if (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1734 if(memorystatus_highwater_enabled
) {
1736 * Process is about to transition from
1737 * inactive --> active
1738 * assign active state
1741 boolean_t use_active
= TRUE
;
1742 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
1743 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
1745 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_ELEVATED_INACTIVE
, FALSE
, FALSE
);
1748 if (isProcessInAgingBands(p
)) {
1749 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1754 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1755 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1757 if (effective_now
) {
1758 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1759 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1762 if (isProcessInAgingBands(p
)) {
1763 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1781 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
1784 uint64_t current_time
= 0, idle_delay_time
= 0;
1785 int demote_prio_band
= 0;
1786 memstat_bucket_t
*demotion_bucket
;
1788 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1790 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1792 current_time
= mach_absolute_time();
1796 demote_prio_band
= JETSAM_PRIORITY_IDLE
+ 1;
1798 for (; demote_prio_band
< JETSAM_PRIORITY_MAX
; demote_prio_band
++) {
1800 if (demote_prio_band
!= system_procs_aging_band
&& demote_prio_band
!= applications_aging_band
)
1803 demotion_bucket
= &memstat_bucket
[demote_prio_band
];
1804 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1807 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
1809 assert(p
->p_memstat_idledeadline
);
1811 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
1813 if (current_time
>= p
->p_memstat_idledeadline
) {
1815 if ((isSysProc(p
) &&
1816 ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) != P_DIRTY_IDLE_EXIT_ENABLED
)) || /* system proc marked dirty*/
1817 task_has_assertions((struct task
*)(p
->task
))) { /* has outstanding assertions which might indicate outstanding work too */
1818 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1820 p
->p_memstat_idledeadline
+= idle_delay_time
;
1821 p
= TAILQ_NEXT(p
, p_memstat_list
);
1825 proc_t next_proc
= NULL
;
1827 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
1828 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1830 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false, true);
1837 // No further candidates
1844 memorystatus_reschedule_idle_demotion_locked();
1848 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
1852 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
1854 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1855 boolean_t present_in_apps_aging_bucket
= FALSE
;
1856 uint64_t idle_delay_time
= 0;
1858 if (jetsam_aging_policy
== kJetsamAgingPolicyNone
) {
1862 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
1864 * This process isn't going to be making the trip to the lower bands.
1869 if (isProcessInAgingBands(p
)){
1871 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1872 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) != P_DIRTY_AGING_IN_PROGRESS
);
1875 if (isSysProc(p
) && system_procs_aging_band
) {
1876 present_in_sysprocs_aging_bucket
= TRUE
;
1878 } else if (isApp(p
) && applications_aging_band
) {
1879 present_in_apps_aging_bucket
= TRUE
;
1883 assert(!present_in_sysprocs_aging_bucket
);
1884 assert(!present_in_apps_aging_bucket
);
1886 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",
1887 p
->p_pid
, p
->p_memstat_dirty
, set_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1890 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
1893 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1896 p
->p_memstat_dirty
|= P_DIRTY_AGING_IN_PROGRESS
;
1897 p
->p_memstat_idledeadline
= mach_absolute_time() + idle_delay_time
;
1900 assert(p
->p_memstat_idledeadline
);
1902 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== FALSE
) {
1903 memorystatus_scheduled_idle_demotions_sysprocs
++;
1905 } else if (isApp(p
) && present_in_apps_aging_bucket
== FALSE
) {
1906 memorystatus_scheduled_idle_demotions_apps
++;
1911 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
1913 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1914 boolean_t present_in_apps_aging_bucket
= FALSE
;
1916 if (!system_procs_aging_band
&& !applications_aging_band
) {
1920 if ((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0) {
1924 if (isProcessInAgingBands(p
)) {
1926 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1927 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == P_DIRTY_AGING_IN_PROGRESS
);
1930 if (isSysProc(p
) && system_procs_aging_band
) {
1931 assert(p
->p_memstat_effectivepriority
== system_procs_aging_band
);
1932 assert(p
->p_memstat_idledeadline
);
1933 present_in_sysprocs_aging_bucket
= TRUE
;
1935 } else if (isApp(p
) && applications_aging_band
) {
1936 assert(p
->p_memstat_effectivepriority
== applications_aging_band
);
1937 assert(p
->p_memstat_idledeadline
);
1938 present_in_apps_aging_bucket
= TRUE
;
1942 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1943 p
->p_pid
, clear_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1947 p
->p_memstat_idledeadline
= 0;
1948 p
->p_memstat_dirty
&= ~P_DIRTY_AGING_IN_PROGRESS
;
1951 if (isSysProc(p
) &&present_in_sysprocs_aging_bucket
== TRUE
) {
1952 memorystatus_scheduled_idle_demotions_sysprocs
--;
1953 assert(memorystatus_scheduled_idle_demotions_sysprocs
>= 0);
1955 } else if (isApp(p
) && present_in_apps_aging_bucket
== TRUE
) {
1956 memorystatus_scheduled_idle_demotions_apps
--;
1957 assert(memorystatus_scheduled_idle_demotions_apps
>= 0);
1960 assert((memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
) >= 0);
1964 memorystatus_reschedule_idle_demotion_locked(void) {
1965 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
)) {
1966 if (memstat_idle_demotion_deadline
) {
1967 /* Transitioned 1->0, so cancel next call */
1968 thread_call_cancel(memorystatus_idle_demotion_call
);
1969 memstat_idle_demotion_deadline
= 0;
1972 memstat_bucket_t
*demotion_bucket
;
1973 proc_t p
= NULL
, p1
= NULL
, p2
= NULL
;
1975 if (system_procs_aging_band
) {
1977 demotion_bucket
= &memstat_bucket
[system_procs_aging_band
];
1978 p1
= TAILQ_FIRST(&demotion_bucket
->list
);
1983 if (applications_aging_band
) {
1985 demotion_bucket
= &memstat_bucket
[applications_aging_band
];
1986 p2
= TAILQ_FIRST(&demotion_bucket
->list
);
1989 p
= (p1
->p_memstat_idledeadline
> p2
->p_memstat_idledeadline
) ? p2
: p1
;
1991 p
= (p1
== NULL
) ? p2
: p1
;
1999 assert(p
&& p
->p_memstat_idledeadline
);
2000 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
){
2001 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
2002 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
2013 memorystatus_add(proc_t p
, boolean_t locked
)
2015 memstat_bucket_t
*bucket
;
2017 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
2023 DTRACE_MEMORYSTATUS2(memorystatus_add
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
);
2025 /* Processes marked internal do not have priority tracked */
2026 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2030 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2032 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2033 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
- 1);
2035 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2036 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
- 1);
2038 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2040 * Entering the idle band.
2041 * Record idle start time.
2043 p
->p_memstat_idle_start
= mach_absolute_time();
2046 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
2049 memorystatus_list_count
++;
2051 memorystatus_check_levels_locked();
2063 * Moves a process from one jetsam bucket to another.
2064 * which changes the LRU position of the process.
2066 * Monitors transition between buckets and if necessary
2067 * will update cached memory limits accordingly.
2069 * skip_demotion_check:
2070 * - if the 'jetsam aging policy' is NOT 'legacy':
2071 * When this flag is TRUE, it means we are going
2072 * to age the ripe processes out of the aging bands and into the
2073 * IDLE band and apply their inactive memory limits.
2075 * - if the 'jetsam aging policy' is 'legacy':
2076 * When this flag is TRUE, it might mean the above aging mechanism
2078 * It might be that we have a process that has used up its 'idle deferral'
2079 * stay that is given to it once per lifetime. And in this case, the process
2080 * won't be going through any aging codepaths. But we still need to apply
2081 * the right inactive limits and so we explicitly set this to TRUE if the
2082 * new priority for the process is the IDLE band.
2085 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
)
2087 memstat_bucket_t
*old_bucket
, *new_bucket
;
2089 assert(priority
< MEMSTAT_BUCKET_COUNT
);
2091 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2092 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2096 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2097 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, head_insert
? "head" : "tail");
2099 DTRACE_MEMORYSTATUS3(memorystatus_update_priority
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
, int, priority
);
2101 #if DEVELOPMENT || DEBUG
2102 if (priority
== JETSAM_PRIORITY_IDLE
&& /* if the process is on its way into the IDLE band */
2103 skip_demotion_check
== FALSE
&& /* and it isn't via the path that will set the INACTIVE memlimits */
2104 (p
->p_memstat_dirty
& P_DIRTY_TRACK
) && /* and it has 'DIRTY' tracking enabled */
2105 ((p
->p_memstat_memlimit
!= p
->p_memstat_memlimit_inactive
) || /* and we notice that the current limit isn't the right value (inactive) */
2106 ((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) */
2107 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 */
2108 #endif /* DEVELOPMENT || DEBUG */
2110 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2112 if (skip_demotion_check
== FALSE
) {
2116 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2117 * the processes from the aging bands and balancing the demotion counts.
2118 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2121 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2122 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2124 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2126 } else if (isApp(p
)) {
2129 * Check to see if the application is being lowered in jetsam priority. If so, and:
2130 * - it has an 'elevated inactive jetsam band' attribute, then put it in the JETSAM_PRIORITY_ELEVATED_INACTIVE band.
2131 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2134 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2135 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2138 if (applications_aging_band
) {
2139 if (p
->p_memstat_effectivepriority
== applications_aging_band
) {
2140 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions_apps
+ 1));
2143 if ((jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) && (priority
<= applications_aging_band
)) {
2144 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2145 priority
= applications_aging_band
;
2146 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2153 if ((system_procs_aging_band
&& (priority
== system_procs_aging_band
)) || (applications_aging_band
&& (priority
== applications_aging_band
))) {
2154 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2157 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
2158 old_bucket
->count
--;
2160 new_bucket
= &memstat_bucket
[priority
];
2162 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
2164 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
2165 new_bucket
->count
++;
2167 if (memorystatus_highwater_enabled
) {
2169 boolean_t use_active
;
2172 * If cached limit data is updated, then the limits
2173 * will be enforced by writing to the ledgers.
2175 boolean_t ledger_update_needed
= TRUE
;
2178 * Here, we must update the cached memory limit if the task
2179 * is transitioning between:
2180 * active <--> inactive
2183 * dirty <--> clean is ignored
2185 * We bypass non-idle processes that have opted into dirty tracking because
2186 * a move between buckets does not imply a transition between the
2187 * dirty <--> clean state.
2190 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2192 if (skip_demotion_check
== TRUE
&& priority
== JETSAM_PRIORITY_IDLE
) {
2193 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2196 ledger_update_needed
= FALSE
;
2199 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
2201 * inactive --> active
2203 * assign active state
2205 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2208 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
2210 * active --> inactive
2212 * assign inactive state
2214 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2218 * The transition between jetsam priority buckets apparently did
2219 * not affect active/inactive state.
2220 * This is not unusual... especially during startup when
2221 * processes are getting established in their respective bands.
2223 ledger_update_needed
= FALSE
;
2227 * Enforce the new limits by writing to the ledger
2229 if (ledger_update_needed
) {
2230 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, use_active
, is_fatal
);
2232 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2233 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2234 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
2235 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2240 * Record idle start or idle delta.
2242 if (p
->p_memstat_effectivepriority
== priority
) {
2244 * This process is not transitioning between
2245 * jetsam priority buckets. Do nothing.
2247 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2250 * Transitioning out of the idle priority bucket.
2251 * Record idle delta.
2253 assert(p
->p_memstat_idle_start
!= 0);
2254 now
= mach_absolute_time();
2255 if (now
> p
->p_memstat_idle_start
) {
2256 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2258 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
2260 * Transitioning into the idle priority bucket.
2261 * Record idle start.
2263 p
->p_memstat_idle_start
= mach_absolute_time();
2266 p
->p_memstat_effectivepriority
= priority
;
2268 #if CONFIG_SECLUDED_MEMORY
2269 if (secluded_for_apps
&&
2270 task_could_use_secluded_mem(p
->task
)) {
2271 task_set_can_use_secluded_mem(
2273 (priority
>= JETSAM_PRIORITY_FOREGROUND
));
2275 #endif /* CONFIG_SECLUDED_MEMORY */
2277 memorystatus_check_levels_locked();
2282 * Description: Update the jetsam priority and memory limit attributes for a given process.
2285 * p init this process's jetsam information.
2286 * priority The jetsam priority band
2287 * user_data user specific data, unused by the kernel
2288 * effective guards against race if process's update already occurred
2289 * update_memlimit When true we know this is the init step via the posix_spawn path.
2291 * memlimit_active Value in megabytes; The monitored footprint level while the
2292 * process is active. Exceeding it may result in termination
2293 * based on it's associated fatal flag.
2295 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2296 * this describes whether or not it should be immediately fatal.
2298 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2299 * process is inactive. Exceeding it may result in termination
2300 * based on it's associated fatal flag.
2302 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2303 * this describes whether or not it should be immediatly fatal.
2305 * Returns: 0 Success
2310 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
2311 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
2312 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
)
2315 boolean_t head_insert
= false;
2317 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
);
2319 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
2321 if (priority
== -1) {
2322 /* Use as shorthand for default priority */
2323 priority
= JETSAM_PRIORITY_DEFAULT
;
2324 } else if ((priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
2325 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2326 priority
= JETSAM_PRIORITY_IDLE
;
2327 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
2328 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2329 priority
= JETSAM_PRIORITY_IDLE
;
2331 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
2339 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2341 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
2344 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
2348 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
2350 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2357 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
2358 p
->p_memstat_userdata
= user_data
;
2359 p
->p_memstat_requestedpriority
= priority
;
2361 if (update_memlimit
) {
2363 boolean_t use_active
;
2366 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2367 * Forked processes do not come through this path, so no ledger limits exist.
2368 * (That's why forked processes can consume unlimited memory.)
2371 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2372 p
->p_pid
, priority
, p
->p_memstat_dirty
,
2373 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2374 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2376 if (memlimit_active
<= 0) {
2378 * This process will have a system_wide task limit when active.
2379 * System_wide task limit is always fatal.
2380 * It's quite common to see non-fatal flag passed in here.
2381 * It's not an error, we just ignore it.
2385 * For backward compatibility with some unexplained launchd behavior,
2386 * we allow a zero sized limit. But we still enforce system_wide limit
2387 * when written to the ledgers.
2390 if (memlimit_active
< 0) {
2391 memlimit_active
= -1; /* enforces system_wide task limit */
2393 memlimit_active_is_fatal
= TRUE
;
2396 if (memlimit_inactive
<= 0) {
2398 * This process will have a system_wide task limit when inactive.
2399 * System_wide task limit is always fatal.
2402 memlimit_inactive
= -1;
2403 memlimit_inactive_is_fatal
= TRUE
;
2407 * Initialize the active limit variants for this process.
2409 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
2412 * Initialize the inactive limit variants for this process.
2414 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
2417 * Initialize the cached limits for target process.
2418 * When the target process is dirty tracked, it's typically
2419 * in a clean state. Non dirty tracked processes are
2420 * typically active (Foreground or above).
2421 * But just in case, we don't make assumptions...
2424 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2425 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2428 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2433 * Enforce the cached limit by writing to the ledger.
2435 if (memorystatus_highwater_enabled
) {
2437 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, use_active
, is_fatal
);
2439 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2440 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2441 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
2442 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2447 * We can't add to the aging bands buckets here.
2448 * But, we could be removing it from those buckets.
2449 * Check and take appropriate steps if so.
2452 if (isProcessInAgingBands(p
)) {
2454 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2455 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2457 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
&& priority
== JETSAM_PRIORITY_IDLE
) {
2459 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2460 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2461 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2462 * is any other aging policy, then we don't need to worry because all processes
2463 * will go through the aging bands and then the demotion thread will take care to
2464 * move them into the IDLE band and apply the required limits.
2466 memorystatus_update_priority_locked(p
, priority
, head_insert
, TRUE
);
2470 memorystatus_update_priority_locked(p
, priority
, head_insert
, FALSE
);
2476 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
2482 memorystatus_remove(proc_t p
, boolean_t locked
)
2485 memstat_bucket_t
*bucket
;
2486 boolean_t reschedule
= FALSE
;
2488 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
2494 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2496 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2498 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2500 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
);
2503 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2505 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
);
2513 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2514 uint64_t now
= mach_absolute_time();
2515 if (now
> p
->p_memstat_idle_start
) {
2516 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2520 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
2523 memorystatus_list_count
--;
2525 /* If awaiting demotion to the idle band, clean up */
2527 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2528 memorystatus_reschedule_idle_demotion_locked();
2531 memorystatus_check_levels_locked();
2534 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
2535 memorystatus_frozen_count
--;
2538 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
2539 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
2540 memorystatus_suspended_count
--;
2558 * Validate dirty tracking flags with process state.
2564 * The proc_list_lock is held by the caller.
2568 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
) {
2569 /* See that the process isn't marked for termination */
2570 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
2574 /* Idle exit requires that process be tracked */
2575 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
2576 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2580 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2581 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
2582 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2586 /* Deferral is only relevant if idle exit is specified */
2587 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
2588 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
2596 memorystatus_update_idle_priority_locked(proc_t p
) {
2599 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
2601 assert(isSysProc(p
));
2603 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2605 priority
= (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) ? system_procs_aging_band
: JETSAM_PRIORITY_IDLE
;
2607 priority
= p
->p_memstat_requestedpriority
;
2610 if (priority
!= p
->p_memstat_effectivepriority
) {
2612 if ((jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) &&
2613 (priority
== JETSAM_PRIORITY_IDLE
)) {
2616 * This process is on its way into the IDLE band. The system is
2617 * using 'legacy' jetsam aging policy. That means, this process
2618 * has already used up its idle-deferral aging time that is given
2619 * once per its lifetime. So we need to set the INACTIVE limits
2620 * explicitly because it won't be going through the demotion paths
2621 * that take care to apply the limits appropriately.
2624 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
2627 * This process has the 'elevated inactive jetsam band' attribute.
2628 * So, there will be no trip to IDLE after all.
2629 * Instead, we pin the process in the elevated band,
2630 * where its ACTIVE limits will apply.
2633 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2636 memorystatus_update_priority_locked(p
, priority
, false, true);
2639 memorystatus_update_priority_locked(p
, priority
, false, false);
2645 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
2646 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2647 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2648 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2650 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2651 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2652 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2653 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2654 * band. The deferral can be cleared early by clearing the appropriate flag.
2656 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2657 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2658 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2662 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
) {
2663 unsigned int old_dirty
;
2664 boolean_t reschedule
= FALSE
;
2665 boolean_t already_deferred
= FALSE
;
2666 boolean_t defer_now
= FALSE
;
2669 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
2670 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
2674 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2676 * Process is on its way out.
2682 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2687 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
2692 old_dirty
= p
->p_memstat_dirty
;
2694 /* These bits are cumulative, as per <rdar://problem/11159924> */
2695 if (pcontrol
& PROC_DIRTY_TRACK
) {
2696 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
2699 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
2700 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
2703 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2704 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
2707 if (old_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2708 already_deferred
= TRUE
;
2712 /* This can be set and cleared exactly once. */
2713 if (pcontrol
& PROC_DIRTY_DEFER
) {
2715 if ( !(old_dirty
& P_DIRTY_DEFER
)) {
2716 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
2722 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2723 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
2724 defer_now
? "Y" : "N",
2725 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
2728 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
2729 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
2730 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2732 if (defer_now
&& !already_deferred
) {
2735 * Request to defer a clean process that's idle-exit enabled
2736 * and not already in the jetsam deferred band. Most likely a
2739 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2742 } else if (!defer_now
) {
2745 * The process isn't asking for the 'aging' facility.
2746 * Could be that it is:
2749 if (already_deferred
) {
2751 * already in the aging bands. Traditionally,
2752 * some processes have tried to use this to
2753 * opt out of the 'aging' facility.
2756 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2759 * agnostic to the 'aging' facility. In that case,
2760 * we'll go ahead and opt it in because this is likely
2761 * a new launch (clean process, dirty tracking enabled)
2764 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2773 * We are trying to operate on a dirty process. Dirty processes have to
2774 * be removed from the deferred band. The question is do we reset the
2775 * deferred state or not?
2777 * This could be a legal request like:
2778 * - this process had opted into the 'aging' band
2779 * - but it's now dirty and requests to opt out.
2780 * In this case, we remove the process from the band and reset its
2781 * state too. It'll opt back in properly when needed.
2783 * OR, this request could be a user-space bug. E.g.:
2784 * - this process had opted into the 'aging' band when clean
2785 * - and, then issues another request to again put it into the band except
2786 * this time the process is dirty.
2787 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
2788 * the deferred band with its state intact. So our request below is no-op.
2789 * But we do it here anyways for coverage.
2791 * memorystatus_update_idle_priority_locked()
2792 * single-mindedly treats a dirty process as "cannot be in the aging band".
2795 if (!defer_now
&& already_deferred
) {
2796 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2800 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2802 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2807 memorystatus_update_idle_priority_locked(p
);
2810 memorystatus_reschedule_idle_demotion_locked();
2822 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
) {
2824 boolean_t kill
= false;
2825 boolean_t reschedule
= FALSE
;
2826 boolean_t was_dirty
= FALSE
;
2827 boolean_t now_dirty
= FALSE
;
2829 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2830 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
2834 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2836 * Process is on its way out.
2842 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2847 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2850 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2851 /* Dirty tracking not enabled */
2853 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2855 * Process is set to be terminated and we're attempting to mark it dirty.
2856 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2860 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
2861 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
2862 /* Mark the process as having been dirtied at some point */
2863 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
2864 memorystatus_dirty_count
++;
2866 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
2867 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
2868 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2869 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2871 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2872 /* Kill previously terminated processes if set clean */
2875 p
->p_memstat_dirty
&= ~flag
;
2876 memorystatus_dirty_count
--;
2888 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2891 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
2892 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
2894 /* Manage idle exit deferral, if applied */
2895 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2898 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
2899 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
2901 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
2902 * in that band on it's way to IDLE.
2905 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2907 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2909 * The process will move from its aging band to its higher requested
2912 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2914 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2919 * Process is back from "dirty" to "clean".
2922 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) {
2923 if (mach_absolute_time() >= p
->p_memstat_idledeadline
) {
2925 * The process' deadline has expired. It currently
2926 * does not reside in any of the aging buckets.
2928 * It's on its way to the JETSAM_PRIORITY_IDLE
2929 * bucket via memorystatus_update_idle_priority_locked()
2932 * So all we need to do is reset all the state on the
2933 * process that's related to the aging bucket i.e.
2934 * the AGING_IN_PROGRESS flag and the timer deadline.
2937 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2941 * It still has some protection window left and so
2942 * we just re-arm the timer without modifying any
2943 * state on the process iff it still wants into that band.
2946 if (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2947 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
2953 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2959 memorystatus_update_idle_priority_locked(p
);
2961 if (memorystatus_highwater_enabled
) {
2962 boolean_t ledger_update_needed
= TRUE
;
2963 boolean_t use_active
;
2966 * We are in this path because this process transitioned between
2967 * dirty <--> clean state. Update the cached memory limits.
2970 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2972 * process is pinned in elevated band
2976 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2978 ledger_update_needed
= TRUE
;
2981 * process is clean...but if it has opted into pressured-exit
2982 * we don't apply the INACTIVE limit till the process has aged
2983 * out and is entering the IDLE band.
2984 * See memorystatus_update_priority_locked() for that.
2987 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
2988 ledger_update_needed
= FALSE
;
2990 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
2992 ledger_update_needed
= TRUE
;
2997 * Enforce the new limits by writing to the ledger.
2999 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
3000 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
3001 * We aren't traversing the jetsam bucket list here, so we should be safe.
3002 * See rdar://21394491.
3005 if (ledger_update_needed
&& proc_ref_locked(p
) == p
) {
3007 if (p
->p_memstat_memlimit
> 0) {
3008 ledger_limit
= p
->p_memstat_memlimit
;
3013 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, use_active
, is_fatal
);
3015 proc_rele_locked(p
);
3017 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
3018 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
3019 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
3020 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
3025 /* If the deferral state changed, reschedule the demotion timer */
3027 memorystatus_reschedule_idle_demotion_locked();
3032 if (proc_ref_locked(p
) == p
) {
3034 psignal(p
, SIGKILL
);
3036 proc_rele_locked(p
);
3047 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
) {
3051 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
3053 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
3057 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
3059 * Process is on its way out.
3065 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
3070 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
3071 /* Dirty tracking not enabled */
3076 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
)) == 0) {
3081 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
3082 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
3085 /* This can be set and cleared exactly once. */
3086 if (pcontrol
& PROC_DIRTY_DEFER
) {
3088 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
3090 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER
;
3092 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3093 memorystatus_update_idle_priority_locked(p
);
3094 memorystatus_reschedule_idle_demotion_locked();
3106 memorystatus_dirty_get(proc_t p
) {
3111 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3112 ret
|= PROC_DIRTY_TRACKED
;
3113 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3114 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
3116 if (p
->p_memstat_dirty
& P_DIRTY
) {
3117 ret
|= PROC_DIRTY_IS_DIRTY
;
3119 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
3120 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
3130 memorystatus_on_terminate(proc_t p
) {
3135 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3137 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
3138 /* Clean; mark as terminated and issue SIGKILL */
3141 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3151 memorystatus_on_suspend(proc_t p
)
3155 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3159 p
->p_memstat_suspendedfootprint
= pages
;
3160 memorystatus_suspended_footprint_total
+= pages
;
3161 memorystatus_suspended_count
++;
3163 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
3168 memorystatus_on_resume(proc_t p
)
3178 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
3180 memorystatus_frozen_count
--;
3181 p
->p_memstat_state
|= P_MEMSTAT_PRIOR_THAW
;
3184 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
3185 memorystatus_suspended_count
--;
3190 p
->p_memstat_state
&= ~(P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
);
3196 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
3197 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3203 memorystatus_on_inactivity(proc_t p
)
3207 /* Wake the freeze thread */
3208 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
3213 * The proc_list_lock is held by the caller.
3216 memorystatus_build_state(proc_t p
) {
3217 uint32_t snapshot_state
= 0;
3220 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3221 snapshot_state
|= kMemorystatusSuspended
;
3223 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
3224 snapshot_state
|= kMemorystatusFrozen
;
3226 if (p
->p_memstat_state
& P_MEMSTAT_PRIOR_THAW
) {
3227 snapshot_state
|= kMemorystatusWasThawed
;
3231 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3232 snapshot_state
|= kMemorystatusTracked
;
3234 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3235 snapshot_state
|= kMemorystatusSupportsIdleExit
;
3237 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3238 snapshot_state
|= kMemorystatusDirty
;
3241 return snapshot_state
;
3245 kill_idle_exit_proc(void)
3247 proc_t p
, victim_p
= PROC_NULL
;
3248 uint64_t current_time
;
3249 boolean_t killed
= FALSE
;
3251 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3253 /* Pick next idle exit victim. */
3254 current_time
= mach_absolute_time();
3256 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_IDLE_EXIT
);
3257 if (jetsam_reason
== OS_REASON_NULL
) {
3258 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3263 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
3265 /* No need to look beyond the idle band */
3266 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
3270 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
|P_DIRTY_IS_DIRTY
|P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
3271 if (current_time
>= p
->p_memstat_idledeadline
) {
3272 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3273 victim_p
= proc_ref_locked(p
);
3278 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
3284 printf("memorystatus: killing_idle_process pid %d [%s]\n", victim_p
->p_pid
, (*victim_p
->p_name
? victim_p
->p_name
: "unknown"));
3285 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
, jetsam_reason
);
3286 proc_rele(victim_p
);
3288 os_reason_free(jetsam_reason
);
3295 memorystatus_thread_wake(void) {
3296 thread_wakeup((event_t
)&memorystatus_wakeup
);
3299 extern void vm_pressure_response(void);
3302 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
3305 assert_wait_timeout(&memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, 1000 * NSEC_PER_USEC
);
3307 assert_wait(&memorystatus_wakeup
, THREAD_UNINT
);
3310 return thread_block(continuation
);
3314 memorystatus_avail_pages_below_pressure(void)
3318 * Instead of CONFIG_EMBEDDED for these *avail_pages* routines, we should
3319 * key off of the system having dynamic swap support. With full swap support,
3320 * the system shouldn't really need to worry about various page thresholds.
3322 return (memorystatus_available_pages
<= memorystatus_available_pages_pressure
);
3323 #else /* CONFIG_EMBEDDED */
3325 #endif /* CONFIG_EMBEDDED */
3329 memorystatus_avail_pages_below_critical(void)
3332 return (memorystatus_available_pages
<= memorystatus_available_pages_critical
);
3333 #else /* CONFIG_EMBEDDED */
3335 #endif /* CONFIG_EMBEDDED */
3339 memorystatus_post_snapshot(int32_t priority
, uint32_t cause
)
3342 #pragma unused(cause)
3344 * Don't generate logs for steady-state idle-exit kills,
3345 * unless it is overridden for debug or by the device
3349 return ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
);
3351 #else /* CONFIG_EMBEDDED */
3353 * Don't generate logs for steady-state idle-exit kills,
3355 * - it is overridden for debug or by the device
3358 * - the kill causes are important i.e. not kMemorystatusKilledIdleExit
3361 boolean_t snapshot_eligible_kill_cause
= (is_reason_thrashing(cause
) || is_reason_zone_map_exhaustion(cause
));
3362 return ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
|| snapshot_eligible_kill_cause
);
3363 #endif /* CONFIG_EMBEDDED */
3367 memorystatus_action_needed(void)
3370 return (is_reason_thrashing(kill_under_pressure_cause
) ||
3371 is_reason_zone_map_exhaustion(kill_under_pressure_cause
) ||
3372 memorystatus_available_pages
<= memorystatus_available_pages_pressure
);
3373 #else /* CONFIG_EMBEDDED */
3374 return (is_reason_thrashing(kill_under_pressure_cause
) ||
3375 is_reason_zone_map_exhaustion(kill_under_pressure_cause
));
3376 #endif /* CONFIG_EMBEDDED */
3380 memorystatus_act_on_hiwat_processes(uint32_t *errors
, uint32_t *hwm_kill
, boolean_t
*post_snapshot
, __unused boolean_t
*is_critical
)
3382 boolean_t killed
= memorystatus_kill_hiwat_proc(errors
);
3385 *hwm_kill
= *hwm_kill
+ 1;
3386 *post_snapshot
= TRUE
;
3389 memorystatus_hwm_candidates
= FALSE
;
3393 /* No highwater processes to kill. Continue or stop for now? */
3394 if (!is_reason_thrashing(kill_under_pressure_cause
) &&
3395 !is_reason_zone_map_exhaustion(kill_under_pressure_cause
) &&
3396 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
3398 * We are _not_ out of pressure but we are above the critical threshold and there's:
3399 * - no compressor thrashing
3400 * - enough zone memory
3401 * - no more HWM processes left.
3402 * For now, don't kill any other processes.
3405 if (*hwm_kill
== 0) {
3406 memorystatus_thread_wasted_wakeup
++;
3409 *is_critical
= FALSE
;
3413 #endif /* CONFIG_JETSAM */
3419 memorystatus_act_aggressive(uint32_t cause
, os_reason_t jetsam_reason
, int *jld_idle_kills
, boolean_t
*corpse_list_purged
, boolean_t
*post_snapshot
)
3421 if (memorystatus_jld_enabled
== TRUE
) {
3424 uint32_t errors
= 0;
3426 /* Jetsam Loop Detection - locals */
3427 memstat_bucket_t
*bucket
;
3428 int jld_bucket_count
= 0;
3429 struct timeval jld_now_tstamp
= {0,0};
3430 uint64_t jld_now_msecs
= 0;
3431 int elevated_bucket_count
= 0;
3433 /* Jetsam Loop Detection - statics */
3434 static uint64_t jld_timestamp_msecs
= 0;
3435 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
3436 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
3437 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3439 * Jetsam Loop Detection: attempt to detect
3440 * rapid daemon relaunches in the lower bands.
3443 microuptime(&jld_now_tstamp
);
3446 * Ignore usecs in this calculation.
3447 * msecs granularity is close enough.
3449 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
3452 switch (jetsam_aging_policy
) {
3453 case kJetsamAgingPolicyLegacy
:
3454 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3455 jld_bucket_count
= bucket
->count
;
3456 bucket
= &memstat_bucket
[JETSAM_PRIORITY_AGING_BAND1
];
3457 jld_bucket_count
+= bucket
->count
;
3459 case kJetsamAgingPolicySysProcsReclaimedFirst
:
3460 case kJetsamAgingPolicyAppsReclaimedFirst
:
3461 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3462 jld_bucket_count
= bucket
->count
;
3463 bucket
= &memstat_bucket
[system_procs_aging_band
];
3464 jld_bucket_count
+= bucket
->count
;
3465 bucket
= &memstat_bucket
[applications_aging_band
];
3466 jld_bucket_count
+= bucket
->count
;
3468 case kJetsamAgingPolicyNone
:
3470 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3471 jld_bucket_count
= bucket
->count
;
3475 bucket
= &memstat_bucket
[JETSAM_PRIORITY_ELEVATED_INACTIVE
];
3476 elevated_bucket_count
= bucket
->count
;
3481 * memorystatus_jld_eval_period_msecs is a tunable
3482 * memorystatus_jld_eval_aggressive_count is a tunable
3483 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
3485 if ( (jld_bucket_count
== 0) ||
3486 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
3489 * Refresh evaluation parameters
3491 jld_timestamp_msecs
= jld_now_msecs
;
3492 jld_idle_kill_candidates
= jld_bucket_count
;
3493 *jld_idle_kills
= 0;
3494 jld_eval_aggressive_count
= 0;
3495 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3498 if (*jld_idle_kills
> jld_idle_kill_candidates
) {
3499 jld_eval_aggressive_count
++;
3501 #if DEVELOPMENT || DEBUG
3502 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
3503 jld_eval_aggressive_count
,
3504 jld_timestamp_msecs
,
3506 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
3507 jld_eval_aggressive_count
,
3508 jld_idle_kill_candidates
,
3510 #endif /* DEVELOPMENT || DEBUG */
3512 if ((jld_eval_aggressive_count
== memorystatus_jld_eval_aggressive_count
) &&
3513 (total_corpses_count() > 0) && (*corpse_list_purged
== FALSE
)) {
3515 * If we reach this aggressive cycle, corpses might be causing memory pressure.
3516 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
3517 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
3519 task_purge_all_corpses();
3520 *corpse_list_purged
= TRUE
;
3522 else if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
3524 * Bump up the jetsam priority limit (eg: the bucket index)
3525 * Enforce bucket index sanity.
3527 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
3528 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
3530 * Do nothing. Stick with the default level.
3533 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
3537 /* Visit elevated processes first */
3538 while (elevated_bucket_count
) {
3540 elevated_bucket_count
--;
3543 * memorystatus_kill_elevated_process() drops a reference,
3544 * so take another one so we can continue to use this exit reason
3545 * even after it returns.
3548 os_reason_ref(jetsam_reason
);
3549 killed
= memorystatus_kill_elevated_process(
3552 jld_eval_aggressive_count
,
3556 *post_snapshot
= TRUE
;
3557 if (memorystatus_avail_pages_below_pressure()) {
3559 * Still under pressure.
3560 * Find another pinned processes.
3568 * No pinned processes left to kill.
3569 * Abandon elevated band.
3576 * memorystatus_kill_top_process_aggressive() allocates its own
3577 * jetsam_reason so the kMemorystatusKilledVMThrashing cause
3578 * is consistent throughout the aggressive march.
3580 killed
= memorystatus_kill_top_process_aggressive(
3581 kMemorystatusKilledVMThrashing
,
3582 jld_eval_aggressive_count
,
3583 jld_priority_band_max
,
3587 /* Always generate logs after aggressive kill */
3588 *post_snapshot
= TRUE
;
3589 *jld_idle_kills
= 0;
3602 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
3604 static boolean_t is_vm_privileged
= FALSE
;
3606 boolean_t post_snapshot
= FALSE
;
3607 uint32_t errors
= 0;
3608 uint32_t hwm_kill
= 0;
3609 boolean_t sort_flag
= TRUE
;
3610 boolean_t corpse_list_purged
= FALSE
;
3611 int jld_idle_kills
= 0;
3613 if (is_vm_privileged
== FALSE
) {
3615 * It's the first time the thread has run, so just mark the thread as privileged and block.
3616 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
3618 thread_wire(host_priv_self(), current_thread(), TRUE
);
3619 is_vm_privileged
= TRUE
;
3621 if (vm_restricted_to_single_processor
== TRUE
)
3622 thread_vm_bind_group_add();
3623 thread_set_thread_name(current_thread(), "VM_memorystatus");
3624 memorystatus_thread_block(0, memorystatus_thread
);
3627 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
3628 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
,0);
3631 * Jetsam aware version.
3633 * The VM pressure notification thread is working it's way through clients in parallel.
3635 * So, while the pressure notification thread is targeting processes in order of
3636 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
3637 * any processes that have exceeded their highwater mark.
3639 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
3640 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
3642 while (memorystatus_action_needed()) {
3646 uint64_t jetsam_reason_code
= JETSAM_REASON_INVALID
;
3647 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3649 cause
= kill_under_pressure_cause
;
3651 case kMemorystatusKilledFCThrashing
:
3652 jetsam_reason_code
= JETSAM_REASON_MEMORY_FCTHRASHING
;
3654 case kMemorystatusKilledVMThrashing
:
3655 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMTHRASHING
;
3657 case kMemorystatusKilledZoneMapExhaustion
:
3658 jetsam_reason_code
= JETSAM_REASON_ZONE_MAP_EXHAUSTION
;
3660 case kMemorystatusKilledVMPageShortage
:
3663 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMPAGESHORTAGE
;
3664 cause
= kMemorystatusKilledVMPageShortage
;
3669 boolean_t is_critical
= TRUE
;
3670 if (memorystatus_act_on_hiwat_processes(&errors
, &hwm_kill
, &post_snapshot
, &is_critical
)) {
3671 if (is_critical
== FALSE
) {
3673 * For now, don't kill any other processes.
3681 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, jetsam_reason_code
);
3682 if (jetsam_reason
== OS_REASON_NULL
) {
3683 printf("memorystatus_thread: failed to allocate jetsam reason\n");
3686 if (memorystatus_act_aggressive(cause
, jetsam_reason
, &jld_idle_kills
, &corpse_list_purged
, &post_snapshot
)) {
3691 * memorystatus_kill_top_process() drops a reference,
3692 * so take another one so we can continue to use this exit reason
3693 * even after it returns
3695 os_reason_ref(jetsam_reason
);
3698 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, jetsam_reason
, &priority
, &errors
);
3702 if (memorystatus_post_snapshot(priority
, cause
) == TRUE
) {
3704 post_snapshot
= TRUE
;
3707 /* Jetsam Loop Detection */
3708 if (memorystatus_jld_enabled
== TRUE
) {
3709 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
3713 * We've reached into bands beyond idle deferred.
3714 * We make no attempt to monitor them
3719 if ((priority
>= JETSAM_PRIORITY_UI_SUPPORT
) && (total_corpses_count() > 0) && (corpse_list_purged
== FALSE
)) {
3721 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
3722 * then we attempt to relieve pressure by purging corpse memory.
3724 task_purge_all_corpses();
3725 corpse_list_purged
= TRUE
;
3730 if (memorystatus_avail_pages_below_critical()) {
3732 * Still under pressure and unable to kill a process - purge corpse memory
3734 if (total_corpses_count() > 0) {
3735 task_purge_all_corpses();
3736 corpse_list_purged
= TRUE
;
3739 if (memorystatus_avail_pages_below_critical()) {
3741 * Still under pressure and unable to kill a process - panic
3743 panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)memorystatus_available_pages
);
3750 * We do not want to over-kill when thrashing has been detected.
3751 * To avoid that, we reset the flag here and notify the
3754 if (is_reason_thrashing(kill_under_pressure_cause
)) {
3755 kill_under_pressure_cause
= 0;
3757 vm_thrashing_jetsam_done();
3758 #endif /* CONFIG_JETSAM */
3759 } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause
)) {
3760 kill_under_pressure_cause
= 0;
3763 os_reason_free(jetsam_reason
);
3766 kill_under_pressure_cause
= 0;
3769 memorystatus_clear_errors();
3772 if (post_snapshot
) {
3774 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3775 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
3776 uint64_t timestamp_now
= mach_absolute_time();
3777 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3778 memorystatus_jetsam_snapshot
->js_gencount
++;
3779 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3780 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3782 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3785 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3793 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
3794 memorystatus_available_pages
, 0, 0, 0, 0);
3796 memorystatus_thread_block(0, memorystatus_thread
);
3801 * when an idle-exitable proc was killed
3803 * when there are no more idle-exitable procs found
3804 * when the attempt to kill an idle-exitable proc failed
3806 boolean_t
memorystatus_idle_exit_from_VM(void) {
3809 * This routine should no longer be needed since we are
3810 * now using jetsam bands on all platforms and so will deal
3811 * with IDLE processes within the memorystatus thread itself.
3813 * But we still use it because we observed that macos systems
3814 * started heavy compression/swapping with a bunch of
3815 * idle-exitable processes alive and doing nothing. We decided
3816 * to rather kill those processes than start swapping earlier.
3819 return(kill_idle_exit_proc());
3823 * Callback invoked when allowable physical memory footprint exceeded
3824 * (dirty pages + IOKit mappings)
3826 * This is invoked for both advisory, non-fatal per-task high watermarks,
3827 * as well as the fatal task memory limits.
3830 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3832 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3834 proc_t p
= current_proc();
3836 #if VM_PRESSURE_EVENTS
3837 if (warning
== TRUE
) {
3839 * This is a warning path which implies that the current process is close, but has
3840 * not yet exceeded its per-process memory limit.
3842 if (memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, FALSE
/* not exceeded */) != TRUE
) {
3843 /* Print warning, since it's possible that task has not registered for pressure notifications */
3844 os_log(OS_LOG_DEFAULT
, "memorystatus_on_ledger_footprint_exceeded: failed to warn the current task (%d exiting, or no handler registered?).\n", p
->p_pid
);
3848 #endif /* VM_PRESSURE_EVENTS */
3850 if (memlimit_is_fatal
) {
3852 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
3853 * has violated either the system-wide per-task memory limit OR its own task limit.
3855 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_PERPROCESSLIMIT
);
3856 if (jetsam_reason
== NULL
) {
3857 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
3858 } else if (corpse_for_fatal_memkill
!= 0) {
3859 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
3860 jetsam_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
3863 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
, jetsam_reason
) != TRUE
) {
3864 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
3868 * HWM offender exists. Done without locks or synchronization.
3869 * See comment near its declaration for more details.
3871 memorystatus_hwm_candidates
= TRUE
;
3873 #if VM_PRESSURE_EVENTS
3875 * The current process is not in the warning path.
3876 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
3877 * Failure to send note is ignored here.
3879 (void)memorystatus_warn_process(p
->p_pid
, memlimit_is_active
, memlimit_is_fatal
, TRUE
/* exceeded */);
3881 #endif /* VM_PRESSURE_EVENTS */
3886 memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
)
3888 proc_t p
= current_proc();
3891 * The limit violation is logged here, but only once per process per limit.
3892 * Soft memory limit is a non-fatal high-water-mark
3893 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
3896 os_log_with_startup_serial(OS_LOG_DEFAULT
, "EXC_RESOURCE -> %s[%d] exceeded mem limit: %s%s %d MB (%s)\n",
3897 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, (memlimit_is_active
? "Active" : "Inactive"),
3898 (memlimit_is_fatal
? "Hard" : "Soft"), max_footprint_mb
,
3899 (memlimit_is_fatal
? "fatal" : "non-fatal"));
3907 * Evaluates process state to determine which limit
3908 * should be applied (active vs. inactive limit).
3910 * Processes that have the 'elevated inactive jetsam band' attribute
3911 * are first evaluated based on their current priority band.
3912 * presently elevated ==> active
3914 * Processes that opt into dirty tracking are evaluated
3915 * based on clean vs dirty state.
3917 * clean ==> inactive
3919 * Process that do not opt into dirty tracking are
3920 * evalulated based on priority level.
3921 * Foreground or above ==> active
3922 * Below Foreground ==> inactive
3924 * Return: TRUE if active
3929 proc_jetsam_state_is_active_locked(proc_t p
) {
3931 if ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) &&
3932 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
)) {
3934 * process has the 'elevated inactive jetsam band' attribute
3935 * and process is present in the elevated band
3936 * implies active state
3939 } else if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3941 * process has opted into dirty tracking
3942 * active state is based on dirty vs. clean
3944 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3947 * implies active state
3953 * implies inactive state
3957 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
3959 * process is Foreground or higher
3960 * implies active state
3965 * process found below Foreground
3966 * implies inactive state
3973 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3976 uint32_t errors
= 0;
3978 if (victim_pid
== -1) {
3979 /* No pid, so kill first process */
3980 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, jetsam_reason
, NULL
, &errors
);
3982 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3986 memorystatus_clear_errors();
3990 /* Fire off snapshot notification */
3992 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3993 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
3994 uint64_t timestamp_now
= mach_absolute_time();
3995 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3996 if (memorystatus_jetsam_snapshot_count
> 0 && (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3997 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
)) {
3999 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
4002 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
4014 * Jetsam a specific process.
4017 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
4020 uint64_t killtime
= 0;
4022 clock_usec_t tv_usec
;
4025 /* TODO - add a victim queue and push this into the main jetsam thread */
4027 p
= proc_find(victim_pid
);
4029 os_reason_free(jetsam_reason
);
4035 if (memorystatus_jetsam_snapshot_count
== 0) {
4036 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4039 killtime
= mach_absolute_time();
4040 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4041 tv_msec
= tv_usec
/ 1000;
4043 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4047 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: killing_specific_process pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
4048 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "unknown"),
4049 memorystatus_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, (uint64_t)memorystatus_available_pages
);
4051 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4059 * Toggle the P_MEMSTAT_TERMINATED state.
4060 * Takes the proc_list_lock.
4063 proc_memstat_terminated(proc_t p
, boolean_t set
)
4065 #if DEVELOPMENT || DEBUG
4069 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4071 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4076 #pragma unused(p, set)
4080 #endif /* DEVELOPMENT || DEBUG */
4087 * This is invoked when cpulimits have been exceeded while in fatal mode.
4088 * The jetsam_flags do not apply as those are for memory related kills.
4089 * We call this routine so that the offending process is killed with
4090 * a non-zero exit status.
4093 jetsam_on_ledger_cpulimit_exceeded(void)
4096 int jetsam_flags
= 0; /* make it obvious */
4097 proc_t p
= current_proc();
4098 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4100 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
4101 p
->p_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"));
4103 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_CPULIMIT
);
4104 if (jetsam_reason
== OS_REASON_NULL
) {
4105 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
4108 retval
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
4111 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
4115 #endif /* CONFIG_JETSAM */
4118 memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
)
4123 *count
= get_task_memory_region_count(task
);
4127 * Called during EXC_RESOURCE handling when a process exceeds a soft
4128 * memory limit. This is the corpse fork path and here we decide if
4129 * vm_map_fork will be allowed when creating the corpse.
4130 * The current task is suspended.
4132 * By default, a vm_map_fork is allowed to proceed.
4134 * A few simple policy assumptions:
4135 * Desktop platform is not considered in this path.
4136 * The vm_map_fork is always allowed.
4138 * If the device has a zero system-wide task limit,
4139 * then the vm_map_fork is allowed.
4141 * And if a process's memory footprint calculates less
4142 * than or equal to half of the system-wide task limit,
4143 * then the vm_map_fork is allowed. This calculation
4144 * is based on the assumption that a process can
4145 * munch memory up to the system-wide task limit.
4148 memorystatus_allowed_vm_map_fork(__unused task_t task
)
4150 boolean_t is_allowed
= TRUE
; /* default */
4154 uint64_t footprint_in_bytes
= 0;
4155 uint64_t purgeable_in_bytes
= 0;
4156 uint64_t max_allowed_bytes
= 0;
4158 if (max_task_footprint_mb
== 0) {
4159 return (is_allowed
);
4162 purgeable_in_bytes
= get_task_purgeable_size(task
);
4163 footprint_in_bytes
= get_task_phys_footprint(task
);
4166 * Maximum is half the system-wide task limit.
4168 max_allowed_bytes
= ((((uint64_t)max_task_footprint_mb
) * 1024ULL * 1024ULL) >> 1);
4170 if (footprint_in_bytes
> purgeable_in_bytes
) {
4171 footprint_in_bytes
-= purgeable_in_bytes
;
4174 if (footprint_in_bytes
<= max_allowed_bytes
) {
4175 return (is_allowed
);
4177 printf("memorystatus disallowed vm_map_fork %lld %lld\n", footprint_in_bytes
, max_allowed_bytes
);
4178 return (!is_allowed
);
4181 #else /* CONFIG_EMBEDDED */
4183 return (is_allowed
);
4185 #endif /* CONFIG_EMBEDDED */
4190 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
4197 pages
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
4198 assert(((uint32_t)pages
) == pages
);
4199 *footprint
= (uint32_t)pages
;
4201 if (max_footprint
) {
4202 pages
= (get_task_phys_footprint_recent_max(task
) / PAGE_SIZE_64
);
4203 assert(((uint32_t)pages
) == pages
);
4204 *max_footprint
= (uint32_t)pages
;
4206 if (max_footprint_lifetime
) {
4207 pages
= (get_task_resident_max(task
) / PAGE_SIZE_64
);
4208 assert(((uint32_t)pages
) == pages
);
4209 *max_footprint_lifetime
= (uint32_t)pages
;
4211 if (purgeable_pages
) {
4212 pages
= (get_task_purgeable_size(task
) / PAGE_SIZE_64
);
4213 assert(((uint32_t)pages
) == pages
);
4214 *purgeable_pages
= (uint32_t)pages
;
4219 memorystatus_get_task_phys_footprint_page_counts(task_t task
,
4220 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
4221 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
4222 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
4223 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
)
4227 if (internal_pages
) {
4228 *internal_pages
= (get_task_internal(task
) / PAGE_SIZE_64
);
4231 if (internal_compressed_pages
) {
4232 *internal_compressed_pages
= (get_task_internal_compressed(task
) / PAGE_SIZE_64
);
4235 if (purgeable_nonvolatile_pages
) {
4236 *purgeable_nonvolatile_pages
= (get_task_purgeable_nonvolatile(task
) / PAGE_SIZE_64
);
4239 if (purgeable_nonvolatile_compressed_pages
) {
4240 *purgeable_nonvolatile_compressed_pages
= (get_task_purgeable_nonvolatile_compressed(task
) / PAGE_SIZE_64
);
4243 if (alternate_accounting_pages
) {
4244 *alternate_accounting_pages
= (get_task_alternate_accounting(task
) / PAGE_SIZE_64
);
4247 if (alternate_accounting_compressed_pages
) {
4248 *alternate_accounting_compressed_pages
= (get_task_alternate_accounting_compressed(task
) / PAGE_SIZE_64
);
4251 if (iokit_mapped_pages
) {
4252 *iokit_mapped_pages
= (get_task_iokit_mapped(task
) / PAGE_SIZE_64
);
4255 if (page_table_pages
) {
4256 *page_table_pages
= (get_task_page_table(task
) / PAGE_SIZE_64
);
4261 * This routine only acts on the global jetsam event snapshot.
4262 * Updating the process's entry can race when the memorystatus_thread
4263 * has chosen to kill a process that is racing to exit on another core.
4266 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
)
4268 memorystatus_jetsam_snapshot_entry_t
*entry
= NULL
;
4269 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4270 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4274 if (memorystatus_jetsam_snapshot_count
== 0) {
4276 * No active snapshot.
4283 * Sanity check as this routine should only be called
4284 * from a jetsam kill path.
4286 assert(kill_cause
!= 0 && killtime
!= 0);
4288 snapshot
= memorystatus_jetsam_snapshot
;
4289 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4291 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
4292 if (snapshot_list
[i
].pid
== p
->p_pid
) {
4294 entry
= &snapshot_list
[i
];
4296 if (entry
->killed
|| entry
->jse_killtime
) {
4298 * We apparently raced on the exit path
4299 * for this process, as it's snapshot entry
4300 * has already recorded a kill.
4302 assert(entry
->killed
&& entry
->jse_killtime
);
4307 * Update the entry we just found in the snapshot.
4310 entry
->killed
= kill_cause
;
4311 entry
->jse_killtime
= killtime
;
4312 entry
->jse_gencount
= snapshot
->js_gencount
;
4313 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
;
4316 * If a process has moved between bands since snapshot was
4317 * initialized, then likely these fields changed too.
4319 if (entry
->priority
!= p
->p_memstat_effectivepriority
) {
4321 strlcpy(entry
->name
, p
->p_name
, sizeof(entry
->name
));
4322 entry
->priority
= p
->p_memstat_effectivepriority
;
4323 entry
->state
= memorystatus_build_state(p
);
4324 entry
->user_data
= p
->p_memstat_userdata
;
4325 entry
->fds
= p
->p_fd
->fd_nfiles
;
4329 * Always update the page counts on a kill.
4333 uint32_t max_pages
= 0;
4334 uint32_t max_pages_lifetime
= 0;
4335 uint32_t purgeable_pages
= 0;
4337 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4338 entry
->pages
= (uint64_t)pages
;
4339 entry
->max_pages
= (uint64_t)max_pages
;
4340 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4341 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4343 uint64_t internal_pages
= 0;
4344 uint64_t internal_compressed_pages
= 0;
4345 uint64_t purgeable_nonvolatile_pages
= 0;
4346 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4347 uint64_t alternate_accounting_pages
= 0;
4348 uint64_t alternate_accounting_compressed_pages
= 0;
4349 uint64_t iokit_mapped_pages
= 0;
4350 uint64_t page_table_pages
= 0;
4352 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4353 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4354 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4355 &iokit_mapped_pages
, &page_table_pages
);
4357 entry
->jse_internal_pages
= internal_pages
;
4358 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4359 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4360 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4361 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4362 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4363 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4364 entry
->jse_page_table_pages
= page_table_pages
;
4366 uint64_t region_count
= 0;
4367 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4368 entry
->jse_memory_region_count
= region_count
;
4374 if (entry
== NULL
) {
4376 * The entry was not found in the snapshot, so the process must have
4377 * launched after the snapshot was initialized.
4378 * Let's try to append the new entry.
4380 if (memorystatus_jetsam_snapshot_count
< memorystatus_jetsam_snapshot_max
) {
4382 * A populated snapshot buffer exists
4383 * and there is room to init a new entry.
4385 assert(memorystatus_jetsam_snapshot_count
== snapshot
->entry_count
);
4387 unsigned int next
= memorystatus_jetsam_snapshot_count
;
4389 if(memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[next
], (snapshot
->js_gencount
)) == TRUE
) {
4391 entry
= &snapshot_list
[next
];
4392 entry
->killed
= kill_cause
;
4393 entry
->jse_killtime
= killtime
;
4395 snapshot
->entry_count
= ++next
;
4396 memorystatus_jetsam_snapshot_count
= next
;
4398 if (memorystatus_jetsam_snapshot_count
>= memorystatus_jetsam_snapshot_max
) {
4400 * We just used the last slot in the snapshot buffer.
4401 * We only want to log it once... so we do it here
4402 * when we notice we've hit the max.
4404 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
4405 memorystatus_jetsam_snapshot_count
);
4412 if (entry
== NULL
) {
4414 * If we reach here, the snapshot buffer could not be updated.
4415 * Most likely, the buffer is full, in which case we would have
4416 * logged a warning in the previous call.
4418 * For now, we will stop appending snapshot entries.
4419 * When the buffer is consumed, the snapshot state will reset.
4422 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
4423 p
->p_pid
, p
->p_memstat_effectivepriority
, memorystatus_jetsam_snapshot_count
);
4430 void memorystatus_pages_update(unsigned int pages_avail
)
4432 memorystatus_available_pages
= pages_avail
;
4434 #if VM_PRESSURE_EVENTS
4436 * Since memorystatus_available_pages changes, we should
4437 * re-evaluate the pressure levels on the system and
4438 * check if we need to wake the pressure thread.
4439 * We also update memorystatus_level in that routine.
4441 vm_pressure_response();
4443 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
4445 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
4446 memorystatus_thread_wake();
4449 #else /* VM_PRESSURE_EVENTS */
4451 boolean_t critical
, delta
;
4453 if (!memorystatus_delta
) {
4457 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
4458 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
4459 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
4461 if (critical
|| delta
) {
4462 unsigned int total_pages
;
4464 total_pages
= (unsigned int) atop_64(max_mem
);
4465 #if CONFIG_SECLUDED_MEMORY
4466 total_pages
-= vm_page_secluded_count
;
4467 #endif /* CONFIG_SECLUDED_MEMORY */
4468 memorystatus_level
= memorystatus_available_pages
* 100 / total_pages
;
4469 memorystatus_thread_wake();
4471 #endif /* VM_PRESSURE_EVENTS */
4473 #endif /* CONFIG_JETSAM */
4476 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
)
4479 clock_usec_t tv_usec
;
4481 uint32_t max_pages
= 0;
4482 uint32_t max_pages_lifetime
= 0;
4483 uint32_t purgeable_pages
= 0;
4484 uint64_t internal_pages
= 0;
4485 uint64_t internal_compressed_pages
= 0;
4486 uint64_t purgeable_nonvolatile_pages
= 0;
4487 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4488 uint64_t alternate_accounting_pages
= 0;
4489 uint64_t alternate_accounting_compressed_pages
= 0;
4490 uint64_t iokit_mapped_pages
= 0;
4491 uint64_t page_table_pages
=0;
4492 uint64_t region_count
= 0;
4493 uint64_t cids
[COALITION_NUM_TYPES
];
4495 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
4497 entry
->pid
= p
->p_pid
;
4498 strlcpy(&entry
->name
[0], p
->p_name
, sizeof(entry
->name
));
4499 entry
->priority
= p
->p_memstat_effectivepriority
;
4501 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4502 entry
->pages
= (uint64_t)pages
;
4503 entry
->max_pages
= (uint64_t)max_pages
;
4504 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4505 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4507 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4508 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4509 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4510 &iokit_mapped_pages
, &page_table_pages
);
4512 entry
->jse_internal_pages
= internal_pages
;
4513 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4514 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4515 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4516 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4517 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4518 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4519 entry
->jse_page_table_pages
= page_table_pages
;
4521 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4522 entry
->jse_memory_region_count
= region_count
;
4524 entry
->state
= memorystatus_build_state(p
);
4525 entry
->user_data
= p
->p_memstat_userdata
;
4526 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
4527 entry
->fds
= p
->p_fd
->fd_nfiles
;
4529 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
4530 entry
->cpu_time
.tv_sec
= tv_sec
;
4531 entry
->cpu_time
.tv_usec
= tv_usec
;
4533 assert(p
->p_stats
!= NULL
);
4534 entry
->jse_starttime
= p
->p_stats
->ps_start
; /* abstime process started */
4535 entry
->jse_killtime
= 0; /* abstime jetsam chose to kill process */
4536 entry
->killed
= 0; /* the jetsam kill cause */
4537 entry
->jse_gencount
= gencount
; /* indicates a pass through jetsam thread, when process was targeted to be killed */
4539 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
; /* Most recent timespan spent in idle-band */
4541 proc_coalitionids(p
, cids
);
4542 entry
->jse_coalition_jetsam_id
= cids
[COALITION_TYPE_JETSAM
];
4548 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
4550 kern_return_t kr
= KERN_SUCCESS
;
4551 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
4552 vm_statistics64_data_t vm_stat
;
4554 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
) != KERN_SUCCESS
)) {
4555 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
4556 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
4558 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
4559 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
4560 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
4561 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
4562 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
4563 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
4565 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
4566 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
4567 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
4568 snapshot
->stats
.compressions
= vm_stat
.compressions
;
4569 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
4570 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
4571 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
4574 get_zone_map_size(&snapshot
->stats
.zone_map_size
, &snapshot
->stats
.zone_map_capacity
);
4575 get_largest_zone_info(snapshot
->stats
.largest_zone_name
, sizeof(snapshot
->stats
.largest_zone_name
),
4576 &snapshot
->stats
.largest_zone_size
);
4580 * Collect vm statistics at boot.
4581 * Called only once (see kern_exec.c)
4582 * Data can be consumed at any time.
4585 memorystatus_init_at_boot_snapshot() {
4586 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
4587 memorystatus_at_boot_snapshot
.entry_count
= 0;
4588 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
4589 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
4593 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
4596 unsigned int b
= 0, i
= 0;
4598 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4599 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4600 unsigned int snapshot_max
= 0;
4604 * This is an on_demand snapshot
4606 snapshot
= od_snapshot
;
4607 snapshot_list
= od_snapshot
->entries
;
4608 snapshot_max
= ods_list_count
;
4611 * This is a jetsam event snapshot
4613 snapshot
= memorystatus_jetsam_snapshot
;
4614 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4615 snapshot_max
= memorystatus_jetsam_snapshot_max
;
4619 * Init the snapshot header information
4621 memorystatus_init_snapshot_vmstats(snapshot
);
4622 snapshot
->snapshot_time
= mach_absolute_time();
4623 snapshot
->notification_time
= 0;
4624 snapshot
->js_gencount
= 0;
4626 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
4629 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
4631 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
], snapshot
->js_gencount
)) {
4635 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",
4637 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],
4638 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]);
4640 if (++i
== snapshot_max
) {
4645 snapshot
->entry_count
= i
;
4648 /* update the system buffer count */
4649 memorystatus_jetsam_snapshot_count
= i
;
4653 #if DEVELOPMENT || DEBUG
4657 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
) {
4659 memorystatus_jetsam_panic_options_t debug
;
4661 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
4665 ret
= copyin(buffer
, &debug
, buffer_size
);
4670 /* Panic bits match kMemorystatusKilled* enum */
4671 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
4673 /* Copyout new value */
4674 debug
.data
= memorystatus_jetsam_panic_debug
;
4675 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
4679 #endif /* CONFIG_JETSAM */
4682 * Triggers a sort_order on a specified jetsam priority band.
4683 * This is for testing only, used to force a path through the sort
4687 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
) {
4691 unsigned int bucket_index
= 0;
4693 if (priority
== -1) {
4694 /* Use as shorthand for default priority */
4695 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
4697 bucket_index
= (unsigned int)priority
;
4700 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
4705 #endif /* DEVELOPMENT || DEBUG */
4708 * Jetsam the first process in the queue.
4711 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
,
4712 int32_t *priority
, uint32_t *errors
)
4715 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4716 boolean_t new_snapshot
= FALSE
, force_new_snapshot
= FALSE
, killed
= FALSE
;
4720 uint64_t killtime
= 0;
4722 clock_usec_t tv_usec
;
4724 int32_t local_max_kill_prio
= JETSAM_PRIORITY_IDLE
;
4726 #ifndef CONFIG_FREEZE
4730 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4731 memorystatus_available_pages
, 0, 0, 0, 0);
4735 if (sort_flag
== TRUE
) {
4736 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4739 local_max_kill_prio
= max_kill_priority
;
4741 force_new_snapshot
= FALSE
;
4743 #else /* CONFIG_JETSAM */
4745 if (sort_flag
== TRUE
) {
4746 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_IDLE
, JETSAM_SORT_DEFAULT
);
4750 * On macos, we currently only have 2 reasons to be here:
4752 * kMemorystatusKilledZoneMapExhaustion
4754 * kMemorystatusKilledVMThrashing
4756 * If we are here because of kMemorystatusKilledZoneMapExhaustion, we will consider
4757 * any and all processes as eligible kill candidates since we need to avoid a panic.
4759 * Since this function can be called async. it is harder to toggle the max_kill_priority
4760 * value before and after a call. And so we use this local variable to set the upper band
4761 * on the eligible kill bands.
4763 if (cause
== kMemorystatusKilledZoneMapExhaustion
) {
4764 local_max_kill_prio
= JETSAM_PRIORITY_MAX
;
4766 local_max_kill_prio
= max_kill_priority
;
4770 * And, because we are here under extreme circumstances, we force a snapshot even for
4773 force_new_snapshot
= TRUE
;
4775 #endif /* CONFIG_JETSAM */
4779 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4780 while (next_p
&& (next_p
->p_memstat_effectivepriority
<= local_max_kill_prio
)) {
4781 #if DEVELOPMENT || DEBUG
4783 int procSuspendedForDiagnosis
;
4784 #endif /* DEVELOPMENT || DEBUG */
4787 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4789 #if DEVELOPMENT || DEBUG
4790 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4791 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4792 #endif /* DEVELOPMENT || DEBUG */
4795 aPid_ep
= p
->p_memstat_effectivepriority
;
4797 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4798 continue; /* with lock held */
4801 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
4802 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4803 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4806 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
4808 if (cause
== kMemorystatusKilledVnodes
)
4811 * If the system runs out of vnodes, we systematically jetsam
4812 * processes in hopes of stumbling onto a vnode gain that helps
4813 * the system recover. The process that happens to trigger
4814 * this path has no known relationship to the vnode shortage.
4815 * Deadlock avoidance: attempt to safeguard the caller.
4818 if (p
== current_proc()) {
4819 /* do not jetsam the current process */
4826 boolean_t reclaim_proc
= !(p
->p_memstat_state
& (P_MEMSTAT_LOCKED
| P_MEMSTAT_NORECLAIM
));
4827 if (any
|| reclaim_proc
) {
4839 * Capture a snapshot if none exists and:
4840 * - we are forcing a new snapshot creation, either because:
4841 * - on a particular platform we need these snapshots every time, OR
4842 * - a boot-arg/embedded device tree property has been set.
4843 * - priority was not requested (this is something other than an ambient kill)
4844 * - the priority was requested *and* the targeted process is not at idle priority
4846 if ((memorystatus_jetsam_snapshot_count
== 0) &&
4847 (force_new_snapshot
|| memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (aPid_ep
!= JETSAM_PRIORITY_IDLE
))))) {
4848 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4849 new_snapshot
= TRUE
;
4853 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4854 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4855 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4856 * acquisition of the proc lock.
4858 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4860 killtime
= mach_absolute_time();
4861 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4862 tv_msec
= tv_usec
/ 1000;
4864 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
4865 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && activeProcess
) {
4866 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
4867 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_level
);
4868 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
4869 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
4870 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
4871 jetsam_diagnostic_suspended_one_active_proc
= 1;
4872 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
4875 p
= proc_ref_locked(p
);
4878 task_suspend(p
->task
);
4880 *priority
= aPid_ep
;
4888 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
4890 /* Shift queue, update stats */
4891 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4893 if (proc_ref_locked(p
) == p
) {
4895 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: %s pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
4896 (unsigned long)tv_sec
, tv_msec
,
4897 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "killing_idle_process" : "killing_top_process"),
4898 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
4899 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
4902 * memorystatus_do_kill() drops a reference, so take another one so we can
4903 * continue to use this exit reason even after memorystatus_do_kill()
4906 os_reason_ref(jetsam_reason
);
4908 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4913 *priority
= aPid_ep
;
4921 * Failure - first unwind the state,
4922 * then fall through to restart the search.
4925 proc_rele_locked(p
);
4926 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4927 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4932 * Failure - restart the search.
4934 * We might have raced with "p" exiting on another core, resulting in no
4935 * ref on "p". Or, we may have failed to kill "p".
4937 * Either way, we fall thru to here, leaving the proc in the
4938 * P_MEMSTAT_TERMINATED state.
4940 * And, we hold the the proc_list_lock at this point.
4944 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4952 os_reason_free(jetsam_reason
);
4954 /* Clear snapshot if freshly captured and no target was found */
4955 if (new_snapshot
&& !killed
) {
4957 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4961 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4962 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4968 * Jetsam aggressively
4971 memorystatus_kill_top_process_aggressive(uint32_t cause
, int aggr_count
,
4972 int32_t priority_max
, uint32_t *errors
)
4975 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4976 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4979 int32_t aPid_ep
= 0;
4980 unsigned int memorystatus_level_snapshot
= 0;
4981 uint64_t killtime
= 0;
4983 clock_usec_t tv_usec
;
4985 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4987 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4988 memorystatus_available_pages
, priority_max
, 0, 0, 0);
4990 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4992 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, cause
);
4993 if (jetsam_reason
== OS_REASON_NULL
) {
4994 printf("memorystatus_kill_top_process_aggressive: failed to allocate exit reason\n");
4999 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5001 #if DEVELOPMENT || DEBUG
5003 int procSuspendedForDiagnosis
;
5004 #endif /* DEVELOPMENT || DEBUG */
5006 if (((next_p
->p_listflag
& P_LIST_EXITED
) != 0) ||
5007 ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
)) {
5010 * We have raced with next_p running on another core.
5011 * It may be exiting or it may have moved to a different
5012 * jetsam priority band. This means we have lost our
5013 * place in line while traversing the jetsam list. We
5014 * attempt to recover by rewinding to the beginning of the band
5015 * we were already traversing. By doing this, we do not guarantee
5016 * that no process escapes this aggressive march, but we can make
5017 * skipping an entire range of processes less likely. (PR-21069019)
5020 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding band %d, %s(%d) moved or exiting.\n",
5021 aggr_count
, i
, (*next_p
->p_name
? next_p
->p_name
: "unknown"), next_p
->p_pid
);
5023 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5028 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5030 if (p
->p_memstat_effectivepriority
> priority_max
) {
5032 * Bail out of this killing spree if we have
5033 * reached beyond the priority_max jetsam band.
5034 * That is, we kill up to and through the
5035 * priority_max jetsam band.
5041 #if DEVELOPMENT || DEBUG
5042 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
5043 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
5044 #endif /* DEVELOPMENT || DEBUG */
5047 aPid_ep
= p
->p_memstat_effectivepriority
;
5049 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5053 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5054 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
5055 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
5058 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5061 * Capture a snapshot if none exists.
5063 if (memorystatus_jetsam_snapshot_count
== 0) {
5064 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5065 new_snapshot
= TRUE
;
5069 * Mark as terminated so that if exit1() indicates success, but the process (for example)
5070 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
5071 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
5072 * acquisition of the proc lock.
5074 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5076 killtime
= mach_absolute_time();
5077 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5078 tv_msec
= tv_usec
/ 1000;
5080 /* Shift queue, update stats */
5081 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5084 * In order to kill the target process, we will drop the proc_list_lock.
5085 * To guaranteee that p and next_p don't disappear out from under the lock,
5086 * we must take a ref on both.
5087 * If we cannot get a reference, then it's likely we've raced with
5088 * that process exiting on another core.
5090 if (proc_ref_locked(p
) == p
) {
5092 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
5096 * We must have raced with next_p exiting on another core.
5097 * Recover by getting the next eligible process in the band.
5100 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
5101 aggr_count
, next_p
->p_pid
, (*next_p
->p_name
? next_p
->p_name
: "(unknown)"));
5104 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
5109 printf("%lu.%03d memorystatus: %s%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
5110 (unsigned long)tv_sec
, tv_msec
,
5111 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "killing_idle_process_aggressive" : "killing_top_process_aggressive"),
5112 aggr_count
, aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5113 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
5115 memorystatus_level_snapshot
= memorystatus_level
;
5118 * memorystatus_do_kill() drops a reference, so take another one so we can
5119 * continue to use this exit reason even after memorystatus_do_kill()
5122 os_reason_ref(jetsam_reason
);
5123 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5133 * Continue the killing spree.
5137 proc_rele_locked(next_p
);
5140 if (aPid_ep
== JETSAM_PRIORITY_FOREGROUND
&& memorystatus_aggressive_jetsam_lenient
== TRUE
) {
5141 if (memorystatus_level
> memorystatus_level_snapshot
&& ((memorystatus_level
- memorystatus_level_snapshot
) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD
)) {
5142 #if DEVELOPMENT || DEBUG
5143 printf("Disabling Lenient mode after one-time deployment.\n");
5144 #endif /* DEVELOPMENT || DEBUG */
5145 memorystatus_aggressive_jetsam_lenient
= FALSE
;
5154 * Failure - first unwind the state,
5155 * then fall through to restart the search.
5158 proc_rele_locked(p
);
5160 proc_rele_locked(next_p
);
5162 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5163 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5169 * Failure - restart the search at the beginning of
5170 * the band we were already traversing.
5172 * We might have raced with "p" exiting on another core, resulting in no
5173 * ref on "p". Or, we may have failed to kill "p".
5175 * Either way, we fall thru to here, leaving the proc in the
5176 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
5178 * And, we hold the the proc_list_lock at this point.
5181 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5187 os_reason_free(jetsam_reason
);
5189 /* Clear snapshot if freshly captured and no target was found */
5190 if (new_snapshot
&& (kill_count
== 0)) {
5191 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5194 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5195 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5197 if (kill_count
> 0) {
5206 memorystatus_kill_hiwat_proc(uint32_t *errors
)
5209 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5210 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5214 uint64_t killtime
= 0;
5216 clock_usec_t tv_usec
;
5218 os_reason_t jetsam_reason
= OS_REASON_NULL
;
5219 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
5220 memorystatus_available_pages
, 0, 0, 0, 0);
5222 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_HIGHWATER
);
5223 if (jetsam_reason
== OS_REASON_NULL
) {
5224 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
5229 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5231 uint64_t footprint_in_bytes
= 0;
5232 uint64_t memlimit_in_bytes
= 0;
5236 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5239 aPid_ep
= p
->p_memstat_effectivepriority
;
5241 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5245 /* skip if no limit set */
5246 if (p
->p_memstat_memlimit
<= 0) {
5250 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
5251 memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
5252 skip
= (footprint_in_bytes
<= memlimit_in_bytes
);
5254 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5255 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
5256 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
5260 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5264 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5275 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5276 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5277 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing",
5278 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5279 (footprint_in_bytes
/ (1024ULL * 1024ULL)), /* converted bytes to MB */
5280 p
->p_memstat_memlimit
);
5281 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5283 if (memorystatus_jetsam_snapshot_count
== 0) {
5284 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5285 new_snapshot
= TRUE
;
5288 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5290 killtime
= mach_absolute_time();
5291 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5292 tv_msec
= tv_usec
/ 1000;
5294 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
5295 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5296 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid
, memorystatus_available_pages
);
5297 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
5298 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
5300 p
= proc_ref_locked(p
);
5303 task_suspend(p
->task
);
5310 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
5312 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledHiwat
, killtime
);
5314 if (proc_ref_locked(p
) == p
) {
5317 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: killing_highwater_process pid %d [%s] (highwater %d) - memorystatus_available_pages: %llu\n",
5318 (unsigned long)tv_sec
, tv_msec
, aPid
, (*p
->p_name
? p
->p_name
: "unknown"), aPid_ep
, (uint64_t)memorystatus_available_pages
);
5321 * memorystatus_do_kill drops a reference, so take another one so we can
5322 * continue to use this exit reason even after memorystatus_do_kill()
5325 os_reason_ref(jetsam_reason
);
5327 killed
= memorystatus_do_kill(p
, kMemorystatusKilledHiwat
, jetsam_reason
);
5337 * Failure - first unwind the state,
5338 * then fall through to restart the search.
5341 proc_rele_locked(p
);
5342 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5343 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5348 * Failure - restart the search.
5350 * We might have raced with "p" exiting on another core, resulting in no
5351 * ref on "p". Or, we may have failed to kill "p".
5353 * Either way, we fall thru to here, leaving the proc in the
5354 * P_MEMSTAT_TERMINATED state.
5356 * And, we hold the the proc_list_lock at this point.
5360 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5368 os_reason_free(jetsam_reason
);
5370 /* Clear snapshot if freshly captured and no target was found */
5371 if (new_snapshot
&& !killed
) {
5373 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5377 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
5378 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5384 * Jetsam a process pinned in the elevated band.
5386 * Return: true -- at least one pinned process was jetsammed
5387 * false -- no pinned process was jetsammed
5390 memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
)
5393 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5394 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5396 unsigned int i
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
5398 uint64_t killtime
= 0;
5400 clock_usec_t tv_usec
;
5404 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5405 memorystatus_available_pages
, 0, 0, 0, 0);
5409 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5413 next_p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
5416 aPid_ep
= p
->p_memstat_effectivepriority
;
5419 * Only pick a process pinned in this elevated band
5421 if (!(p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
5425 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5430 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5435 #if DEVELOPMENT || DEBUG
5436 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
5438 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5439 memorystatus_available_pages
);
5440 #endif /* DEVELOPMENT || DEBUG */
5442 if (memorystatus_jetsam_snapshot_count
== 0) {
5443 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5444 new_snapshot
= TRUE
;
5447 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5449 killtime
= mach_absolute_time();
5450 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5451 tv_msec
= tv_usec
/ 1000;
5453 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5455 if (proc_ref_locked(p
) == p
) {
5459 os_log_with_startup_serial(OS_LOG_DEFAULT
, "%lu.%03d memorystatus: killing_top_process_elevated%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
5460 (unsigned long)tv_sec
, tv_msec
,
5462 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5463 memorystatus_kill_cause_name
[cause
], aPid_ep
, (uint64_t)memorystatus_available_pages
);
5466 * memorystatus_do_kill drops a reference, so take another one so we can
5467 * continue to use this exit reason even after memorystatus_do_kill()
5470 os_reason_ref(jetsam_reason
);
5471 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5481 * Failure - first unwind the state,
5482 * then fall through to restart the search.
5485 proc_rele_locked(p
);
5486 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5487 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5492 * Failure - restart the search.
5494 * We might have raced with "p" exiting on another core, resulting in no
5495 * ref on "p". Or, we may have failed to kill "p".
5497 * Either way, we fall thru to here, leaving the proc in the
5498 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
5500 * And, we hold the the proc_list_lock at this point.
5503 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5509 os_reason_free(jetsam_reason
);
5511 /* Clear snapshot if freshly captured and no target was found */
5512 if (new_snapshot
&& (kill_count
== 0)) {
5514 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5518 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5519 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5525 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
) {
5527 * TODO: allow a general async path
5529 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
5530 * add the appropriate exit reason code mapping.
5532 if ((victim_pid
!= -1) || (cause
!= kMemorystatusKilledVMPageShortage
&& cause
!= kMemorystatusKilledVMThrashing
&&
5533 cause
!= kMemorystatusKilledFCThrashing
&& cause
!= kMemorystatusKilledZoneMapExhaustion
)) {
5537 kill_under_pressure_cause
= cause
;
5538 memorystatus_thread_wake();
5543 memorystatus_kill_on_VM_thrashing(boolean_t async
) {
5545 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing
);
5547 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMTHRASHING
);
5548 if (jetsam_reason
== OS_REASON_NULL
) {
5549 printf("memorystatus_kill_on_VM_thrashing -- sync: failed to allocate jetsam reason\n");
5552 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing
, jetsam_reason
);
5558 memorystatus_kill_on_VM_page_shortage(boolean_t async
) {
5560 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
5562 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMPAGESHORTAGE
);
5563 if (jetsam_reason
== OS_REASON_NULL
) {
5564 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
5567 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
, jetsam_reason
);
5572 memorystatus_kill_on_FC_thrashing(boolean_t async
) {
5576 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
5578 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_FCTHRASHING
);
5579 if (jetsam_reason
== OS_REASON_NULL
) {
5580 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
5583 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
, jetsam_reason
);
5588 memorystatus_kill_on_vnode_limit(void) {
5589 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_VNODE
);
5590 if (jetsam_reason
== OS_REASON_NULL
) {
5591 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
5594 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
, jetsam_reason
);
5597 #endif /* CONFIG_JETSAM */
5600 memorystatus_kill_on_zone_map_exhaustion(pid_t pid
) {
5601 boolean_t res
= FALSE
;
5603 res
= memorystatus_kill_process_async(-1, kMemorystatusKilledZoneMapExhaustion
);
5605 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_ZONE_MAP_EXHAUSTION
);
5606 if (jetsam_reason
== OS_REASON_NULL
) {
5607 printf("memorystatus_kill_on_zone_map_exhaustion: failed to allocate jetsam reason\n");
5610 res
= memorystatus_kill_process_sync(pid
, kMemorystatusKilledZoneMapExhaustion
, jetsam_reason
);
5617 __private_extern__
void
5618 memorystatus_freeze_init(void)
5620 kern_return_t result
;
5623 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
5624 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
5626 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
5628 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
5629 if (result
== KERN_SUCCESS
) {
5630 thread_deallocate(thread
);
5632 panic("Could not create memorystatus_freeze_thread");
5637 * Synchronously freeze the passed proc. Called with a reference to the proc held.
5639 * Returns EINVAL or the value returned by task_freeze().
5642 memorystatus_freeze_process_sync(proc_t p
)
5646 boolean_t memorystatus_freeze_swap_low
= FALSE
;
5648 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5649 memorystatus_available_pages
, 0, 0, 0, 0);
5651 lck_mtx_lock(&freezer_mutex
);
5657 if (memorystatus_freeze_enabled
== FALSE
) {
5661 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5665 if (memorystatus_freeze_update_throttle()) {
5666 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
5667 memorystatus_freeze_throttle_count
++;
5674 uint32_t purgeable
, wired
, clean
, dirty
, state
;
5675 uint32_t max_pages
, pages
, i
;
5679 state
= p
->p_memstat_state
;
5681 /* Ensure the process is eligible for freezing */
5682 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5687 /* Only freeze processes meeting our minimum resident page criteria */
5688 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5689 if (pages
< memorystatus_freeze_pages_min
) {
5694 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5696 unsigned int avail_swap_space
= 0; /* in pages. */
5699 * Freezer backed by the compressor and swap file(s)
5700 * while will hold compressed data.
5702 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5704 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5706 if (max_pages
< memorystatus_freeze_pages_min
) {
5712 * We only have the compressor without any swap.
5714 max_pages
= UINT32_MAX
- 1;
5717 /* Mark as locked temporarily to avoid kill */
5718 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5721 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5723 DTRACE_MEMORYSTATUS6(memorystatus_freeze
, proc_t
, p
, unsigned int, memorystatus_available_pages
, boolean_t
, purgeable
, unsigned int, wired
, uint32_t, clean
, uint32_t, dirty
);
5725 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
5726 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5727 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5728 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5731 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5733 if (ret
== KERN_SUCCESS
) {
5734 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5736 memorystatus_frozen_count
++;
5738 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5740 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5742 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5743 throttle_intervals
[i
].pageouts
+= dirty
;
5747 memorystatus_freeze_pageouts
+= dirty
;
5748 memorystatus_freeze_count
++;
5752 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5759 lck_mtx_unlock(&freezer_mutex
);
5760 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5761 memorystatus_available_pages
, aPid
, 0, 0, 0);
5767 memorystatus_freeze_top_process(boolean_t
*memorystatus_freeze_swap_low
)
5771 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5774 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5775 memorystatus_available_pages
, 0, 0, 0, 0);
5779 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5782 uint32_t purgeable
, wired
, clean
, dirty
;
5785 uint32_t max_pages
= 0;
5789 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5792 state
= p
->p_memstat_state
;
5794 /* Ensure the process is eligible for freezing */
5795 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5796 continue; // with lock held
5799 /* Only freeze processes meeting our minimum resident page criteria */
5800 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5801 if (pages
< memorystatus_freeze_pages_min
) {
5802 continue; // with lock held
5805 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5807 /* Ensure there's enough free space to freeze this process. */
5809 unsigned int avail_swap_space
= 0; /* in pages. */
5812 * Freezer backed by the compressor and swap file(s)
5813 * while will hold compressed data.
5815 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5817 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5819 if (max_pages
< memorystatus_freeze_pages_min
) {
5820 *memorystatus_freeze_swap_low
= TRUE
;
5826 * We only have the compressor pool.
5828 max_pages
= UINT32_MAX
- 1;
5831 /* Mark as locked temporarily to avoid kill */
5832 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5834 p
= proc_ref_locked(p
);
5840 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5842 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
5843 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5844 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5845 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5848 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5851 if (KERN_SUCCESS
== kr
) {
5852 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5854 memorystatus_frozen_count
++;
5856 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5858 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5860 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5861 throttle_intervals
[i
].pageouts
+= dirty
;
5865 memorystatus_freeze_pageouts
+= dirty
;
5866 memorystatus_freeze_count
++;
5870 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5872 /* Return KERN_SUCESS */
5886 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5887 memorystatus_available_pages
, aPid
, 0, 0, 0);
5892 static inline boolean_t
5893 memorystatus_can_freeze_processes(void)
5899 if (memorystatus_suspended_count
) {
5900 uint32_t average_resident_pages
, estimated_processes
;
5902 /* Estimate the number of suspended processes we can fit */
5903 average_resident_pages
= memorystatus_suspended_footprint_total
/ memorystatus_suspended_count
;
5904 estimated_processes
= memorystatus_suspended_count
+
5905 ((memorystatus_available_pages
- memorystatus_available_pages_critical
) / average_resident_pages
);
5907 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
5908 if (estimated_processes
<= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
) {
5909 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_LOW
;
5911 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
5914 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
5915 memorystatus_suspended_count
, average_resident_pages
, estimated_processes
);
5917 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
5932 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
5934 boolean_t can_freeze
= TRUE
;
5936 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
5937 after boot, and is generally is a no-op once we've reached steady state. */
5938 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
5942 /* Check minimum suspended process threshold. */
5943 if (!memorystatus_can_freeze_processes()) {
5946 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT
);
5948 if ( !VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5950 * In-core compressor used for freezing WITHOUT on-disk swap support.
5952 if (vm_compressor_low_on_space()) {
5953 if (*memorystatus_freeze_swap_low
) {
5954 *memorystatus_freeze_swap_low
= TRUE
;
5960 if (*memorystatus_freeze_swap_low
) {
5961 *memorystatus_freeze_swap_low
= FALSE
;
5968 * Freezing WITH on-disk swap support.
5970 * In-core compressor fronts the swap.
5972 if (vm_swap_low_on_space()) {
5973 if (*memorystatus_freeze_swap_low
) {
5974 *memorystatus_freeze_swap_low
= TRUE
;
5986 memorystatus_freeze_update_throttle_interval(mach_timespec_t
*ts
, struct throttle_interval_t
*interval
)
5988 unsigned int freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
5989 if (CMP_MACH_TIMESPEC(ts
, &interval
->ts
) >= 0) {
5990 if (!interval
->max_pageouts
) {
5991 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / (24 * 60)));
5993 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval
->mins
);
5995 interval
->ts
.tv_sec
= interval
->mins
* 60;
5996 interval
->ts
.tv_nsec
= 0;
5997 ADD_MACH_TIMESPEC(&interval
->ts
, ts
);
5998 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
5999 if (interval
->pageouts
> interval
->max_pageouts
) {
6000 interval
->pageouts
-= interval
->max_pageouts
;
6002 interval
->pageouts
= 0;
6004 interval
->throttle
= FALSE
;
6005 } else if (!interval
->throttle
&& interval
->pageouts
>= interval
->max_pageouts
) {
6006 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval
->mins
);
6007 interval
->throttle
= TRUE
;
6010 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
6011 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
6012 interval
->throttle
? "on" : "off");
6016 memorystatus_freeze_update_throttle(void)
6022 boolean_t throttled
= FALSE
;
6024 #if DEVELOPMENT || DEBUG
6025 if (!memorystatus_freeze_throttle_enabled
)
6029 clock_get_system_nanotime(&sec
, &nsec
);
6033 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
6035 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
6036 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
6037 * order to allow for bursts of activity.
6039 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
6040 memorystatus_freeze_update_throttle_interval(&ts
, &throttle_intervals
[i
]);
6041 if (throttle_intervals
[i
].throttle
== TRUE
)
6049 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
6051 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
6053 lck_mtx_lock(&freezer_mutex
);
6054 if (memorystatus_freeze_enabled
) {
6055 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
6056 /* Only freeze if we've not exceeded our pageout budgets.*/
6057 if (!memorystatus_freeze_update_throttle()) {
6058 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low
);
6060 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
6061 memorystatus_freeze_throttle_count
++; /* Throttled, update stats */
6065 lck_mtx_unlock(&freezer_mutex
);
6067 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
6068 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
6072 sysctl_memorystatus_do_fastwake_warmup_all SYSCTL_HANDLER_ARGS
6074 #pragma unused(oidp, req, arg1, arg2)
6076 /* Need to be root or have entitlement */
6077 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
6081 if (memorystatus_freeze_enabled
== FALSE
) {
6085 do_fastwake_warmup_all();
6090 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_do_fastwake_warmup_all
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6091 0, 0, &sysctl_memorystatus_do_fastwake_warmup_all
, "I", "");
6093 #endif /* CONFIG_FREEZE */
6095 #if VM_PRESSURE_EVENTS
6097 #if CONFIG_MEMORYSTATUS
6100 memorystatus_send_note(int event_code
, void *data
, size_t data_length
) {
6102 struct kev_msg ev_msg
;
6104 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
6105 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
6106 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
6108 ev_msg
.event_code
= event_code
;
6110 ev_msg
.dv
[0].data_length
= data_length
;
6111 ev_msg
.dv
[0].data_ptr
= data
;
6112 ev_msg
.dv
[1].data_length
= 0;
6114 ret
= kev_post_msg(&ev_msg
);
6116 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
6123 memorystatus_warn_process(pid_t pid
, __unused boolean_t is_active
, __unused boolean_t is_fatal
, boolean_t limit_exceeded
) {
6125 boolean_t ret
= FALSE
;
6126 boolean_t found_knote
= FALSE
;
6127 struct knote
*kn
= NULL
;
6128 int send_knote_count
= 0;
6131 * See comment in sysctl_memorystatus_vm_pressure_send.
6134 memorystatus_klist_lock();
6136 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6137 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
6138 pid_t knote_pid
= knote_proc
->p_pid
;
6140 if (knote_pid
== pid
) {
6142 * By setting the "fflags" here, we are forcing
6143 * a process to deal with the case where it's
6144 * bumping up into its memory limits. If we don't
6145 * do this here, we will end up depending on the
6146 * system pressure snapshot evaluation in
6147 * filt_memorystatus().
6151 if (!limit_exceeded
) {
6153 * Intentionally set either the unambiguous limit warning,
6154 * the system-wide critical or the system-wide warning
6158 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
6159 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
6162 } else if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
6163 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
6166 } else if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
6167 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
6173 * Send this notification when a process has exceeded a soft limit.
6175 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
6176 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
6181 #else /* CONFIG_EMBEDDED */
6182 if (!limit_exceeded
) {
6185 * Processes on desktop are not expecting to handle a system-wide
6186 * critical or system-wide warning notification from this path.
6187 * Intentionally set only the unambiguous limit warning here.
6189 * If the limit is soft, however, limit this to one notification per
6190 * active/inactive limit (per each registered listener).
6193 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
6197 * Restrict proc_limit_warn notifications when
6198 * non-fatal (soft) limit is at play.
6201 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
6203 * Mark this knote for delivery.
6205 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
6207 * And suppress it from future notifications.
6209 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
6213 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
6215 * Mark this knote for delivery.
6217 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
6219 * And suppress it from future notifications.
6221 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
6227 * No restriction on proc_limit_warn notifications when
6228 * fatal (hard) limit is at play.
6230 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
6236 * Send this notification when a process has exceeded a soft limit,
6239 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
6243 * Restrict critical notifications for soft limits.
6247 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
6249 * Suppress future proc_limit_critical notifications
6250 * for the active soft limit.
6252 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
6253 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
6258 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
6260 * Suppress future proc_limit_critical_notifications
6261 * for the inactive soft limit.
6263 kn
->kn_sfflags
&= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
6264 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
6270 * We should never be trying to send a critical notification for
6271 * a hard limit... the process would be killed before it could be
6274 panic("Caught sending pid %d a critical warning for a fatal limit.\n", pid
);
6278 #endif /* CONFIG_EMBEDDED */
6283 if (send_knote_count
> 0) {
6284 KNOTE(&memorystatus_klist
, 0);
6289 memorystatus_klist_unlock();
6295 * Can only be set by the current task on itself.
6298 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
6300 boolean_t set_privilege
= FALSE
;
6302 * Need an entitlement check here?
6304 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
6305 set_privilege
= TRUE
;
6306 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
6307 set_privilege
= FALSE
;
6312 return (task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
));
6316 memorystatus_send_pressure_note(pid_t pid
) {
6317 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
6318 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
6322 memorystatus_send_low_swap_note(void) {
6324 struct knote
*kn
= NULL
;
6326 memorystatus_klist_lock();
6327 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6328 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
6329 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
6330 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
6331 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
6332 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
6333 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
6338 memorystatus_klist_unlock();
6342 memorystatus_bg_pressure_eligible(proc_t p
) {
6343 boolean_t eligible
= FALSE
;
6347 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
6349 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
6350 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
6360 memorystatus_is_foreground_locked(proc_t p
) {
6361 return ((p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
6362 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
));
6366 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
6367 * to access the p_memstat_dirty field.
6370 memorystatus_proc_is_dirty_unsafe(void *v
)
6375 proc_t p
= (proc_t
)v
;
6376 return (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) != 0;
6379 #endif /* CONFIG_MEMORYSTATUS */
6382 * Trigger levels to test the mechanism.
6383 * Can be used via a sysctl.
6385 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
6386 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
6387 #define TEST_PURGEABLE_TRIGGER_ONE 3
6388 #define TEST_PURGEABLE_TRIGGER_ALL 4
6389 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
6390 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
6392 boolean_t memorystatus_manual_testing_on
= FALSE
;
6393 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
6395 extern struct knote
*
6396 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
6399 * This value is the threshold that a process must meet to be considered for scavenging.
6402 #define VM_PRESSURE_MINIMUM_RSIZE 1 /* MB */
6403 #else /* CONFIG_EMBEDDED */
6404 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
6405 #endif /* CONFIG_EMBEDDED */
6407 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
6410 #define VM_PRESSURE_DEBUG(cond, format, ...) \
6412 if (cond) { printf(format, ##__VA_ARGS__); } \
6415 #define VM_PRESSURE_DEBUG(cond, format, ...)
6418 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
6420 void memorystatus_on_pageout_scan_end(void) {
6427 * knote_pressure_level - to check if the knote is registered for this notification level.
6429 * task - task whose bits we'll be modifying
6431 * 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.
6433 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
6438 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
)
6440 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
6442 if (pressure_level_to_clear
&& task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
6444 task_clear_has_been_notified(task
, pressure_level_to_clear
);
6447 task_mark_has_been_notified(task
, pressure_level_to_set
);
6455 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
)
6457 struct knote
*kn
= NULL
;
6459 memorystatus_klist_lock();
6460 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6462 proc_t p
= PROC_NULL
;
6463 struct task
* t
= TASK_NULL
;
6465 p
= knote_get_kq(kn
)->kq_p
;
6467 if (p
!= proc_ref_locked(p
)) {
6474 t
= (struct task
*)(p
->task
);
6476 task_clear_has_been_notified(t
, pressure_level_to_clear
);
6481 memorystatus_klist_unlock();
6484 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
6487 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
);
6490 * Used by the vm_pressure_thread which is
6491 * signalled from within vm_pageout_scan().
6493 static void vm_dispatch_memory_pressure(void);
6494 void consider_vm_pressure_events(void);
6496 void consider_vm_pressure_events(void)
6498 vm_dispatch_memory_pressure();
6500 static void vm_dispatch_memory_pressure(void)
6502 memorystatus_update_vm_pressure(FALSE
);
6505 extern vm_pressure_level_t
6506 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
6509 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
)
6511 struct knote
*kn
= NULL
, *kn_max
= NULL
;
6512 uint64_t resident_max
= 0; /* MB */
6513 struct timeval curr_tstamp
= {0, 0};
6514 int elapsed_msecs
= 0;
6515 int selected_task_importance
= 0;
6516 static int pressure_snapshot
= -1;
6517 boolean_t pressure_increase
= FALSE
;
6519 if (pressure_snapshot
== -1) {
6523 pressure_snapshot
= level
;
6524 pressure_increase
= TRUE
;
6527 if (level
&& (level
>= pressure_snapshot
)) {
6528 pressure_increase
= TRUE
;
6530 pressure_increase
= FALSE
;
6533 pressure_snapshot
= level
;
6536 if (pressure_increase
== TRUE
) {
6538 * We'll start by considering the largest
6539 * unimportant task in our list.
6541 selected_task_importance
= INT_MAX
;
6544 * We'll start by considering the largest
6545 * important task in our list.
6547 selected_task_importance
= 0;
6550 microuptime(&curr_tstamp
);
6552 SLIST_FOREACH(kn
, candidate_list
, kn_selnext
) {
6554 uint64_t resident_size
= 0; /* MB */
6555 proc_t p
= PROC_NULL
;
6556 struct task
* t
= TASK_NULL
;
6557 int curr_task_importance
= 0;
6558 boolean_t consider_knote
= FALSE
;
6559 boolean_t privileged_listener
= FALSE
;
6561 p
= knote_get_kq(kn
)->kq_p
;
6563 if (p
!= proc_ref_locked(p
)) {
6570 #if CONFIG_MEMORYSTATUS
6571 if (target_foreground_process
== TRUE
&& !memorystatus_is_foreground_locked(p
)) {
6573 * Skip process not marked foreground.
6578 #endif /* CONFIG_MEMORYSTATUS */
6580 t
= (struct task
*)(p
->task
);
6582 timevalsub(&curr_tstamp
, &p
->vm_pressure_last_notify_tstamp
);
6583 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6585 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(level
);
6587 if ((kn
->kn_sfflags
& dispatch_level
) == 0) {
6592 #if CONFIG_MEMORYSTATUS
6593 if (target_foreground_process
== FALSE
&& !memorystatus_bg_pressure_eligible(p
)) {
6594 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p
->p_pid
);
6598 #endif /* CONFIG_MEMORYSTATUS */
6601 curr_task_importance
= p
->p_memstat_effectivepriority
;
6602 #else /* CONFIG_EMBEDDED */
6603 curr_task_importance
= task_importance_estimate(t
);
6604 #endif /* CONFIG_EMBEDDED */
6607 * Privileged listeners are only considered in the multi-level pressure scheme
6608 * AND only if the pressure is increasing.
6612 if (task_has_been_notified(t
, level
) == FALSE
) {
6615 * Is this a privileged listener?
6617 if (task_low_mem_privileged_listener(t
, FALSE
, &privileged_listener
) == 0) {
6619 if (privileged_listener
) {
6629 } else if (level
== 0) {
6632 * Task wasn't notified when the pressure was increasing and so
6633 * no need to notify it that the pressure is decreasing.
6635 if ((task_has_been_notified(t
, kVMPressureWarning
) == FALSE
) && (task_has_been_notified(t
, kVMPressureCritical
) == FALSE
)) {
6642 * We don't want a small process to block large processes from
6643 * being notified again. <rdar://problem/7955532>
6645 resident_size
= (get_task_phys_footprint(t
))/(1024*1024ULL); /* MB */
6647 if (resident_size
>= VM_PRESSURE_MINIMUM_RSIZE
) {
6651 * Warning or Critical Pressure.
6653 if (pressure_increase
) {
6654 if ((curr_task_importance
< selected_task_importance
) ||
6655 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6658 * We have found a candidate process which is:
6659 * a) at a lower importance than the current selected process
6661 * b) has importance equal to that of the current selected process but is larger
6664 consider_knote
= TRUE
;
6667 if ((curr_task_importance
> selected_task_importance
) ||
6668 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6671 * We have found a candidate process which is:
6672 * a) at a higher importance than the current selected process
6674 * b) has importance equal to that of the current selected process but is larger
6677 consider_knote
= TRUE
;
6680 } else if (level
== 0) {
6682 * Pressure back to normal.
6684 if ((curr_task_importance
> selected_task_importance
) ||
6685 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6687 consider_knote
= TRUE
;
6691 if (consider_knote
) {
6692 resident_max
= resident_size
;
6694 selected_task_importance
= curr_task_importance
;
6695 consider_knote
= FALSE
; /* reset for the next candidate */
6698 /* There was no candidate with enough resident memory to scavenge */
6699 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p
->p_pid
, resident_size
);
6706 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);
6707 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
);
6713 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
6714 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6715 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6717 uint64_t next_warning_notification_sent_at_ts
= 0;
6718 uint64_t next_critical_notification_sent_at_ts
= 0;
6721 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
6723 struct knote
*kn_max
= NULL
;
6724 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
6725 pid_t target_pid
= -1;
6726 struct klist dispatch_klist
= { NULL
};
6727 proc_t target_proc
= PROC_NULL
;
6728 struct task
*task
= NULL
;
6729 boolean_t found_candidate
= FALSE
;
6731 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
6732 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
6733 boolean_t smoothing_window_started
= FALSE
;
6734 struct timeval smoothing_window_start_tstamp
= {0, 0};
6735 struct timeval curr_tstamp
= {0, 0};
6736 int elapsed_msecs
= 0;
6737 uint64_t curr_ts
= mach_absolute_time();
6740 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
6742 int idle_kill_counter
= 0;
6745 * On desktop we take this opportunity to free up memory pressure
6746 * by immediately killing idle exitable processes. We use a delay
6747 * to avoid overkill. And we impose a max counter as a fail safe
6748 * in case daemons re-launch too fast.
6750 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
6751 if (memorystatus_idle_exit_from_VM() == FALSE
) {
6752 /* No idle exitable processes left to kill */
6755 idle_kill_counter
++;
6757 if (memorystatus_manual_testing_on
== TRUE
) {
6759 * Skip the delay when testing
6760 * the pressure notification scheme.
6763 delay(1000000); /* 1 second */
6766 #endif /* !CONFIG_JETSAM */
6768 if (level_snapshot
!= kVMPressureNormal
) {
6771 * Check to see if we are still in the 'resting' period
6772 * after having notified all clients interested in
6773 * a particular pressure level.
6776 level_snapshot
= memorystatus_vm_pressure_level
;
6778 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6780 if (next_warning_notification_sent_at_ts
) {
6781 if (curr_ts
< next_warning_notification_sent_at_ts
) {
6782 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6783 return KERN_SUCCESS
;
6786 next_warning_notification_sent_at_ts
= 0;
6787 memorystatus_klist_reset_all_for_level(kVMPressureWarning
);
6789 } else if (level_snapshot
== kVMPressureCritical
) {
6791 if (next_critical_notification_sent_at_ts
) {
6792 if (curr_ts
< next_critical_notification_sent_at_ts
) {
6793 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6794 return KERN_SUCCESS
;
6796 next_critical_notification_sent_at_ts
= 0;
6797 memorystatus_klist_reset_all_for_level(kVMPressureCritical
);
6805 * There is a race window here. But it's not clear
6806 * how much we benefit from having extra synchronization.
6808 level_snapshot
= memorystatus_vm_pressure_level
;
6810 if (prev_level_snapshot
> level_snapshot
) {
6812 * Pressure decreased? Let's take a little breather
6813 * and see if this condition stays.
6815 if (smoothing_window_started
== FALSE
) {
6817 smoothing_window_started
= TRUE
;
6818 microuptime(&smoothing_window_start_tstamp
);
6821 microuptime(&curr_tstamp
);
6822 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
6823 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6825 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
6827 delay(INTER_NOTIFICATION_DELAY
);
6832 prev_level_snapshot
= level_snapshot
;
6833 smoothing_window_started
= FALSE
;
6835 memorystatus_klist_lock();
6836 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
6838 if (kn_max
== NULL
) {
6839 memorystatus_klist_unlock();
6842 * No more level-based clients to notify.
6844 * Start the 'resting' window within which clients will not be re-notified.
6847 if (level_snapshot
!= kVMPressureNormal
) {
6848 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6849 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6851 /* Next warning notification (if nothing changes) won't be sent before...*/
6852 next_warning_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6855 if (level_snapshot
== kVMPressureCritical
) {
6856 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6858 /* Next critical notification (if nothing changes) won't be sent before...*/
6859 next_critical_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6862 return KERN_FAILURE
;
6865 target_proc
= knote_get_kq(kn_max
)->kq_p
;
6868 if (target_proc
!= proc_ref_locked(target_proc
)) {
6869 target_proc
= PROC_NULL
;
6871 memorystatus_klist_unlock();
6876 target_pid
= target_proc
->p_pid
;
6878 task
= (struct task
*)(target_proc
->task
);
6880 if (level_snapshot
!= kVMPressureNormal
) {
6882 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6884 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, 0, kVMPressureWarning
) == TRUE
) {
6885 found_candidate
= TRUE
;
6888 if (level_snapshot
== kVMPressureCritical
) {
6890 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, 0, kVMPressureCritical
) == TRUE
) {
6891 found_candidate
= TRUE
;
6896 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6898 task_clear_has_been_notified(task
, kVMPressureWarning
);
6899 task_clear_has_been_notified(task
, kVMPressureCritical
);
6901 found_candidate
= TRUE
;
6905 if (found_candidate
== FALSE
) {
6906 proc_rele(target_proc
);
6907 memorystatus_klist_unlock();
6911 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
6913 int knote_pressure_level
= convert_internal_pressure_level_to_dispatch_level(level_snapshot
);
6915 if (is_knote_registered_modify_task_pressure_bits(kn_cur
, knote_pressure_level
, task
, 0, level_snapshot
) == TRUE
) {
6916 proc_t knote_proc
= knote_get_kq(kn_cur
)->kq_p
;
6917 pid_t knote_pid
= knote_proc
->p_pid
;
6918 if (knote_pid
== target_pid
) {
6919 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
6920 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
6925 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
6927 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
6928 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
6929 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
6932 memorystatus_klist_unlock();
6934 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
6935 proc_rele(target_proc
);
6937 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
6941 if (memorystatus_manual_testing_on
== TRUE
) {
6943 * Testing out the pressure notification scheme.
6944 * No need for delays etc.
6948 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
6950 unsigned int page_delta
= 0;
6951 unsigned int skip_delay_page_threshold
= 0;
6953 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
6955 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
6956 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
6958 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
6960 * We are nearing the critcal mark fast and can't afford to wait between
6965 #endif /* CONFIG_JETSAM */
6967 if (sleep_interval
) {
6968 delay(sleep_interval
);
6973 return KERN_SUCCESS
;
6977 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
6979 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6981 switch (internal_pressure_level
) {
6983 case kVMPressureNormal
:
6985 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6989 case kVMPressureWarning
:
6990 case kVMPressureUrgent
:
6992 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
6996 case kVMPressureCritical
:
6998 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
7006 return dispatch_level
;
7010 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
7012 #pragma unused(arg1, arg2, oidp)
7016 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
7020 #endif /* CONFIG_EMBEDDED */
7021 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
7023 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
7026 #if DEBUG || DEVELOPMENT
7028 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
,
7029 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
7031 #else /* DEBUG || DEVELOPMENT */
7033 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
7034 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
7036 #endif /* DEBUG || DEVELOPMENT */
7038 extern int memorystatus_purge_on_warning
;
7039 extern int memorystatus_purge_on_critical
;
7042 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
7044 #pragma unused(arg1, arg2)
7048 int pressure_level
= 0;
7049 int trigger_request
= 0;
7052 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
7053 if (error
|| !req
->newptr
) {
7057 memorystatus_manual_testing_on
= TRUE
;
7059 trigger_request
= (level
>> 16) & 0xFFFF;
7060 pressure_level
= (level
& 0xFFFF);
7062 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
7063 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
7066 switch (pressure_level
) {
7067 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
7068 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
7069 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
7076 * The pressure level is being set from user-space.
7077 * And user-space uses the constants in sys/event.h
7078 * So we translate those events to our internal levels here.
7080 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
7082 memorystatus_manual_testing_level
= kVMPressureNormal
;
7085 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
7087 memorystatus_manual_testing_level
= kVMPressureWarning
;
7088 force_purge
= memorystatus_purge_on_warning
;
7090 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
7092 memorystatus_manual_testing_level
= kVMPressureCritical
;
7093 force_purge
= memorystatus_purge_on_critical
;
7096 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
7098 /* purge according to the new pressure level */
7099 switch (trigger_request
) {
7100 case TEST_PURGEABLE_TRIGGER_ONE
:
7101 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
7102 if (force_purge
== 0) {
7103 /* no purging requested */
7106 vm_purgeable_object_purge_one_unlocked(force_purge
);
7108 case TEST_PURGEABLE_TRIGGER_ALL
:
7109 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
7110 if (force_purge
== 0) {
7111 /* no purging requested */
7114 while (vm_purgeable_object_purge_one_unlocked(force_purge
));
7118 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
7119 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
7121 memorystatus_update_vm_pressure(TRUE
);
7124 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
7125 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
7127 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
7132 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
7133 memorystatus_manual_testing_on
= FALSE
;
7139 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
7140 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
7143 extern int memorystatus_purge_on_warning
;
7144 extern int memorystatus_purge_on_urgent
;
7145 extern int memorystatus_purge_on_critical
;
7147 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_warning
, 0, "");
7148 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_urgent
, 0, "");
7149 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_critical
, 0, "");
7152 #endif /* VM_PRESSURE_EVENTS */
7154 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
7156 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
7158 uint32_t list_count
, i
= 0;
7159 memorystatus_priority_entry_t
*list_entry
;
7162 list_count
= memorystatus_list_count
;
7163 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
7165 /* Just a size check? */
7170 /* Otherwise, validate the size of the buffer */
7171 if (*buffer_size
< *list_size
) {
7175 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
7180 memset(*list_ptr
, 0, *list_size
);
7182 *buffer_size
= *list_size
;
7185 list_entry
= *list_ptr
;
7189 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
7190 while (p
&& (*list_size
< *buffer_size
)) {
7191 list_entry
->pid
= p
->p_pid
;
7192 list_entry
->priority
= p
->p_memstat_effectivepriority
;
7193 list_entry
->user_data
= p
->p_memstat_userdata
;
7195 if (p
->p_memstat_memlimit
<= 0) {
7196 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
7198 list_entry
->limit
= p
->p_memstat_memlimit
;
7201 list_entry
->state
= memorystatus_build_state(p
);
7204 *list_size
+= sizeof(memorystatus_priority_entry_t
);
7206 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
7211 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
7217 memorystatus_get_priority_pid(pid_t pid
, user_addr_t buffer
, size_t buffer_size
) {
7219 memorystatus_priority_entry_t mp_entry
;
7221 /* Validate inputs */
7222 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_entry_t
))) {
7226 proc_t p
= proc_find(pid
);
7231 memset (&mp_entry
, 0, sizeof(memorystatus_priority_entry_t
));
7233 mp_entry
.pid
= p
->p_pid
;
7234 mp_entry
.priority
= p
->p_memstat_effectivepriority
;
7235 mp_entry
.user_data
= p
->p_memstat_userdata
;
7236 if (p
->p_memstat_memlimit
<= 0) {
7237 task_get_phys_footprint_limit(p
->task
, &mp_entry
.limit
);
7239 mp_entry
.limit
= p
->p_memstat_memlimit
;
7241 mp_entry
.state
= memorystatus_build_state(p
);
7245 error
= copyout(&mp_entry
, buffer
, buffer_size
);
7251 memorystatus_cmd_get_priority_list(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
7253 boolean_t size_only
;
7257 * When a non-zero pid is provided, the 'list' has only one entry.
7260 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
7263 list_size
= sizeof(memorystatus_priority_entry_t
) * 1;
7265 error
= memorystatus_get_priority_pid(pid
, buffer
, buffer_size
);
7268 memorystatus_priority_entry_t
*list
= NULL
;
7269 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
7273 error
= copyout(list
, buffer
, list_size
);
7278 kfree(list
, buffer_size
);
7283 *retval
= list_size
;
7290 memorystatus_clear_errors(void)
7295 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
7299 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
7301 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
7302 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
7304 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
7309 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
7314 memorystatus_update_levels_locked(boolean_t critical_only
) {
7316 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
7319 * If there's an entry in the first bucket, we have idle processes.
7322 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
7323 if (first_bucket
->count
) {
7324 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
7326 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
7328 * The critical threshold must never exceed the pressure threshold
7330 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
7334 #if DEBUG || DEVELOPMENT
7335 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
7336 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
7338 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
7340 * The critical threshold must never exceed the pressure threshold
7342 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
7345 #endif /* DEBUG || DEVELOPMENT */
7347 if (memorystatus_jetsam_policy
& kPolicyMoreFree
) {
7348 memorystatus_available_pages_critical
+= memorystatus_policy_more_free_offset_pages
;
7351 if (critical_only
) {
7355 #if VM_PRESSURE_EVENTS
7356 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
7357 #if DEBUG || DEVELOPMENT
7358 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
7359 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
7367 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
7369 #pragma unused(arg1, arg2, oidp)
7370 int error
= 0, more_free
= 0;
7373 * TODO: Enable this privilege check?
7375 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
7380 error
= sysctl_handle_int(oidp
, &more_free
, 0, req
);
7381 if (error
|| !req
->newptr
)
7384 if ((more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == kPolicyMoreFree
)) ||
7385 (!more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == 0))) {
7388 * No change in state.
7396 memorystatus_jetsam_policy
|= kPolicyMoreFree
;
7398 memorystatus_jetsam_policy
&= ~kPolicyMoreFree
;
7401 memorystatus_update_levels_locked(TRUE
);
7407 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_policy_more_free
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
7408 0, 0, &sysctl_kern_memorystatus_policy_more_free
, "I", "");
7410 #endif /* CONFIG_JETSAM */
7413 * Get the at_boot snapshot
7416 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7417 size_t input_size
= *snapshot_size
;
7420 * The at_boot snapshot has no entry list.
7422 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
7429 * Validate the size of the snapshot buffer
7431 if (input_size
< *snapshot_size
) {
7436 * Update the notification_time only
7438 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
7439 *snapshot
= &memorystatus_at_boot_snapshot
;
7441 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
7442 (long)input_size
, (long)*snapshot_size
, 0);
7447 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7448 size_t input_size
= *snapshot_size
;
7449 uint32_t ods_list_count
= memorystatus_list_count
;
7450 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
7452 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
7459 * Validate the size of the snapshot buffer.
7460 * This is inherently racey. May want to revisit
7461 * this error condition and trim the output when
7464 if (input_size
< *snapshot_size
) {
7469 * Allocate and initialize a snapshot buffer.
7471 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
7476 memset(ods
, 0, *snapshot_size
);
7479 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
7483 * Return the kernel allocated, on_demand buffer.
7484 * The caller of this routine will copy the data out
7485 * to user space and then free the kernel allocated
7490 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7491 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
7497 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7498 size_t input_size
= *snapshot_size
;
7500 if (memorystatus_jetsam_snapshot_count
> 0) {
7501 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
7510 if (input_size
< *snapshot_size
) {
7514 *snapshot
= memorystatus_jetsam_snapshot
;
7516 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7517 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
7524 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
7526 boolean_t size_only
;
7527 boolean_t is_default_snapshot
= FALSE
;
7528 boolean_t is_on_demand_snapshot
= FALSE
;
7529 boolean_t is_at_boot_snapshot
= FALSE
;
7530 memorystatus_jetsam_snapshot_t
*snapshot
;
7532 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
7536 is_default_snapshot
= TRUE
;
7537 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
7539 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7541 * Unsupported bit set in flag.
7546 if ((flags
& (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) ==
7547 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7549 * Can't have both set at the same time.
7554 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
7555 is_on_demand_snapshot
= TRUE
;
7557 * When not requesting the size only, the following call will allocate
7558 * an on_demand snapshot buffer, which is freed below.
7560 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
7562 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
7563 is_at_boot_snapshot
= TRUE
;
7564 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
7567 * Invalid flag setting.
7578 * Copy the data out to user space and clear the snapshot buffer.
7579 * If working with the jetsam snapshot,
7580 * clearing the buffer means, reset the count.
7581 * If working with an on_demand snapshot
7582 * clearing the buffer means, free it.
7583 * If working with the at_boot snapshot
7584 * there is nothing to clear or update.
7587 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
7588 if (is_default_snapshot
) {
7590 * The jetsam snapshot is never freed, its count is simply reset.
7593 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
7594 memorystatus_jetsam_snapshot_last_timestamp
= 0;
7599 if (is_on_demand_snapshot
) {
7601 * The on_demand snapshot is always freed,
7602 * even if the copyout failed.
7605 kfree(snapshot
, buffer_size
);
7611 *retval
= buffer_size
;
7618 * Routine: memorystatus_cmd_grp_set_properties
7619 * Purpose: Update properties for a group of processes.
7621 * Supported Properties:
7623 * Move each process out of its effective priority
7624 * band and into a new priority band.
7625 * Maintains relative order from lowest to highest priority.
7626 * In single band, maintains relative order from head to tail.
7628 * eg: before [effectivepriority | pid]
7630 * [17 | p55, p67, p19 ]
7635 * after [ new band | pid]
7636 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7638 * Returns: 0 on success, else non-zero.
7640 * Caveat: We know there is a race window regarding recycled pids.
7641 * A process could be killed before the kernel can act on it here.
7642 * If a pid cannot be found in any of the jetsam priority bands,
7643 * then we simply ignore it. No harm.
7644 * But, if the pid has been recycled then it could be an issue.
7645 * In that scenario, we might move an unsuspecting process to the new
7646 * priority band. It's not clear how the kernel can safeguard
7647 * against this, but it would be an extremely rare case anyway.
7648 * The caller of this api might avoid such race conditions by
7649 * ensuring that the processes passed in the pid list are suspended.
7653 /* This internal structure can expand when we add support for more properties */
7654 typedef struct memorystatus_internal_properties
7657 int32_t priority
; /* see memorytstatus_priority_entry_t : priority */
7658 } memorystatus_internal_properties_t
;
7662 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7664 #pragma unused (flags)
7667 * We only handle setting priority
7672 memorystatus_priority_entry_t
*entries
= NULL
;
7673 uint32_t entry_count
= 0;
7675 /* This will be the ordered proc list */
7676 memorystatus_internal_properties_t
*table
= NULL
;
7677 size_t table_size
= 0;
7678 uint32_t table_count
= 0;
7681 uint32_t bucket_index
= 0;
7682 boolean_t head_insert
;
7683 int32_t new_priority
;
7688 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0) || ((buffer_size
% sizeof(memorystatus_priority_entry_t
)) != 0)) {
7693 entry_count
= (buffer_size
/ sizeof(memorystatus_priority_entry_t
));
7694 if ((entries
= (memorystatus_priority_entry_t
*)kalloc(buffer_size
)) == NULL
) {
7699 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_START
, entry_count
, 0, 0, 0, 0);
7701 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
7705 /* Verify sanity of input priorities */
7706 for (i
=0; i
< entry_count
; i
++) {
7707 if (entries
[i
].priority
== -1) {
7708 /* Use as shorthand for default priority */
7709 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
7710 } else if ((entries
[i
].priority
== system_procs_aging_band
) || (entries
[i
].priority
== applications_aging_band
)) {
7711 /* Both the aging bands are reserved for internal use;
7712 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
7713 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
7714 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7715 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7717 /* Deal with this later */
7718 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
7725 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
7726 if ( (table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
7730 memset(table
, 0, table_size
);
7734 * For each jetsam bucket entry, spin through the input property list.
7735 * When a matching pid is found, populate an adjacent table with the
7736 * appropriate proc pointer and new property values.
7737 * This traversal automatically preserves order from lowest
7738 * to highest priority.
7745 /* Create the ordered table */
7746 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
7747 while (p
&& (table_count
< entry_count
)) {
7748 for (i
=0; i
< entry_count
; i
++ ) {
7749 if (p
->p_pid
== entries
[i
].pid
) {
7750 /* Build the table data */
7751 table
[table_count
].proc
= p
;
7752 table
[table_count
].priority
= entries
[i
].priority
;
7757 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
7760 /* We now have ordered list of procs ready to move */
7761 for (i
=0; i
< table_count
; i
++) {
7765 /* Allow head inserts -- but relative order is now */
7766 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7767 new_priority
= JETSAM_PRIORITY_IDLE
;
7770 new_priority
= table
[i
].priority
;
7771 head_insert
= false;
7775 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7780 * Take appropriate steps if moving proc out of
7781 * either of the aging bands.
7783 if ((p
->p_memstat_effectivepriority
== system_procs_aging_band
) || (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
7784 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7787 memorystatus_update_priority_locked(p
, new_priority
, head_insert
, false);
7793 * if (table_count != entry_count)
7794 * then some pids were not found in a jetsam band.
7795 * harmless but interesting...
7797 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_END
, entry_count
, table_count
, 0, 0, 0);
7801 kfree(entries
, buffer_size
);
7803 kfree(table
, table_size
);
7810 * This routine is used to update a process's jetsam priority position and stored user_data.
7811 * It is not used for the setting of memory limits, which is why the last 6 args to the
7812 * memorystatus_update() call are 0 or FALSE.
7816 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7818 memorystatus_priority_properties_t mpp_entry
;
7820 /* Validate inputs */
7821 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
7825 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
7835 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7840 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
);
7848 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7850 memorystatus_memlimit_properties_t mmp_entry
;
7852 /* Validate inputs */
7853 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7857 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
7860 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
7867 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7868 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7869 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
7870 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7871 * to the task's ledgers via task_set_phys_footprint_limit().
7874 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7876 memorystatus_memlimit_properties_t mmp_entry
;
7878 /* Validate inputs */
7879 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7883 memset (&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
7885 proc_t p
= proc_find(pid
);
7891 * Get the active limit and attributes.
7892 * No locks taken since we hold a reference to the proc.
7895 if (p
->p_memstat_memlimit_active
> 0 ) {
7896 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
7898 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
7901 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
7902 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7906 * Get the inactive limit and attributes
7908 if (p
->p_memstat_memlimit_inactive
<= 0) {
7909 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
7911 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
7913 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
7914 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7918 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
7925 * SPI for kbd - pr24956468
7926 * This is a very simple snapshot that calculates how much a
7927 * process's phys_footprint exceeds a specific memory limit.
7928 * Only the inactive memory limit is supported for now.
7929 * The delta is returned as bytes in excess or zero.
7932 memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7934 uint64_t footprint_in_bytes
= 0;
7935 uint64_t delta_in_bytes
= 0;
7936 int32_t memlimit_mb
= 0;
7937 uint64_t memlimit_bytes
= 0;
7939 /* Validate inputs */
7940 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(uint64_t)) || (flags
!= 0)) {
7944 proc_t p
= proc_find(pid
);
7950 * Get the inactive limit.
7951 * No locks taken since we hold a reference to the proc.
7954 if (p
->p_memstat_memlimit_inactive
<= 0) {
7955 task_convert_phys_footprint_limit(-1, &memlimit_mb
);
7957 memlimit_mb
= p
->p_memstat_memlimit_inactive
;
7960 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
7964 memlimit_bytes
= memlimit_mb
* 1024 * 1024; /* MB to bytes */
7967 * Computed delta always returns >= 0 bytes
7969 if (footprint_in_bytes
> memlimit_bytes
) {
7970 delta_in_bytes
= footprint_in_bytes
- memlimit_bytes
;
7973 error
= copyout(&delta_in_bytes
, buffer
, sizeof(delta_in_bytes
));
7980 memorystatus_cmd_get_pressure_status(int32_t *retval
) {
7983 /* Need privilege for check */
7984 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
7989 /* Inherently racy, so it's not worth taking a lock here */
7990 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7996 memorystatus_get_pressure_status_kdp() {
7997 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
8001 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
8003 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
8004 * So, with 2-level HWM preserving previous behavior will map as follows.
8005 * - treat the limit passed in as both an active and inactive limit.
8006 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
8008 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
8009 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
8010 * - so mapping is (active/non-fatal, inactive/non-fatal)
8012 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
8013 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
8014 * - so mapping is (active/fatal, inactive/fatal)
8019 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
) {
8021 memorystatus_memlimit_properties_t entry
;
8023 entry
.memlimit_active
= high_water_mark
;
8024 entry
.memlimit_active_attr
= 0;
8025 entry
.memlimit_inactive
= high_water_mark
;
8026 entry
.memlimit_inactive_attr
= 0;
8028 if (is_fatal_limit
== TRUE
) {
8029 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
8030 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
8033 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
8036 #endif /* CONFIG_JETSAM */
8039 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
) {
8041 int32_t memlimit_active
;
8042 boolean_t memlimit_active_is_fatal
;
8043 int32_t memlimit_inactive
;
8044 boolean_t memlimit_inactive_is_fatal
;
8045 uint32_t valid_attrs
= 0;
8048 proc_t p
= proc_find(pid
);
8054 * Check for valid attribute flags.
8056 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
8057 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
8061 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
8067 * Setup the active memlimit properties
8069 memlimit_active
= entry
->memlimit_active
;
8070 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
8071 memlimit_active_is_fatal
= TRUE
;
8073 memlimit_active_is_fatal
= FALSE
;
8077 * Setup the inactive memlimit properties
8079 memlimit_inactive
= entry
->memlimit_inactive
;
8080 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
8081 memlimit_inactive_is_fatal
= TRUE
;
8083 memlimit_inactive_is_fatal
= FALSE
;
8087 * Setting a limit of <= 0 implies that the process has no
8088 * high-water-mark and has no per-task-limit. That means
8089 * the system_wide task limit is in place, which by the way,
8093 if (memlimit_active
<= 0) {
8095 * Enforce the fatal system_wide task limit while process is active.
8097 memlimit_active
= -1;
8098 memlimit_active_is_fatal
= TRUE
;
8101 if (memlimit_inactive
<= 0) {
8103 * Enforce the fatal system_wide task limit while process is inactive.
8105 memlimit_inactive
= -1;
8106 memlimit_inactive_is_fatal
= TRUE
;
8112 * Store the active limit variants in the proc.
8114 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
8117 * Store the inactive limit variants in the proc.
8119 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
8122 * Enforce appropriate limit variant by updating the cached values
8123 * and writing the ledger.
8124 * Limit choice is based on process active/inactive state.
8127 if (memorystatus_highwater_enabled
) {
8129 boolean_t use_active
;
8131 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
8132 CACHE_ACTIVE_LIMITS_LOCKED(p
, is_fatal
);
8135 CACHE_INACTIVE_LIMITS_LOCKED(p
, is_fatal
);
8139 /* Enforce the limit by writing to the ledgers */
8140 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
;
8142 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
8143 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
8144 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
8145 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
8146 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit
, proc_t
, p
, int32_t, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1));
8156 * Returns the jetsam priority (effective or requested) of the process
8157 * associated with this task.
8160 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
8163 if (effective_priority
) {
8164 return p
->p_memstat_effectivepriority
;
8166 return p
->p_memstat_requestedpriority
;
8173 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
) {
8175 os_reason_t jetsam_reason
= OS_REASON_NULL
;
8179 #pragma unused(jetsam_reason)
8182 /* Need to be root or have entitlement */
8183 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
8190 * Do not enforce it for snapshots.
8192 if (args
->command
!= MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
) {
8193 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
8199 switch (args
->command
) {
8200 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
8201 error
= memorystatus_cmd_get_priority_list(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
8203 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
8204 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
8206 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
8207 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
8209 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
8210 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
8212 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS
:
8213 error
= memorystatus_cmd_get_memlimit_excess_np(args
->pid
, args
->flags
, args
->buffer
, args
->buffersize
, ret
);
8215 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
8216 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
8218 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
8219 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
8221 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
8222 error
= memorystatus_cmd_get_pressure_status(ret
);
8225 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
8227 * This call does not distinguish between active and inactive limits.
8228 * Default behavior in 2-level HWM world is to set both.
8229 * Non-fatal limit is also assumed for both.
8231 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
8233 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
8235 * This call does not distinguish between active and inactive limits.
8236 * Default behavior in 2-level HWM world is to set both.
8237 * Fatal limit is also assumed for both.
8239 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
8241 #endif /* CONFIG_JETSAM */
8243 #if DEVELOPMENT || DEBUG
8244 case MEMORYSTATUS_CMD_TEST_JETSAM
:
8245 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_GENERIC
);
8246 if (jetsam_reason
== OS_REASON_NULL
) {
8247 printf("memorystatus_control: failed to allocate jetsam reason\n");
8250 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
, jetsam_reason
) ? 0 : EINVAL
;
8252 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
8253 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
8256 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
8257 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
8259 #endif /* CONFIG_JETSAM */
8260 #else /* DEVELOPMENT || DEBUG */
8261 #pragma unused(jetsam_reason)
8262 #endif /* DEVELOPMENT || DEBUG */
8263 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE
:
8264 if (memorystatus_aggressive_jetsam_lenient_allowed
== FALSE
) {
8265 #if DEVELOPMENT || DEBUG
8266 printf("Enabling Lenient Mode\n");
8267 #endif /* DEVELOPMENT || DEBUG */
8269 memorystatus_aggressive_jetsam_lenient_allowed
= TRUE
;
8270 memorystatus_aggressive_jetsam_lenient
= TRUE
;
8274 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE
:
8275 #if DEVELOPMENT || DEBUG
8276 printf("Disabling Lenient mode\n");
8277 #endif /* DEVELOPMENT || DEBUG */
8278 memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
8279 memorystatus_aggressive_jetsam_lenient
= FALSE
;
8282 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
8283 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
8284 error
= memorystatus_low_mem_privileged_listener(args
->command
);
8287 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
:
8288 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
:
8289 error
= memorystatus_update_inactive_jetsam_priority_band(args
->pid
, args
->command
, args
->flags
? TRUE
: FALSE
);
8302 filt_memorystatusattach(struct knote
*kn
, __unused
struct kevent_internal_s
*kev
)
8306 kn
->kn_flags
|= EV_CLEAR
;
8307 error
= memorystatus_knote_register(kn
);
8309 kn
->kn_flags
= EV_ERROR
;
8310 kn
->kn_data
= error
;
8316 filt_memorystatusdetach(struct knote
*kn
)
8318 memorystatus_knote_unregister(kn
);
8322 filt_memorystatus(struct knote
*kn __unused
, long hint
)
8326 case kMemorystatusNoPressure
:
8327 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
8328 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
8331 case kMemorystatusPressure
:
8332 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
8333 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
8334 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
8336 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
8338 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
8339 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
8343 case kMemorystatusLowSwap
:
8344 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
8345 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
8349 case kMemorystatusProcLimitWarn
:
8350 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8351 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
8355 case kMemorystatusProcLimitCritical
:
8356 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8357 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
8367 if (kn
->kn_fflags
!= 0) {
8368 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
8369 pid_t knote_pid
= knote_proc
->p_pid
;
8371 printf("filt_memorystatus: sending kn 0x%lx (event 0x%x) for pid (%d)\n",
8372 (unsigned long)kn
, kn
->kn_fflags
, knote_pid
);
8376 return (kn
->kn_fflags
!= 0);
8380 filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
8383 int prev_kn_sfflags
= 0;
8385 memorystatus_klist_lock();
8388 * copy in new kevent settings
8389 * (saving the "desired" data and fflags).
8392 prev_kn_sfflags
= kn
->kn_sfflags
;
8393 kn
->kn_sfflags
= (kev
->fflags
& EVFILT_MEMORYSTATUS_ALL_MASK
);
8395 #if !CONFIG_EMBEDDED
8397 * Only on desktop do we restrict notifications to
8398 * one per active/inactive state (soft limits only).
8400 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8402 * Is there previous state to preserve?
8404 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8406 * This knote was previously interested in proc_limit_warn,
8407 * so yes, preserve previous state.
8409 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
) {
8410 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8412 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
) {
8413 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8417 * This knote was not previously interested in proc_limit_warn,
8418 * but it is now. Set both states.
8420 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8421 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8425 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8427 * Is there previous state to preserve?
8429 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8431 * This knote was previously interested in proc_limit_critical,
8432 * so yes, preserve previous state.
8434 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
) {
8435 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8437 if (prev_kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
) {
8438 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8442 * This knote was not previously interested in proc_limit_critical,
8443 * but it is now. Set both states.
8445 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8446 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8449 #endif /* !CONFIG_EMBEDDED */
8451 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
8452 kn
->kn_udata
= kev
->udata
;
8455 * reset the output flags based on a
8456 * combination of the old events and
8457 * the new desired event list.
8459 //kn->kn_fflags &= kn->kn_sfflags;
8461 res
= (kn
->kn_fflags
!= 0);
8463 memorystatus_klist_unlock();
8469 filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
8471 #pragma unused(data)
8474 memorystatus_klist_lock();
8475 res
= (kn
->kn_fflags
!= 0);
8477 *kev
= kn
->kn_kevent
;
8478 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
8482 memorystatus_klist_unlock();
8488 memorystatus_klist_lock(void) {
8489 lck_mtx_lock(&memorystatus_klist_mutex
);
8493 memorystatus_klist_unlock(void) {
8494 lck_mtx_unlock(&memorystatus_klist_mutex
);
8498 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
) {
8499 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
8500 klist_init(&memorystatus_klist
);
8504 memorystatus_knote_register(struct knote
*kn
) {
8507 memorystatus_klist_lock();
8510 * Support only userspace visible flags.
8512 if ((kn
->kn_sfflags
& EVFILT_MEMORYSTATUS_ALL_MASK
) == (unsigned int) kn
->kn_sfflags
) {
8514 #if !CONFIG_EMBEDDED
8515 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
8516 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE
;
8517 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE
;
8520 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
8521 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE
;
8522 kn
->kn_sfflags
|= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE
;
8524 #endif /* !CONFIG_EMBEDDED */
8526 KNOTE_ATTACH(&memorystatus_klist
, kn
);
8532 memorystatus_klist_unlock();
8538 memorystatus_knote_unregister(struct knote
*kn __unused
) {
8539 memorystatus_klist_lock();
8540 KNOTE_DETACH(&memorystatus_klist
, kn
);
8541 memorystatus_klist_unlock();
8546 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
8548 memorystatus_issue_pressure_kevent(boolean_t pressured
) {
8549 memorystatus_klist_lock();
8550 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
8551 memorystatus_klist_unlock();
8554 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
8557 /* Coalition support */
8559 /* sorting info for a particular priority bucket */
8560 typedef struct memstat_sort_info
{
8561 coalition_t msi_coal
;
8562 uint64_t msi_page_count
;
8565 } memstat_sort_info_t
;
8568 * qsort from smallest page count to largest page count
8570 * return < 0 for a < b
8574 static int memstat_asc_cmp(const void *a
, const void *b
)
8576 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
8577 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
8579 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
8583 * Return the number of pids rearranged during this sort.
8586 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
8588 #define MAX_SORT_PIDS 80
8589 #define MAX_COAL_LEADERS 10
8591 unsigned int b
= bucket_index
;
8595 coalition_t coal
= COALITION_NULL
;
8597 int total_pids_moved
= 0;
8601 * The system is typically under memory pressure when in this
8602 * path, hence, we want to avoid dynamic memory allocation.
8604 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
8605 pid_t pid_list
[MAX_SORT_PIDS
];
8607 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8612 * Clear the array that holds coalition leader information
8614 for (i
=0; i
< MAX_COAL_LEADERS
; i
++) {
8615 leaders
[i
].msi_coal
= COALITION_NULL
;
8616 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
8617 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
8618 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
8621 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8623 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
8624 if (nleaders
< MAX_COAL_LEADERS
) {
8625 int coal_ntasks
= 0;
8626 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
8627 leaders
[nleaders
].msi_coal
= coal
;
8628 leaders
[nleaders
].msi_page_count
= coal_page_count
;
8629 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
8630 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
8634 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8635 * Abandoned coalitions will linger at the tail of the priority band
8636 * when this sort session ends.
8637 * TODO: should this be an assert?
8639 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
8640 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
8644 p
=memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8647 if (nleaders
== 0) {
8648 /* Nothing to sort */
8653 * Sort the coalition leader array, from smallest coalition page count
8654 * to largest coalition page count. When inserted in the priority bucket,
8655 * smallest coalition is handled first, resulting in the last to be jetsammed.
8658 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
8662 for (i
= 0; i
< nleaders
; i
++) {
8663 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8664 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
8665 leaders
[i
].msi_ntasks
);
8670 * During coalition sorting, processes in a priority band are rearranged
8671 * by being re-inserted at the head of the queue. So, when handling a
8672 * list, the first process that gets moved to the head of the queue,
8673 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8675 * So, for example, the coalition leader is expected to jetsam last,
8676 * after its coalition members. Therefore, the coalition leader is
8677 * inserted at the head of the queue first.
8679 * After processing a coalition, the jetsam order is as follows:
8680 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8684 * Coalition members are rearranged in the priority bucket here,
8685 * based on their coalition role.
8687 total_pids_moved
= 0;
8688 for (i
=0; i
< nleaders
; i
++) {
8690 /* a bit of bookkeeping */
8693 /* Coalition leaders are jetsammed last, so move into place first */
8694 pid_list
[0] = leaders
[i
].msi_pid
;
8695 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
8697 /* xpc services should jetsam after extensions */
8698 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
8699 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8702 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8703 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8706 /* extensions should jetsam after unmarked processes */
8707 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
8708 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8711 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8712 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8715 /* undefined coalition members should be the first to jetsam */
8716 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
8717 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8720 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8721 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8725 if (pids_moved
== leaders
[i
].msi_ntasks
) {
8727 * All the pids in the coalition were found in this band.
8729 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
8730 pids_moved
, leaders
[i
].msi_ntasks
);
8731 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
8733 * Apparently new coalition members showed up during the sort?
8735 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
8736 pids_moved
, leaders
[i
].msi_ntasks
);
8739 * Apparently not all the pids in the coalition were found in this band?
8741 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
8742 pids_moved
, leaders
[i
].msi_ntasks
);
8746 total_pids_moved
+= pids_moved
;
8750 return(total_pids_moved
);
8755 * Traverse a list of pids, searching for each within the priority band provided.
8756 * If pid is found, move it to the front of the priority band.
8757 * Never searches outside the priority band provided.
8760 * bucket_index - jetsam priority band.
8761 * pid_list - pointer to a list of pids.
8762 * list_sz - number of pids in the list.
8764 * Pid list ordering is important in that,
8765 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8766 * The sort_order is set by the coalition default.
8769 * the number of pids found and hence moved within the priority band.
8772 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
8774 memstat_bucket_t
*current_bucket
;
8778 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
8782 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8786 current_bucket
= &memstat_bucket
[bucket_index
];
8787 for (i
=0; i
< list_sz
; i
++) {
8788 unsigned int b
= bucket_index
;
8790 proc_t aProc
= NULL
;
8794 list_index
= ((list_sz
- 1) - i
);
8795 aPid
= pid_list
[list_index
];
8797 /* never search beyond bucket_index provided */
8798 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8800 if (p
->p_pid
== aPid
) {
8804 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8807 if (aProc
== NULL
) {
8808 /* pid not found in this band, just skip it */
8811 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
8812 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
8820 memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index
)
8822 int32_t i
= JETSAM_PRIORITY_IDLE
;
8825 if (max_bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8829 while(i
<= max_bucket_index
) {
8830 count
+= memstat_bucket
[i
++].count
;
8837 memorystatus_update_priority_for_appnap(proc_t p
, boolean_t is_appnap
)
8840 if (!p
|| (!isApp(p
)) || (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
)) {
8842 * Ineligible processes OR system processes e.g. launchd.
8849 * We would like to use memorystatus_update() here to move the processes
8850 * within the bands. Unfortunately memorystatus_update() calls
8851 * memorystatus_update_priority_locked() which uses any band transitions
8852 * as an indication to modify ledgers. For that it needs the task lock
8853 * and since we came into this function with the task lock held, we'll deadlock.
8855 * Unfortunately we can't completely disable ledger updates because we still
8856 * need the ledger updates for a subset of processes i.e. daemons.
8857 * When all processes on all platforms support memory limits, we can simply call
8858 * memorystatus_update().
8860 * It also has some logic to deal with 'aging' which, currently, is only applicable
8861 * on CONFIG_JETSAM configs. So, till every platform has CONFIG_JETSAM we'll need
8862 * to do this explicit band transition.
8865 memstat_bucket_t
*current_bucket
, *new_bucket
;
8866 int32_t priority
= 0;
8870 if (((p
->p_listflag
& P_LIST_EXITED
) != 0) ||
8871 (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
))) {
8873 * If the process is on its way out OR
8874 * jetsam has alread tried and failed to kill this process,
8875 * let's skip the whole jetsam band transition.
8882 current_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
8883 new_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
8884 priority
= JETSAM_PRIORITY_IDLE
;
8886 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
8888 * It is possible that someone pulled this process
8889 * out of the IDLE band without updating its app-nap
8896 current_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
8897 new_bucket
= &memstat_bucket
[p
->p_memstat_requestedpriority
];
8898 priority
= p
->p_memstat_requestedpriority
;
8901 TAILQ_REMOVE(¤t_bucket
->list
, p
, p_memstat_list
);
8902 current_bucket
->count
--;
8904 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
8905 new_bucket
->count
++;
8908 * Record idle start or idle delta.
8910 if (p
->p_memstat_effectivepriority
== priority
) {
8912 * This process is not transitioning between
8913 * jetsam priority buckets. Do nothing.
8915 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
8918 * Transitioning out of the idle priority bucket.
8919 * Record idle delta.
8921 assert(p
->p_memstat_idle_start
!= 0);
8922 now
= mach_absolute_time();
8923 if (now
> p
->p_memstat_idle_start
) {
8924 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
8926 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
8928 * Transitioning into the idle priority bucket.
8929 * Record idle start.
8931 p
->p_memstat_idle_start
= mach_absolute_time();
8934 p
->p_memstat_effectivepriority
= priority
;
8940 #else /* !CONFIG_JETSAM */
8942 #pragma unused(is_appnap)
8944 #endif /* !CONFIG_JETSAM */