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 <libkern/libkern.h>
39 #include <mach/coalition.h>
40 #include <mach/mach_time.h>
41 #include <mach/task.h>
42 #include <mach/host_priv.h>
43 #include <mach/mach_host.h>
44 #include <pexpert/pexpert.h>
45 #include <sys/coalition.h>
46 #include <sys/kern_event.h>
48 #include <sys/proc_info.h>
49 #include <sys/signal.h>
50 #include <sys/signalvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysproto.h>
56 #include <vm/vm_pageout.h>
57 #include <vm/vm_protos.h>
60 #include <vm/vm_map.h>
61 #endif /* CONFIG_FREEZE */
63 #include <sys/kern_memorystatus.h>
66 /* For logging clarity */
67 static const char *jetsam_kill_cause_name
[] = {
69 "jettisoned" , /* kMemorystatusKilled */
70 "highwater" , /* kMemorystatusKilledHiwat */
71 "vnode-limit" , /* kMemorystatusKilledVnodes */
72 "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
73 "vm-thrashing" , /* kMemorystatusKilledVMThrashing */
74 "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
75 "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
76 "diagnostic" , /* kMemorystatusKilledDiagnostic */
77 "idle-exit" , /* kMemorystatusKilledIdleExit */
80 /* Does cause indicate vm or fc thrashing? */
82 is_thrashing(unsigned cause
)
85 case kMemorystatusKilledVMThrashing
:
86 case kMemorystatusKilledFCThrashing
:
93 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
94 extern void vm_thrashing_jetsam_done(void);
97 /* These are very verbose printfs(), enable with
98 * MEMORYSTATUS_DEBUG_LOG
100 #if MEMORYSTATUS_DEBUG_LOG
101 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
103 if (cond) { printf(format, ##__VA_ARGS__); } \
106 #define MEMORYSTATUS_DEBUG(cond, format, ...)
110 * Active / Inactive limit support
111 * proc list must be locked
113 * The SET_*** macros are used to initialize a limit
114 * for the first time.
116 * The CACHE_*** macros are use to cache the limit that will
117 * soon be in effect down in the ledgers.
120 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
122 (p)->p_memstat_memlimit_active = (limit); \
123 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED; \
125 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
127 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
131 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
133 (p)->p_memstat_memlimit_inactive = (limit); \
134 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED; \
136 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
138 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
142 #define CACHE_ACTIVE_LIMITS_LOCKED(p, trigger_exception) \
144 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
145 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
146 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
148 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
150 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED) { \
151 trigger_exception = FALSE; \
153 trigger_exception = TRUE; \
157 #define CACHE_INACTIVE_LIMITS_LOCKED(p, trigger_exception) \
159 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
160 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
161 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
163 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
165 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED) { \
166 trigger_exception = FALSE; \
168 trigger_exception = TRUE; \
173 /* General tunables */
175 unsigned long delta_percentage
= 5;
176 unsigned long critical_threshold_percentage
= 5;
177 unsigned long idle_offset_percentage
= 5;
178 unsigned long pressure_threshold_percentage
= 15;
179 unsigned long freeze_threshold_percentage
= 50;
181 /* General memorystatus stuff */
183 struct klist memorystatus_klist
;
184 static lck_mtx_t memorystatus_klist_mutex
;
186 static void memorystatus_klist_lock(void);
187 static void memorystatus_klist_unlock(void);
189 static uint64_t memorystatus_idle_delay_time
= 0;
192 * Memorystatus kevents
195 static int filt_memorystatusattach(struct knote
*kn
);
196 static void filt_memorystatusdetach(struct knote
*kn
);
197 static int filt_memorystatus(struct knote
*kn
, long hint
);
199 struct filterops memorystatus_filtops
= {
200 .f_attach
= filt_memorystatusattach
,
201 .f_detach
= filt_memorystatusdetach
,
202 .f_event
= filt_memorystatus
,
206 kMemorystatusNoPressure
= 0x1,
207 kMemorystatusPressure
= 0x2,
208 kMemorystatusLowSwap
= 0x4
211 /* Idle guard handling */
213 static int32_t memorystatus_scheduled_idle_demotions
= 0;
215 static thread_call_t memorystatus_idle_demotion_call
;
217 static void memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
);
218 static void memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
);
219 static void memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clean_state
);
220 static void memorystatus_reschedule_idle_demotion_locked(void);
222 static void memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
);
224 boolean_t
is_knote_registered_modify_task_pressure_bits(struct knote
*, int, task_t
, vm_pressure_level_t
, vm_pressure_level_t
);
225 void memorystatus_send_low_swap_note(void);
227 int memorystatus_wakeup
= 0;
229 unsigned int memorystatus_level
= 0;
230 unsigned int memorystatus_early_boot_level
= 0;
232 static int memorystatus_list_count
= 0;
234 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
236 typedef struct memstat_bucket
{
237 TAILQ_HEAD(, proc
) list
;
241 memstat_bucket_t memstat_bucket
[MEMSTAT_BUCKET_COUNT
];
243 uint64_t memstat_idle_demotion_deadline
= 0;
245 static unsigned int memorystatus_dirty_count
= 0;
248 SYSCTL_INT(_kern
, OID_AUTO
, max_task_pmem
, CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
, &max_task_footprint_mb
, 0, "");
249 #endif // CONFIG_JETSAM
253 memorystatus_get_level(__unused
struct proc
*p
, struct memorystatus_get_level_args
*args
, __unused
int *ret
)
255 user_addr_t level
= 0;
259 if (copyout(&memorystatus_level
, level
, sizeof(memorystatus_level
)) != 0) {
266 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
);
267 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
);
269 static void memorystatus_thread(void *param __unused
, wait_result_t wr __unused
);
275 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
);
277 static int memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
279 static int memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
);
281 static int memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
283 static boolean_t
proc_jetsam_state_is_active_locked(proc_t
);
285 int proc_get_memstat_priority(proc_t
, boolean_t
);
287 /* Kill processes exceeding their limit either under memory pressure (1), or as soon as possible (0) */
288 #define LEGACY_HIWATER 1
290 static boolean_t memorystatus_idle_snapshot
= 0;
292 static int memorystatus_highwater_enabled
= 1; /* Update the cached memlimit data. This should be removed. */
294 unsigned int memorystatus_delta
= 0;
296 static unsigned int memorystatus_available_pages_critical_base
= 0;
297 //static unsigned int memorystatus_last_foreground_pressure_pages = (unsigned int)-1;
298 static unsigned int memorystatus_available_pages_critical_idle_offset
= 0;
300 /* Jetsam Loop Detection */
301 static boolean_t memorystatus_jld_enabled
= TRUE
; /* Enables jetsam loop detection on all devices */
302 static uint32_t memorystatus_jld_eval_period_msecs
= 0; /* Init pass sets this based on device memory size */
303 static int memorystatus_jld_eval_aggressive_count
= 3; /* Raise the priority max after 'n' aggressive loops */
304 static int memorystatus_jld_eval_aggressive_priority_band_max
= 15; /* Kill aggressively up through this band */
306 #if DEVELOPMENT || DEBUG
308 * Jetsam Loop Detection tunables.
311 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_period_msecs
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_period_msecs
, 0, "");
312 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_count
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_count
, 0, "");
313 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_priority_band_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_priority_band_max
, 0, "");
314 #endif /* DEVELOPMENT || DEBUG */
316 #if DEVELOPMENT || DEBUG
317 static unsigned int memorystatus_jetsam_panic_debug
= 0;
319 static unsigned int memorystatus_jetsam_policy
= kPolicyDefault
;
320 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic
= 0;
321 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
324 static unsigned int memorystatus_thread_wasted_wakeup
= 0;
326 static uint32_t kill_under_pressure_cause
= 0;
329 * default jetsam snapshot support
331 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot
;
332 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
333 static unsigned int memorystatus_jetsam_snapshot_count
= 0;
334 static unsigned int memorystatus_jetsam_snapshot_max
= 0;
335 static uint64_t memorystatus_jetsam_snapshot_last_timestamp
= 0;
336 static uint64_t memorystatus_jetsam_snapshot_timeout
= 0;
337 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
340 * snapshot support for memstats collected at boot.
342 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot
;
344 static void memorystatus_clear_errors(void);
345 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
);
346 static uint32_t memorystatus_build_state(proc_t p
);
347 static void memorystatus_update_levels_locked(boolean_t critical_only
);
348 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
350 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
);
351 static boolean_t
memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, int32_t *priority
, uint32_t *errors
);
352 static boolean_t
memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, int aggr_count
, int32_t priority_max
, uint32_t *errors
);
354 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t *errors
);
357 static boolean_t
memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
);
358 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
);
360 /* Priority Band Sorting Routines */
361 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
);
362 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
);
363 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
);
364 static int memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
);
367 typedef int (*cmpfunc_t
)(const void *a
, const void *b
);
368 extern void qsort(void *a
, size_t n
, size_t es
, cmpfunc_t cmp
);
369 static int memstat_asc_cmp(const void *a
, const void *b
);
371 #endif /* CONFIG_JETSAM */
375 extern unsigned int vm_page_free_count
;
376 extern unsigned int vm_page_active_count
;
377 extern unsigned int vm_page_inactive_count
;
378 extern unsigned int vm_page_throttled_count
;
379 extern unsigned int vm_page_purgeable_count
;
380 extern unsigned int vm_page_wire_count
;
382 #if VM_PRESSURE_EVENTS
384 #include "vm_pressure.h"
386 extern boolean_t
memorystatus_warn_process(pid_t pid
, boolean_t critical
);
388 vm_pressure_level_t memorystatus_vm_pressure_level
= kVMPressureNormal
;
390 #if CONFIG_MEMORYSTATUS
391 unsigned int memorystatus_available_pages
= (unsigned int)-1;
392 unsigned int memorystatus_available_pages_pressure
= 0;
393 unsigned int memorystatus_available_pages_critical
= 0;
394 unsigned int memorystatus_frozen_count
= 0;
395 unsigned int memorystatus_suspended_count
= 0;
398 * We use this flag to signal if we have any HWM offenders
399 * on the system. This way we can reduce the number of wakeups
400 * of the memorystatus_thread when the system is between the
401 * "pressure" and "critical" threshold.
403 * The (re-)setting of this variable is done without any locks
404 * or synchronization simply because it is not possible (currently)
405 * to keep track of HWM offenders that drop down below their memory
406 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
407 * by allowing the unguarded modification of this variable.
409 boolean_t memorystatus_hwm_candidates
= 0;
411 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
412 #endif /* CONFIG_MEMORYSTATUS */
414 #endif /* VM_PRESSURE_EVENTS */
420 boolean_t memorystatus_freeze_enabled
= FALSE
;
421 int memorystatus_freeze_wakeup
= 0;
423 lck_grp_attr_t
*freezer_lck_grp_attr
;
424 lck_grp_t
*freezer_lck_grp
;
425 static lck_mtx_t freezer_mutex
;
427 static inline boolean_t
memorystatus_can_freeze_processes(void);
428 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
430 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
433 static unsigned int memorystatus_freeze_threshold
= 0;
435 static unsigned int memorystatus_freeze_pages_min
= 0;
436 static unsigned int memorystatus_freeze_pages_max
= 0;
438 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
440 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
443 static uint64_t memorystatus_freeze_count
= 0;
444 static uint64_t memorystatus_freeze_pageouts
= 0;
447 static throttle_interval_t throttle_intervals
[] = {
448 { 60, 8, 0, 0, { 0, 0 }, FALSE
}, /* 1 hour intermediate interval, 8x burst */
449 { 24 * 60, 1, 0, 0, { 0, 0 }, FALSE
}, /* 24 hour long interval, no burst */
452 static uint64_t memorystatus_freeze_throttle_count
= 0;
454 static unsigned int memorystatus_suspended_footprint_total
= 0;
456 extern uint64_t vm_swap_get_free_space(void);
458 static boolean_t
memorystatus_freeze_update_throttle();
460 #endif /* CONFIG_FREEZE */
464 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
466 #if DEVELOPMENT || DEBUG
471 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index
)
475 uint32_t pages_in_mb
= 0;
476 unsigned int b
= bucket_index
;
477 boolean_t traverse_all_buckets
= FALSE
;
479 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
480 traverse_all_buckets
= TRUE
;
483 traverse_all_buckets
= FALSE
;
488 * Missing from this dump is the value actually
489 * stored in the ledger... also, format could be better.
491 printf("memorystatus_debug_dump ***START***\n");
492 printf("bucket [pid] [pages/pages-mb] state [EP / RP] dirty deadline [C-limit / A-limit / IA-limit] name\n");
493 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
495 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
496 pages_in_mb
= (pages
* 4096) /1024 / 1024;
497 printf("%d [%d] [%d/%dMB] 0x%x [%d / %d] 0x%x %lld [%d%s / %d%s / %d%s] %s\n",
498 b
, p
->p_pid
, pages
, pages_in_mb
,
499 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
500 p
->p_memstat_memlimit
,
501 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
502 p
->p_memstat_memlimit_active
,
503 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
504 p
->p_memstat_memlimit_inactive
,
505 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
506 (p
->p_comm
? p
->p_comm
: "unknown"));
507 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
509 printf("memorystatus_debug_dump ***END***\n");
513 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
515 #pragma unused(oidp, arg2)
516 int bucket_index
= 0;
518 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
519 if (error
|| !req
->newptr
) {
522 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
523 if (error
|| !req
->newptr
) {
526 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
528 * All jetsam buckets will be dumped.
532 * Only a single bucket will be dumped.
537 memorystatus_debug_dump_bucket_locked(bucket_index
);
539 memorystatus_debug_dump_this_bucket
= bucket_index
;
544 * Debug aid to look at jetsam buckets and proc jetsam fields.
545 * Use this sysctl to act on a particular jetsam bucket.
546 * Writing the sysctl triggers the dump.
547 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
550 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", "");
553 /* Debug aid to aid determination of limit */
556 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
558 #pragma unused(oidp, arg2)
561 int error
, enable
= 0;
563 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
564 if (error
|| !req
->newptr
) {
568 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
569 if (error
|| !req
->newptr
) {
573 if (!(enable
== 0 || enable
== 1)) {
579 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
581 boolean_t trigger_exception
;
585 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
586 * Background limits are described via the inactive limit slots.
589 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
590 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
592 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
597 * Disabling limits does not touch the stored variants.
598 * Set the cached limit fields to system_wide defaults.
600 p
->p_memstat_memlimit
= -1;
601 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
602 trigger_exception
= TRUE
;
606 * Enforce the cached limit by writing to the ledger.
608 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, trigger_exception
);
610 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
613 memorystatus_highwater_enabled
= enable
;
621 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
623 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
625 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
626 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
627 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
628 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
630 /* Diagnostic code */
633 kJetsamDiagnosticModeNone
= 0,
634 kJetsamDiagnosticModeAll
= 1,
635 kJetsamDiagnosticModeStopAtFirstActive
= 2,
636 kJetsamDiagnosticModeCount
637 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
639 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
642 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
644 #pragma unused(arg1, arg2)
646 const char *diagnosticStrings
[] = {
647 "jetsam: diagnostic mode: resetting critical level.",
648 "jetsam: diagnostic mode: will examine all processes",
649 "jetsam: diagnostic mode: will stop at first active process"
652 int error
, val
= jetsam_diagnostic_mode
;
653 boolean_t changed
= FALSE
;
655 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
656 if (error
|| !req
->newptr
)
658 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
659 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
665 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
666 jetsam_diagnostic_mode
= val
;
668 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
670 switch (jetsam_diagnostic_mode
) {
671 case kJetsamDiagnosticModeNone
:
672 /* Already cleared */
674 case kJetsamDiagnosticModeAll
:
675 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
677 case kJetsamDiagnosticModeStopAtFirstActive
:
678 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
681 /* Already validated */
685 memorystatus_update_levels_locked(FALSE
);
692 printf("%s\n", diagnosticStrings
[val
]);
698 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
|CTLFLAG_ANYBODY
,
699 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
701 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
703 #if VM_PRESSURE_EVENTS
705 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
709 * This routine is used for targeted notifications
710 * regardless of system memory pressure.
711 * "memnote" is the current user.
715 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
717 #pragma unused(arg1, arg2)
719 int error
= 0, pid
= 0;
721 struct knote
*kn
= NULL
;
722 boolean_t found_knote
= FALSE
;
724 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
725 if (error
|| !req
->newptr
)
729 * We inspect 3 lists here for targeted notifications:
730 * - memorystatus_klist
731 * - vm_pressure_klist
732 * - vm_pressure_dormant_klist
734 * The vm_pressure_* lists are tied to the old VM_PRESSURE
735 * notification mechanism. We intend to stop using that
736 * mechanism and, in turn, get rid of the 2 lists and
737 * vm_dispatch_pressure_note_to_pid() too.
740 memorystatus_klist_lock();
742 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
743 proc_t knote_proc
= kn
->kn_kq
->kq_p
;
744 pid_t knote_pid
= knote_proc
->p_pid
;
746 if (knote_pid
== pid
) {
748 * Forcibly send this pid a "warning" memory pressure notification.
750 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
756 KNOTE(&memorystatus_klist
, 0);
759 ret
= vm_dispatch_pressure_note_to_pid(pid
, FALSE
);
762 memorystatus_klist_unlock();
767 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
768 0, 0, &sysctl_memorystatus_vm_pressure_send
, "I", "");
770 #endif /* VM_PRESSURE_EVENTS */
772 #endif /* CONFIG_JETSAM */
776 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
778 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
780 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
781 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
783 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_count
, "");
784 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
785 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_throttle_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_count
, "");
786 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
788 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
789 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
792 * Manual trigger of freeze and thaw for dev / debug kernels only.
795 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
797 #pragma unused(arg1, arg2)
801 if (memorystatus_freeze_enabled
== FALSE
) {
805 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
806 if (error
|| !req
->newptr
)
810 vm_pageout_anonymous_pages();
815 lck_mtx_lock(&freezer_mutex
);
819 uint32_t purgeable
, wired
, clean
, dirty
;
821 uint32_t max_pages
= 0;
823 if (DEFAULT_FREEZER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
825 unsigned int avail_swap_space
= 0; /* in pages. */
827 if (DEFAULT_FREEZER_IS_ACTIVE
) {
829 * Freezer backed by default pager and swap file(s).
831 avail_swap_space
= default_pager_swap_pages_free();
834 * Freezer backed by the compressor and swap file(s)
835 * while will hold compressed data.
837 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
840 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
844 * We only have the compressor without any swap.
846 max_pages
= UINT32_MAX
- 1;
849 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
855 lck_mtx_unlock(&freezer_mutex
);
859 lck_mtx_unlock(&freezer_mutex
);
863 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
864 0, 0, &sysctl_memorystatus_freeze
, "I", "");
867 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
869 #pragma unused(arg1, arg2)
874 if (memorystatus_freeze_enabled
== FALSE
) {
878 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
879 if (error
|| !req
->newptr
)
884 error
= task_thaw(p
->task
);
895 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
896 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
898 #endif /* CONFIG_FREEZE */
900 #endif /* DEVELOPMENT || DEBUG */
902 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
905 thread_t
*new_thread
);
909 * Picks the sorting routine for a given jetsam priority band.
912 * bucket_index - jetsam priority band to be sorted.
913 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
914 * Currently sort_order is only meaningful when handling
921 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
926 * Verify the jetsam priority
928 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
932 #if DEVELOPMENT || DEBUG
933 if (sort_order
== JETSAM_SORT_DEFAULT
) {
934 coal_sort_order
= COALITION_SORT_DEFAULT
;
936 coal_sort_order
= sort_order
; /* only used for testing scenarios */
940 if (sort_order
== JETSAM_SORT_DEFAULT
) {
941 coal_sort_order
= COALITION_SORT_DEFAULT
;
948 switch (bucket_index
) {
949 case JETSAM_PRIORITY_FOREGROUND
:
950 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
952 * Fall back to per process sorting when zero coalitions are found.
954 memorystatus_sort_by_largest_process_locked(bucket_index
);
958 memorystatus_sort_by_largest_process_locked(bucket_index
);
967 * Sort processes by size for a single jetsam bucket.
970 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
972 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
973 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
974 uint32_t pages
= 0, max_pages
= 0;
975 memstat_bucket_t
*current_bucket
;
977 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
981 current_bucket
= &memstat_bucket
[bucket_index
];
983 p
= TAILQ_FIRST(¤t_bucket
->list
);
986 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
991 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
992 /* traversing list until we find next largest process */
994 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
995 if (pages
> max_pages
) {
1001 if (prev_max_proc
!= max_proc
) {
1002 /* found a larger process, place it in the list */
1003 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1004 if (insert_after_proc
== NULL
) {
1005 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1007 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1009 prev_max_proc
= max_proc
;
1012 insert_after_proc
= max_proc
;
1014 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1018 #endif /* CONFIG_JETSAM */
1020 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
) {
1021 memstat_bucket_t
*current_bucket
;
1024 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1028 current_bucket
= &memstat_bucket
[*bucket_index
];
1029 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1030 if (!next_p
&& search
) {
1031 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1032 current_bucket
= &memstat_bucket
[*bucket_index
];
1033 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1040 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
) {
1041 memstat_bucket_t
*current_bucket
;
1044 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1048 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1049 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1050 current_bucket
= &memstat_bucket
[*bucket_index
];
1051 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1057 __private_extern__
void
1058 memorystatus_init(void)
1060 thread_t thread
= THREAD_NULL
;
1061 kern_return_t result
;
1065 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1066 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1069 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_idle_delay_time
);
1072 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1073 TAILQ_INIT(&memstat_bucket
[i
].list
);
1074 memstat_bucket
[i
].count
= 0;
1077 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1079 /* Apply overrides */
1080 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1081 assert(delta_percentage
< 100);
1082 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1083 assert(critical_threshold_percentage
< 100);
1084 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1085 assert(idle_offset_percentage
< 100);
1086 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1087 assert(pressure_threshold_percentage
< 100);
1088 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1089 assert(freeze_threshold_percentage
< 100);
1092 /* device tree can request to take snapshots for idle-exit kills by default */
1093 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1095 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1096 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1097 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1099 memorystatus_jetsam_snapshot_max
= maxproc
;
1100 memorystatus_jetsam_snapshot
=
1101 (memorystatus_jetsam_snapshot_t
*)kalloc(sizeof(memorystatus_jetsam_snapshot_t
) +
1102 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
1103 if (!memorystatus_jetsam_snapshot
) {
1104 panic("Could not allocate memorystatus_jetsam_snapshot");
1107 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
1109 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
1111 /* No contention at this point */
1112 memorystatus_update_levels_locked(FALSE
);
1114 /* Jetsam Loop Detection */
1115 if (max_mem
<= (512 * 1024 * 1024)) {
1116 /* 512 MB devices */
1117 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
1119 /* 1GB and larger devices */
1120 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
1125 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1128 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &thread
);
1129 if (result
== KERN_SUCCESS
) {
1130 thread_deallocate(thread
);
1132 panic("Could not create memorystatus_thread");
1136 /* Centralised for the purposes of allowing panic-on-jetsam */
1138 vm_wake_compactor_swapper(void);
1141 * The jetsam no frills kill call
1142 * Return: 0 on success
1143 * error code on failure (EINVAL...)
1146 jetsam_do_kill(proc_t p
, int jetsam_flags
) {
1148 error
= exit1_internal(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
);
1153 * Wrapper for processes exiting with memorystatus details
1156 memorystatus_do_kill(proc_t p
, uint32_t cause
) {
1159 __unused pid_t victim_pid
= p
->p_pid
;
1161 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
1162 victim_pid
, cause
, vm_page_free_count
, 0, 0);
1164 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1165 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
1166 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
1169 #pragma unused(cause)
1171 int jetsam_flags
= P_LTERM_JETSAM
;
1173 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
1174 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
1175 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
1176 case kMemorystatusKilledVMThrashing
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
1177 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
1178 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
1179 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
1181 error
= jetsam_do_kill(p
, jetsam_flags
);
1183 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
1184 victim_pid
, cause
, vm_page_free_count
, error
, 0);
1186 vm_wake_compactor_swapper();
1188 return (error
== 0);
1196 memorystatus_check_levels_locked(void) {
1199 memorystatus_update_levels_locked(TRUE
);
1204 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
1207 uint64_t current_time
;
1208 memstat_bucket_t
*demotion_bucket
;
1210 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1212 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1214 current_time
= mach_absolute_time();
1218 demotion_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE_DEFERRED
];
1219 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1222 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
1224 assert(p
->p_memstat_idledeadline
);
1225 assert(p
->p_memstat_dirty
& P_DIRTY_DEFER_IN_PROGRESS
);
1226 assert((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
);
1228 if (current_time
>= p
->p_memstat_idledeadline
) {
1229 #if DEBUG || DEVELOPMENT
1230 if (!(p
->p_memstat_dirty
& P_DIRTY_MARKED
)) {
1231 printf("memorystatus_perform_idle_demotion: moving process %d [%s] to idle band, but never dirtied (0x%x)!\n",
1232 p
->p_pid
, (p
->p_comm
? p
->p_comm
: "(unknown)"), p
->p_memstat_dirty
);
1235 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1236 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false);
1238 // The prior process has moved out of the demotion bucket, so grab the new head and continue
1239 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1243 // No further candidates
1247 memorystatus_reschedule_idle_demotion_locked();
1251 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
1255 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
1257 boolean_t present_in_deferred_bucket
= FALSE
;
1259 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1260 present_in_deferred_bucket
= TRUE
;
1263 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",
1264 p
->p_pid
, p
->p_memstat_dirty
, set_state
, memorystatus_scheduled_idle_demotions
);
1266 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
1269 assert(p
->p_memstat_idledeadline
== 0);
1270 p
->p_memstat_dirty
|= P_DIRTY_DEFER_IN_PROGRESS
;
1271 p
->p_memstat_idledeadline
= mach_absolute_time() + memorystatus_idle_delay_time
;
1274 assert(p
->p_memstat_idledeadline
);
1276 if (present_in_deferred_bucket
== FALSE
) {
1277 memorystatus_scheduled_idle_demotions
++;
1282 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
1284 boolean_t present_in_deferred_bucket
= FALSE
;
1286 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1287 present_in_deferred_bucket
= TRUE
;
1288 assert(p
->p_memstat_idledeadline
);
1291 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1292 p
->p_pid
, clear_state
, memorystatus_scheduled_idle_demotions
);
1296 p
->p_memstat_idledeadline
= 0;
1297 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER_IN_PROGRESS
;
1300 if (present_in_deferred_bucket
== TRUE
) {
1301 memorystatus_scheduled_idle_demotions
--;
1304 assert(memorystatus_scheduled_idle_demotions
>= 0);
1308 memorystatus_reschedule_idle_demotion_locked(void) {
1309 if (0 == memorystatus_scheduled_idle_demotions
) {
1310 if (memstat_idle_demotion_deadline
) {
1311 /* Transitioned 1->0, so cancel next call */
1312 thread_call_cancel(memorystatus_idle_demotion_call
);
1313 memstat_idle_demotion_deadline
= 0;
1316 memstat_bucket_t
*demotion_bucket
;
1318 demotion_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE_DEFERRED
];
1319 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1321 assert(p
&& p
->p_memstat_idledeadline
);
1323 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
){
1324 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
1325 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
1335 memorystatus_add(proc_t p
, boolean_t locked
)
1337 memstat_bucket_t
*bucket
;
1339 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
1345 /* Processes marked internal do not have priority tracked */
1346 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1350 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1352 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1353 assert(bucket
->count
== memorystatus_scheduled_idle_demotions
);
1356 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
1359 memorystatus_list_count
++;
1361 memorystatus_check_levels_locked();
1373 * Moves a process from one jetsam bucket to another.
1374 * which changes the LRU position of the process.
1376 * Monitors transition between buckets and if necessary
1377 * will update cached memory limits accordingly.
1380 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
)
1382 memstat_bucket_t
*old_bucket
, *new_bucket
;
1384 assert(priority
< MEMSTAT_BUCKET_COUNT
);
1386 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
1387 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
1391 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting pid %d to priority %d, inserting at %s\n",
1392 p
->p_pid
, priority
, head_insert
? "head" : "tail");
1394 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1395 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1396 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions
+ 1));
1399 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
1400 old_bucket
->count
--;
1402 new_bucket
= &memstat_bucket
[priority
];
1404 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
1406 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
1407 new_bucket
->count
++;
1410 if (memorystatus_highwater_enabled
) {
1411 boolean_t trigger_exception
;
1414 * If cached limit data is updated, then the limits
1415 * will be enforced by writing to the ledgers.
1417 boolean_t ledger_update_needed
= TRUE
;
1420 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
1421 * Background limits are described via the inactive limit slots.
1423 * Here, we must update the cached memory limit if the task
1424 * is transitioning between:
1425 * active <--> inactive
1428 * dirty <--> clean is ignored
1430 * We bypass processes that have opted into dirty tracking because
1431 * a move between buckets does not imply a transition between the
1432 * dirty <--> clean state.
1433 * Setting limits on processes opted into dirty tracking is handled
1434 * in memorystatus_dirty_set() where the transition is very clear.
1437 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
1439 ledger_update_needed
= FALSE
;
1441 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
1443 * inactive --> active
1445 * assign active state
1447 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
1449 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
1451 * active --> inactive
1453 * assign inactive state
1455 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
1458 * The transition between jetsam priority buckets apparently did
1459 * not affect active/inactive state.
1460 * This is not unusual... especially during startup when
1461 * processes are getting established in their respective bands.
1463 ledger_update_needed
= FALSE
;
1467 * Enforce the new limits by writing to the ledger
1469 if (ledger_update_needed
) {
1470 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, trigger_exception
);
1472 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
1473 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
1474 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
1475 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
1479 #endif /* CONFIG_JETSAM */
1481 p
->p_memstat_effectivepriority
= priority
;
1483 memorystatus_check_levels_locked();
1488 * Description: Update the jetsam priority and memory limit attributes for a given process.
1491 * p init this process's jetsam information.
1492 * priority The jetsam priority band
1493 * user_data user specific data, unused by the kernel
1494 * effective guards against race if process's update already occurred
1495 * update_memlimit When true we know this is the init step via the posix_spawn path.
1497 * memlimit_active Value in megabytes; The monitored footprint level while the
1498 * process is active. Exceeding it may result in termination
1499 * based on it's associated fatal flag.
1501 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
1502 * this describes whether or not it should be immediately fatal.
1504 * memlimit_inactive Value in megabytes; The monitored footprint level while the
1505 * process is inactive. Exceeding it may result in termination
1506 * based on it's associated fatal flag.
1508 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
1509 * this describes whether or not it should be immediatly fatal.
1511 * memlimit_background This process has a high-water-mark while in the background.
1512 * No longer meaningful. Background limits are described via
1513 * the inactive slots. Flag is ignored.
1516 * Returns: 0 Success
1521 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
1522 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
1523 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
,
1524 __unused boolean_t memlimit_background
)
1527 boolean_t head_insert
= false;
1530 #pragma unused(update_memlimit, memlimit_active, memlimit_inactive)
1531 #pragma unused(memlimit_active_is_fatal, memlimit_inactive_is_fatal)
1532 #endif /* !CONFIG_JETSAM */
1534 MEMORYSTATUS_DEBUG(1, "memorystatus_update: changing pid %d: priority %d, user_data 0x%llx\n", p
->p_pid
, priority
, user_data
);
1536 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
1538 if (priority
== -1) {
1539 /* Use as shorthand for default priority */
1540 priority
= JETSAM_PRIORITY_DEFAULT
;
1541 } else if (priority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1542 /* JETSAM_PRIORITY_IDLE_DEFERRED is reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
1543 priority
= JETSAM_PRIORITY_IDLE
;
1544 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
1545 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
1546 priority
= JETSAM_PRIORITY_IDLE
;
1548 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
1556 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
1558 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
1561 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
1565 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
1567 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
1574 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
1575 p
->p_memstat_userdata
= user_data
;
1576 p
->p_memstat_requestedpriority
= priority
;
1579 if (update_memlimit
) {
1580 boolean_t trigger_exception
;
1583 * Posix_spawn'd processes come through this path to instantiate ledger limits.
1584 * Forked processes do not come through this path, so no ledger limits exist.
1585 * (That's why forked processes can consume unlimited memory.)
1588 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
1589 p
->p_pid
, priority
, p
->p_memstat_dirty
,
1590 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
1591 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
1593 if (memlimit_background
) {
1596 * With 2-level HWM support, we no longer honor P_MEMSTAT_MEMLIMIT_BACKGROUND.
1597 * Background limits are described via the inactive limit slots.
1600 // p->p_memstat_state |= P_MEMSTAT_MEMLIMIT_BACKGROUND;
1602 #if DEVELOPMENT || DEBUG
1603 printf("memorystatus_update: WARNING %s[%d] set unused flag P_MEMSTAT_MEMLIMIT_BACKGROUND [A==%dMB %s] [IA==%dMB %s]\n",
1604 (p
->p_comm
? p
->p_comm
: "unknown"), p
->p_pid
,
1605 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
1606 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
1607 #endif /* DEVELOPMENT || DEBUG */
1610 if (memlimit_active
<= 0) {
1612 * This process will have a system_wide task limit when active.
1613 * System_wide task limit is always fatal.
1614 * It's quite common to see non-fatal flag passed in here.
1615 * It's not an error, we just ignore it.
1619 * For backward compatibility with some unexplained launchd behavior,
1620 * we allow a zero sized limit. But we still enforce system_wide limit
1621 * when written to the ledgers.
1624 if (memlimit_active
< 0) {
1625 memlimit_active
= -1; /* enforces system_wide task limit */
1627 memlimit_active_is_fatal
= TRUE
;
1630 if (memlimit_inactive
<= 0) {
1632 * This process will have a system_wide task limit when inactive.
1633 * System_wide task limit is always fatal.
1636 memlimit_inactive
= -1;
1637 memlimit_inactive_is_fatal
= TRUE
;
1641 * Initialize the active limit variants for this process.
1643 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
1646 * Initialize the inactive limit variants for this process.
1648 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
1651 * Initialize the cached limits for target process.
1652 * When the target process is dirty tracked, it's typically
1653 * in a clean state. Non dirty tracked processes are
1654 * typically active (Foreground or above).
1655 * But just in case, we don't make assumptions...
1658 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
1659 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
1661 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
1665 * Enforce the cached limit by writing to the ledger.
1667 if (memorystatus_highwater_enabled
) {
1669 assert(trigger_exception
== TRUE
);
1670 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, trigger_exception
);
1672 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
1673 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
1674 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
1675 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
1678 #endif /* CONFIG_JETSAM */
1681 * We can't add to the JETSAM_PRIORITY_IDLE_DEFERRED bucket here.
1682 * But, we could be removing it from the bucket.
1683 * Check and take appropriate steps if so.
1686 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1688 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1691 memorystatus_update_priority_locked(p
, priority
, head_insert
);
1697 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
1703 memorystatus_remove(proc_t p
, boolean_t locked
)
1706 memstat_bucket_t
*bucket
;
1708 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
1714 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
1716 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1717 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1718 assert(bucket
->count
== memorystatus_scheduled_idle_demotions
);
1721 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
1724 memorystatus_list_count
--;
1726 /* If awaiting demotion to the idle band, clean up */
1727 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
1728 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1729 memorystatus_reschedule_idle_demotion_locked();
1732 memorystatus_check_levels_locked();
1735 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
1736 memorystatus_frozen_count
--;
1739 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
1740 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
1741 memorystatus_suspended_count
--;
1759 * Validate dirty tracking flags with process state.
1767 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
) {
1768 /* See that the process isn't marked for termination */
1769 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
1773 /* Idle exit requires that process be tracked */
1774 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
1775 !(pcontrol
& PROC_DIRTY_TRACK
)) {
1779 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
1780 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
1781 !(pcontrol
& PROC_DIRTY_TRACK
)) {
1785 /* Deferral is only relevant if idle exit is specified */
1786 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
1787 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
1795 memorystatus_update_idle_priority_locked(proc_t p
) {
1798 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
1800 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
1801 priority
= (p
->p_memstat_dirty
& P_DIRTY_DEFER_IN_PROGRESS
) ? JETSAM_PRIORITY_IDLE_DEFERRED
: JETSAM_PRIORITY_IDLE
;
1803 priority
= p
->p_memstat_requestedpriority
;
1806 if (priority
!= p
->p_memstat_effectivepriority
) {
1807 memorystatus_update_priority_locked(p
, priority
, false);
1812 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
1813 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
1814 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
1815 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
1817 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
1818 * memorystatus_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
1819 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
1820 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
1821 * band. The deferral can be cleared early by clearing the appropriate flag.
1823 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
1824 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
1825 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
1829 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
) {
1830 unsigned int old_dirty
;
1831 boolean_t reschedule
= FALSE
;
1832 boolean_t already_deferred
= FALSE
;
1833 boolean_t defer_now
= FALSE
;
1836 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
1837 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
1841 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
1843 * Process is on its way out.
1849 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1854 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
1859 old_dirty
= p
->p_memstat_dirty
;
1861 /* These bits are cumulative, as per <rdar://problem/11159924> */
1862 if (pcontrol
& PROC_DIRTY_TRACK
) {
1863 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
1866 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
1867 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
1870 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
1871 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
1874 if (old_dirty
& P_DIRTY_DEFER_IN_PROGRESS
) {
1875 already_deferred
= TRUE
;
1878 /* This can be set and cleared exactly once. */
1879 if (pcontrol
& PROC_DIRTY_DEFER
) {
1881 if ( !(old_dirty
& P_DIRTY_DEFER
)) {
1882 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
1888 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
1889 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
1890 defer_now
? "Y" : "N",
1891 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
1894 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
1895 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
1896 if (((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) &&
1897 defer_now
&& !already_deferred
) {
1900 * Request to defer a clean process that's idle-exit enabled
1901 * and not already in the jetsam deferred band.
1903 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
1906 } else if (!defer_now
&& already_deferred
) {
1909 * Either the process is no longer idle-exit enabled OR
1910 * there's a request to cancel a currently active deferral.
1912 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1918 * We are trying to operate on a dirty process. Dirty processes have to
1919 * be removed from the deferred band. The question is do we reset the
1920 * deferred state or not?
1922 * This could be a legal request like:
1923 * - this process had opted into the JETSAM_DEFERRED band
1924 * - but it's now dirty and requests to opt out.
1925 * In this case, we remove the process from the band and reset its
1926 * state too. It'll opt back in properly when needed.
1928 * OR, this request could be a user-space bug. E.g.:
1929 * - this process had opted into the JETSAM_DEFERRED band when clean
1930 * - and, then issues another request to again put it into the band except
1931 * this time the process is dirty.
1932 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
1933 * the deferred band with its state intact. So our request below is no-op.
1934 * But we do it here anyways for coverage.
1936 * memorystatus_update_idle_priority_locked()
1937 * single-mindedly treats a dirty process as "cannot be in the deferred band".
1940 if (!defer_now
&& already_deferred
) {
1941 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1944 memorystatus_invalidate_idle_demotion_locked(p
, FALSE
);
1949 memorystatus_update_idle_priority_locked(p
);
1952 memorystatus_reschedule_idle_demotion_locked();
1964 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
) {
1966 boolean_t kill
= false;
1967 boolean_t reschedule
= FALSE
;
1968 boolean_t was_dirty
= FALSE
;
1969 boolean_t now_dirty
= FALSE
;
1971 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
1973 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
1977 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
1979 * Process is on its way out.
1985 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1990 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
1993 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
1994 /* Dirty tracking not enabled */
1996 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
1998 * Process is set to be terminated and we're attempting to mark it dirty.
1999 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2003 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
2004 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
2005 /* Mark the process as having been dirtied at some point */
2006 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
2007 memorystatus_dirty_count
++;
2009 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
2010 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
2011 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2012 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2014 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2015 /* Kill previously terminated processes if set clean */
2018 p
->p_memstat_dirty
&= ~flag
;
2019 memorystatus_dirty_count
--;
2031 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2034 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
2035 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
2037 /* Manage idle exit deferral, if applied */
2038 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_DEFER_IN_PROGRESS
)) ==
2039 (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_DEFER_IN_PROGRESS
)) {
2042 * P_DIRTY_DEFER_IN_PROGRESS means the process is in the deferred band OR it might be heading back
2043 * there once it's clean again and has some protection window left.
2046 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2048 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2050 * The process will move from the deferred band to its higher requested
2051 * jetsam band. But we don't clear its state i.e. we want to remember that
2052 * this process was part of the "deferred" band and will return to it.
2054 * This way, we don't let it age beyond the protection
2055 * window when it returns to "clean". All the while giving
2056 * it a chance to perform its work while "dirty".
2059 memorystatus_invalidate_idle_demotion_locked(p
, FALSE
);
2064 * Process is back from "dirty" to "clean".
2066 * Is its timer up OR does it still have some protection
2070 if (mach_absolute_time() >= p
->p_memstat_idledeadline
) {
2072 * The process' deadline has expired. It currently
2073 * does not reside in the DEFERRED bucket.
2075 * It's on its way to the JETSAM_PRIORITY_IDLE
2076 * bucket via memorystatus_update_idle_priority_locked()
2079 * So all we need to do is reset all the state on the
2080 * process that's related to the DEFERRED bucket i.e.
2081 * the DIRTY_DEFER_IN_PROGRESS flag and the timer deadline.
2085 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2089 * It still has some protection window left and so
2090 * we just re-arm the timer without modifying any
2091 * state on the process.
2093 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
2099 memorystatus_update_idle_priority_locked(p
);
2102 if (memorystatus_highwater_enabled
) {
2103 boolean_t trigger_exception
;
2105 * We are in this path because this process transitioned between
2106 * dirty <--> clean state. Update the cached memory limits.
2109 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2113 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2118 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2122 * Enforce the new limits by writing to the ledger.
2124 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
2125 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
2126 * We aren't traversing the jetsam bucket list here, so we should be safe.
2127 * See rdar://21394491.
2130 if (proc_ref_locked(p
) == p
) {
2132 if (p
->p_memstat_memlimit
> 0) {
2133 ledger_limit
= p
->p_memstat_memlimit
;
2138 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, trigger_exception
);
2140 proc_rele_locked(p
);
2142 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
2143 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2144 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
2145 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2149 #endif /* CONFIG_JETSAM */
2151 /* If the deferral state changed, reschedule the demotion timer */
2153 memorystatus_reschedule_idle_demotion_locked();
2158 if (proc_ref_locked(p
) == p
) {
2160 psignal(p
, SIGKILL
);
2162 proc_rele_locked(p
);
2173 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
) {
2177 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2179 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
2183 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2185 * Process is on its way out.
2191 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2196 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2197 /* Dirty tracking not enabled */
2202 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
)) == 0) {
2207 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2208 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
2211 /* This can be set and cleared exactly once. */
2212 if (pcontrol
& PROC_DIRTY_DEFER
) {
2214 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
2216 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER
;
2218 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2219 memorystatus_update_idle_priority_locked(p
);
2220 memorystatus_reschedule_idle_demotion_locked();
2232 memorystatus_dirty_get(proc_t p
) {
2237 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2238 ret
|= PROC_DIRTY_TRACKED
;
2239 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
2240 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
2242 if (p
->p_memstat_dirty
& P_DIRTY
) {
2243 ret
|= PROC_DIRTY_IS_DIRTY
;
2245 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
2246 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
2256 memorystatus_on_terminate(proc_t p
) {
2261 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2263 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
2264 /* Clean; mark as terminated and issue SIGKILL */
2267 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
2277 memorystatus_on_suspend(proc_t p
)
2281 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
2285 p
->p_memstat_suspendedfootprint
= pages
;
2286 memorystatus_suspended_footprint_total
+= pages
;
2287 memorystatus_suspended_count
++;
2289 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
2294 memorystatus_on_resume(proc_t p
)
2304 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
2306 memorystatus_frozen_count
--;
2307 p
->p_memstat_state
|= P_MEMSTAT_PRIOR_THAW
;
2310 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
2311 memorystatus_suspended_count
--;
2316 p
->p_memstat_state
&= ~(P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
);
2322 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
2323 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
2329 memorystatus_on_inactivity(proc_t p
)
2333 /* Wake the freeze thread */
2334 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
2339 memorystatus_build_state(proc_t p
) {
2340 uint32_t snapshot_state
= 0;
2343 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
2344 snapshot_state
|= kMemorystatusSuspended
;
2346 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
2347 snapshot_state
|= kMemorystatusFrozen
;
2349 if (p
->p_memstat_state
& P_MEMSTAT_PRIOR_THAW
) {
2350 snapshot_state
|= kMemorystatusWasThawed
;
2354 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2355 snapshot_state
|= kMemorystatusTracked
;
2357 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2358 snapshot_state
|= kMemorystatusSupportsIdleExit
;
2360 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2361 snapshot_state
|= kMemorystatusDirty
;
2364 return snapshot_state
;
2370 kill_idle_exit_proc(void)
2372 proc_t p
, victim_p
= PROC_NULL
;
2373 uint64_t current_time
;
2374 boolean_t killed
= FALSE
;
2377 /* Pick next idle exit victim. */
2378 current_time
= mach_absolute_time();
2382 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
2384 /* No need to look beyond the idle band */
2385 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
2389 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
|P_DIRTY_IS_DIRTY
|P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
2390 if (current_time
>= p
->p_memstat_idledeadline
) {
2391 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2392 victim_p
= proc_ref_locked(p
);
2397 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
2403 printf("memorystatus_thread: idle exiting pid %d [%s]\n", victim_p
->p_pid
, (victim_p
->p_comm
? victim_p
->p_comm
: "(unknown)"));
2404 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
);
2405 proc_rele(victim_p
);
2414 memorystatus_thread_wake(void) {
2415 thread_wakeup((event_t
)&memorystatus_wakeup
);
2417 #endif /* CONFIG_JETSAM */
2419 extern void vm_pressure_response(void);
2422 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
2425 assert_wait_timeout(&memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, 1000 * NSEC_PER_USEC
);
2427 assert_wait(&memorystatus_wakeup
, THREAD_UNINT
);
2430 return thread_block(continuation
);
2434 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
2436 static boolean_t is_vm_privileged
= FALSE
;
2439 boolean_t post_snapshot
= FALSE
;
2440 uint32_t errors
= 0;
2441 uint32_t hwm_kill
= 0;
2442 boolean_t sort_flag
= TRUE
;
2444 /* Jetsam Loop Detection - locals */
2445 memstat_bucket_t
*bucket
;
2446 int jld_bucket_count
= 0;
2447 struct timeval jld_now_tstamp
= {0,0};
2448 uint64_t jld_now_msecs
= 0;
2450 /* Jetsam Loop Detection - statics */
2451 static uint64_t jld_timestamp_msecs
= 0;
2452 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
2453 static int jld_idle_kills
= 0; /* Number of procs killed during eval period */
2454 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
2455 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
2458 if (is_vm_privileged
== FALSE
) {
2460 * It's the first time the thread has run, so just mark the thread as privileged and block.
2461 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
2463 thread_wire(host_priv_self(), current_thread(), TRUE
);
2464 is_vm_privileged
= TRUE
;
2466 if (vm_restricted_to_single_processor
== TRUE
)
2467 thread_vm_bind_group_add();
2469 memorystatus_thread_block(0, memorystatus_thread
);
2474 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
2475 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
,0);
2478 * Jetsam aware version.
2480 * The VM pressure notification thread is working it's way through clients in parallel.
2482 * So, while the pressure notification thread is targeting processes in order of
2483 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
2484 * any processes that have exceeded their highwater mark.
2486 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
2487 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
2489 while (is_thrashing(kill_under_pressure_cause
) ||
2490 memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
2495 if (kill_under_pressure_cause
) {
2496 cause
= kill_under_pressure_cause
;
2498 cause
= kMemorystatusKilledVMPageShortage
;
2503 killed
= memorystatus_kill_hiwat_proc(&errors
);
2506 post_snapshot
= TRUE
;
2509 memorystatus_hwm_candidates
= FALSE
;
2512 /* No highwater processes to kill. Continue or stop for now? */
2513 if (!is_thrashing(kill_under_pressure_cause
) &&
2514 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
2516 * We are _not_ out of pressure but we are above the critical threshold and there's:
2517 * - no compressor thrashing
2518 * - no more HWM processes left.
2519 * For now, don't kill any other processes.
2522 if (hwm_kill
== 0) {
2523 memorystatus_thread_wasted_wakeup
++;
2529 if (memorystatus_jld_enabled
== TRUE
) {
2532 * Jetsam Loop Detection: attempt to detect
2533 * rapid daemon relaunches in the lower bands.
2536 microuptime(&jld_now_tstamp
);
2539 * Ignore usecs in this calculation.
2540 * msecs granularity is close enough.
2542 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
2545 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
2546 jld_bucket_count
= bucket
->count
;
2547 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE_DEFERRED
];
2548 jld_bucket_count
+= bucket
->count
;
2552 * memorystatus_jld_eval_period_msecs is a tunable
2553 * memorystatus_jld_eval_aggressive_count is a tunable
2554 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
2556 if ( (jld_bucket_count
== 0) ||
2557 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
2560 * Refresh evaluation parameters
2562 jld_timestamp_msecs
= jld_now_msecs
;
2563 jld_idle_kill_candidates
= jld_bucket_count
;
2565 jld_eval_aggressive_count
= 0;
2566 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
2569 if (jld_idle_kills
> jld_idle_kill_candidates
) {
2570 jld_eval_aggressive_count
++;
2571 if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
2573 * Bump up the jetsam priority limit (eg: the bucket index)
2574 * Enforce bucket index sanity.
2576 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
2577 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
2579 * Do nothing. Stick with the default level.
2582 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
2586 killed
= memorystatus_kill_top_process_aggressive(
2588 kMemorystatusKilledVMThrashing
,
2589 jld_eval_aggressive_count
,
2590 jld_priority_band_max
,
2595 /* Always generate logs after aggressive kill */
2596 post_snapshot
= TRUE
;
2603 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, &priority
, &errors
);
2608 * Don't generate logs for steady-state idle-exit kills,
2609 * unless it is overridden for debug or by the device
2612 if ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
) {
2613 post_snapshot
= TRUE
;
2616 /* Jetsam Loop Detection */
2617 if (memorystatus_jld_enabled
== TRUE
) {
2618 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== JETSAM_PRIORITY_IDLE_DEFERRED
)) {
2622 * We've reached into bands beyond idle deferred.
2623 * We make no attempt to monitor them
2630 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
2631 /* Under pressure and unable to kill a process - panic */
2632 panic("memorystatus_jetsam_thread: no victim! available pages:%d\n", memorystatus_available_pages
);
2638 * We do not want to over-kill when thrashing has been detected.
2639 * To avoid that, we reset the flag here and notify the
2642 if (is_thrashing(kill_under_pressure_cause
)) {
2643 kill_under_pressure_cause
= 0;
2644 vm_thrashing_jetsam_done();
2648 kill_under_pressure_cause
= 0;
2651 memorystatus_clear_errors();
2654 #if VM_PRESSURE_EVENTS
2656 * LD: We used to target the foreground process first and foremost here.
2657 * Now, we target all processes, starting from the non-suspended, background
2658 * processes first. We will target foreground too.
2660 * memorystatus_update_vm_pressure(TRUE);
2662 //vm_pressure_response();
2665 if (post_snapshot
) {
2666 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
2667 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
2668 uint64_t timestamp_now
= mach_absolute_time();
2669 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
2670 if (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
2671 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
) {
2672 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
2675 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
2681 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
2682 memorystatus_available_pages
, 0, 0, 0, 0);
2684 #else /* CONFIG_JETSAM */
2687 * Jetsam not enabled
2690 #endif /* CONFIG_JETSAM */
2692 memorystatus_thread_block(0, memorystatus_thread
);
2698 * when an idle-exitable proc was killed
2700 * when there are no more idle-exitable procs found
2701 * when the attempt to kill an idle-exitable proc failed
2703 boolean_t
memorystatus_idle_exit_from_VM(void) {
2704 return(kill_idle_exit_proc());
2706 #endif /* !CONFIG_JETSAM */
2711 * Callback invoked when allowable physical memory footprint exceeded
2712 * (dirty pages + IOKit mappings)
2714 * This is invoked for both advisory, non-fatal per-task high watermarks,
2715 * as well as the fatal task memory limits.
2718 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, const int max_footprint_mb
)
2720 boolean_t is_active
;
2723 proc_t p
= current_proc();
2727 is_active
= proc_jetsam_state_is_active_locked(p
);
2728 is_fatal
= (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
);
2730 if (warning
== FALSE
) {
2732 * We only want the EXC_RESOURCE to trigger once per lifetime
2733 * of the active/inactive limit state. So, here, we detect the
2734 * active/inactive state of the process and mark the
2735 * state as exception has been triggered.
2737 if (is_active
== TRUE
) {
2739 * turn off exceptions for active state
2741 p
->p_memstat_state
|= P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED
;
2744 * turn off exceptions for inactive state
2746 p
->p_memstat_state
|= P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED
;
2750 * Soft memory limit is a non-fatal high-water-mark
2751 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
2753 printf("process %d (%s) exceeded physical memory footprint, the %s%sMemoryLimit of %d MB\n",
2754 p
->p_pid
, p
->p_comm
, (is_active
? "Active" : "Inactive"),
2755 (is_fatal
? "Hard" : "Soft"), max_footprint_mb
);
2761 #if VM_PRESSURE_EVENTS
2762 if (warning
== TRUE
) {
2763 if (memorystatus_warn_process(p
->p_pid
, TRUE
/* critical? */) != TRUE
) {
2764 /* Print warning, since it's possible that task has not registered for pressure notifications */
2765 printf("task_exceeded_footprint: failed to warn the current task (exiting, or no handler registered?).\n");
2769 #endif /* VM_PRESSURE_EVENTS */
2773 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
2774 * has violated either the system-wide per-task memory limit OR its own task limit.
2776 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
) != TRUE
) {
2777 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
2781 * HWM offender exists. Done without locks or synchronization.
2782 * See comment near its declaration for more details.
2784 memorystatus_hwm_candidates
= TRUE
;
2789 * Toggle the P_MEMSTAT_TERMINATED state.
2790 * Takes the proc_list_lock.
2793 proc_memstat_terminated(proc_t p
, boolean_t set
)
2795 #if DEVELOPMENT || DEBUG
2799 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
2801 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
2806 #pragma unused(p, set)
2810 #endif /* DEVELOPMENT || DEBUG */
2815 * This is invoked when cpulimits have been exceeded while in fatal mode.
2816 * The jetsam_flags do not apply as those are for memory related kills.
2817 * We call this routine so that the offending process is killed with
2818 * a non-zero exit status.
2821 jetsam_on_ledger_cpulimit_exceeded(void)
2824 int jetsam_flags
= 0; /* make it obvious */
2825 proc_t p
= current_proc();
2827 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
2828 p
->p_pid
, (p
->p_comm
? p
->p_comm
: "(unknown)"));
2830 retval
= jetsam_do_kill(p
, jetsam_flags
);
2833 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
2838 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
2843 *footprint
= (uint32_t)(get_task_phys_footprint(task
) / PAGE_SIZE_64
);
2844 if (max_footprint
) {
2845 *max_footprint
= (uint32_t)(get_task_phys_footprint_max(task
) / PAGE_SIZE_64
);
2847 if (max_footprint_lifetime
) {
2848 *max_footprint_lifetime
= (uint32_t)(get_task_resident_max(task
) / PAGE_SIZE_64
);
2850 if (purgeable_pages
) {
2851 *purgeable_pages
= (uint32_t)(get_task_purgeable_size(task
) / PAGE_SIZE_64
);
2856 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
)
2860 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
2861 if (memorystatus_jetsam_snapshot_list
[i
].pid
== p
->p_pid
) {
2862 /* Update if the priority has changed since the snapshot was taken */
2863 if (memorystatus_jetsam_snapshot_list
[i
].priority
!= p
->p_memstat_effectivepriority
) {
2864 memorystatus_jetsam_snapshot_list
[i
].priority
= p
->p_memstat_effectivepriority
;
2865 strlcpy(memorystatus_jetsam_snapshot_list
[i
].name
, p
->p_comm
, MAXCOMLEN
+1);
2866 memorystatus_jetsam_snapshot_list
[i
].state
= memorystatus_build_state(p
);
2867 memorystatus_jetsam_snapshot_list
[i
].user_data
= p
->p_memstat_userdata
;
2868 memorystatus_jetsam_snapshot_list
[i
].fds
= p
->p_fd
->fd_nfiles
;
2870 memorystatus_jetsam_snapshot_list
[i
].killed
= kill_cause
;
2876 void memorystatus_pages_update(unsigned int pages_avail
)
2878 memorystatus_available_pages
= pages_avail
;
2880 #if VM_PRESSURE_EVENTS
2882 * Since memorystatus_available_pages changes, we should
2883 * re-evaluate the pressure levels on the system and
2884 * check if we need to wake the pressure thread.
2885 * We also update memorystatus_level in that routine.
2887 vm_pressure_response();
2889 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
2891 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
2892 memorystatus_thread_wake();
2895 #else /* VM_PRESSURE_EVENTS */
2897 boolean_t critical
, delta
;
2899 if (!memorystatus_delta
) {
2903 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
2904 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
2905 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
2907 if (critical
|| delta
) {
2908 memorystatus_level
= memorystatus_available_pages
* 100 / atop_64(max_mem
);
2909 memorystatus_thread_wake();
2911 #endif /* VM_PRESSURE_EVENTS */
2915 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
)
2918 clock_usec_t tv_usec
;
2920 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
2922 entry
->pid
= p
->p_pid
;
2923 strlcpy(&entry
->name
[0], p
->p_comm
, MAXCOMLEN
+1);
2924 entry
->priority
= p
->p_memstat_effectivepriority
;
2925 memorystatus_get_task_page_counts(p
->task
, &entry
->pages
, &entry
->max_pages
, &entry
->max_pages_lifetime
, &entry
->purgeable_pages
);
2926 entry
->state
= memorystatus_build_state(p
);
2927 entry
->user_data
= p
->p_memstat_userdata
;
2928 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
2929 entry
->fds
= p
->p_fd
->fd_nfiles
;
2931 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
2932 entry
->cpu_time
.tv_sec
= tv_sec
;
2933 entry
->cpu_time
.tv_usec
= tv_usec
;
2939 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
2941 kern_return_t kr
= KERN_SUCCESS
;
2942 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
2943 vm_statistics64_data_t vm_stat
;
2945 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
) != KERN_SUCCESS
)) {
2946 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
2947 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
2949 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
2950 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
2951 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
2952 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
2953 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
2954 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
2956 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
2957 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
2958 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
2959 snapshot
->stats
.compressions
= vm_stat
.compressions
;
2960 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
2961 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
2962 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
2967 * Collect vm statistics at boot.
2968 * Called only once (see kern_exec.c)
2969 * Data can be consumed at any time.
2972 memorystatus_init_at_boot_snapshot() {
2973 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
2974 memorystatus_at_boot_snapshot
.entry_count
= 0;
2975 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
2976 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
2980 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
2983 unsigned int b
= 0, i
= 0;
2985 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
2986 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
2987 unsigned int snapshot_max
= 0;
2991 * This is an on_demand snapshot
2993 snapshot
= od_snapshot
;
2994 snapshot_list
= od_snapshot
->entries
;
2995 snapshot_max
= ods_list_count
;
2998 * This is a jetsam event snapshot
3000 snapshot
= memorystatus_jetsam_snapshot
;
3001 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
3002 snapshot_max
= memorystatus_jetsam_snapshot_max
;
3005 memorystatus_init_snapshot_vmstats(snapshot
);
3007 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
3010 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
3012 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
])) {
3016 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",
3018 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],
3019 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]);
3021 if (++i
== snapshot_max
) {
3026 snapshot
->snapshot_time
= mach_absolute_time();
3027 snapshot
->entry_count
= i
;
3030 /* update the system buffer count */
3031 memorystatus_jetsam_snapshot_count
= i
;
3035 #if DEVELOPMENT || DEBUG
3038 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
) {
3040 memorystatus_jetsam_panic_options_t debug
;
3042 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
3046 ret
= copyin(buffer
, &debug
, buffer_size
);
3051 /* Panic bits match kMemorystatusKilled* enum */
3052 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
3054 /* Copyout new value */
3055 debug
.data
= memorystatus_jetsam_panic_debug
;
3056 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
3062 * Triggers a sort_order on a specified jetsam priority band.
3063 * This is for testing only, used to force a path through the sort
3067 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
) {
3071 unsigned int bucket_index
= 0;
3073 if (priority
== -1) {
3074 /* Use as shorthand for default priority */
3075 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
3077 bucket_index
= (unsigned int)priority
;
3080 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
3088 * Jetsam a specific process.
3091 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
) {
3095 /* TODO - add a victim queue and push this into the main jetsam thread */
3097 p
= proc_find(victim_pid
);
3102 printf("memorystatus: specifically killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3103 victim_pid
, (p
->p_comm
? p
->p_comm
: "(unknown)"),
3104 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, memorystatus_available_pages
);
3108 if (memorystatus_jetsam_snapshot_count
== 0) {
3109 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3112 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
);
3115 killed
= memorystatus_do_kill(p
, cause
);
3122 * Jetsam the first process in the queue.
3125 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, int32_t *priority
, uint32_t *errors
)
3128 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
3129 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
3134 #ifndef CONFIG_FREEZE
3138 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
3139 memorystatus_available_pages
, 0, 0, 0, 0);
3142 if (sort_flag
== TRUE
) {
3143 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
3148 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3150 #if DEVELOPMENT || DEBUG
3152 int procSuspendedForDiagnosis
;
3153 #endif /* DEVELOPMENT || DEBUG */
3156 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
3158 #if DEVELOPMENT || DEBUG
3159 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
3160 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
3161 #endif /* DEVELOPMENT || DEBUG */
3164 aPid_ep
= p
->p_memstat_effectivepriority
;
3166 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
3170 #if DEVELOPMENT || DEBUG
3171 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
3172 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
3175 #endif /* DEVELOPMENT || DEBUG */
3177 if (cause
== kMemorystatusKilledVnodes
)
3180 * If the system runs out of vnodes, we systematically jetsam
3181 * processes in hopes of stumbling onto a vnode gain that helps
3182 * the system recover. The process that happens to trigger
3183 * this path has no known relationship to the vnode consumption.
3184 * We attempt to safeguard that process e.g: do not jetsam it.
3187 if (p
== current_proc()) {
3188 /* do not jetsam the current process */
3195 boolean_t reclaim_proc
= !(p
->p_memstat_state
& (P_MEMSTAT_LOCKED
| P_MEMSTAT_NORECLAIM
));
3196 if (any
|| reclaim_proc
) {
3208 * Capture a snapshot if none exists and:
3209 * - priority was not requested (this is something other than an ambient kill)
3210 * - the priority was requested *and* the targeted process is not at idle priority
3212 if ((memorystatus_jetsam_snapshot_count
== 0) &&
3213 (memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (*priority
!= JETSAM_PRIORITY_IDLE
))))) {
3214 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3215 new_snapshot
= TRUE
;
3219 * Mark as terminated so that if exit1() indicates success, but the process (for example)
3220 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
3221 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
3222 * acquisition of the proc lock.
3224 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3226 #if DEVELOPMENT || DEBUG
3227 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && activeProcess
) {
3228 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
3229 aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"), memorystatus_level
);
3230 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
);
3231 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
3232 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
3233 jetsam_diagnostic_suspended_one_active_proc
= 1;
3234 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
3237 p
= proc_ref_locked(p
);
3240 task_suspend(p
->task
);
3242 *priority
= aPid_ep
;
3250 #endif /* DEVELOPMENT || DEBUG */
3252 /* Shift queue, update stats */
3253 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
);
3255 if (proc_ref_locked(p
) == p
) {
3257 printf("memorystatus: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3258 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ?
3259 "idle exiting pid" : "jetsam killing pid"),
3260 aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"),
3261 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
3263 killed
= memorystatus_do_kill(p
, cause
);
3268 *priority
= aPid_ep
;
3276 * Failure - first unwind the state,
3277 * then fall through to restart the search.
3280 proc_rele_locked(p
);
3281 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3282 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
3287 * Failure - restart the search.
3289 * We might have raced with "p" exiting on another core, resulting in no
3290 * ref on "p". Or, we may have failed to kill "p".
3292 * Either way, we fall thru to here, leaving the proc in the
3293 * P_MEMSTAT_TERMINATED state.
3295 * And, we hold the the proc_list_lock at this point.
3299 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3307 /* Clear snapshot if freshly captured and no target was found */
3308 if (new_snapshot
&& !killed
) {
3309 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
3312 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
3313 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
3319 * Jetsam aggressively
3322 memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, int aggr_count
, int32_t priority_max
,
3326 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
3327 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
3330 int32_t aPid_ep
= 0;
3334 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
3335 memorystatus_available_pages
, priority_max
, 0, 0, 0);
3339 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3341 #if DEVELOPMENT || DEBUG
3343 int procSuspendedForDiagnosis
;
3344 #endif /* DEVELOPMENT || DEBUG */
3346 if ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
) {
3349 * We have raced with next_p running on another core, as it has
3350 * moved to a different jetsam priority band. This means we have
3351 * lost our place in line while traversing the jetsam list. We
3352 * attempt to recover by rewinding to the beginning of the band
3353 * we were already traversing. By doing this, we do not guarantee
3354 * that no process escapes this aggressive march, but we can make
3355 * skipping an entire range of processes less likely. (PR-21069019)
3358 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding %s moved from band %d --> %d\n",
3359 aggr_count
, next_p
->p_comm
, i
, next_p
->p_memstat_effectivepriority
);
3361 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3366 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
3368 if (p
->p_memstat_effectivepriority
> priority_max
) {
3370 * Bail out of this killing spree if we have
3371 * reached beyond the priority_max jetsam band.
3372 * That is, we kill up to and through the
3373 * priority_max jetsam band.
3379 #if DEVELOPMENT || DEBUG
3380 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
3381 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
3382 #endif /* DEVELOPMENT || DEBUG */
3385 aPid_ep
= p
->p_memstat_effectivepriority
;
3387 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
3391 #if DEVELOPMENT || DEBUG
3392 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
3393 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
3396 #endif /* DEVELOPMENT || DEBUG */
3399 * Capture a snapshot if none exists.
3401 if (memorystatus_jetsam_snapshot_count
== 0) {
3402 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3403 new_snapshot
= TRUE
;
3407 * Mark as terminated so that if exit1() indicates success, but the process (for example)
3408 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
3409 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
3410 * acquisition of the proc lock.
3412 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3414 /* Shift queue, update stats */
3415 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
);
3418 * In order to kill the target process, we will drop the proc_list_lock.
3419 * To guaranteee that p and next_p don't disappear out from under the lock,
3420 * we must take a ref on both.
3421 * If we cannot get a reference, then it's likely we've raced with
3422 * that process exiting on another core.
3424 if (proc_ref_locked(p
) == p
) {
3426 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
3430 * We must have raced with next_p exiting on another core.
3431 * Recover by getting the next eligible process in the band.
3434 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
3435 aggr_count
, next_p
->p_pid
, (next_p
->p_comm
? next_p
->p_comm
: "(unknown)"));
3438 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
3443 printf("memorystatus: aggressive%d: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3445 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing pid"),
3446 aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"),
3447 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
3449 killed
= memorystatus_do_kill(p
, cause
);
3459 * Continue the killing spree.
3463 proc_rele_locked(next_p
);
3469 * Failure - first unwind the state,
3470 * then fall through to restart the search.
3473 proc_rele_locked(p
);
3475 proc_rele_locked(next_p
);
3477 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3478 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
3484 * Failure - restart the search at the beginning of
3485 * the band we were already traversing.
3487 * We might have raced with "p" exiting on another core, resulting in no
3488 * ref on "p". Or, we may have failed to kill "p".
3490 * Either way, we fall thru to here, leaving the proc in the
3491 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
3493 * And, we hold the the proc_list_lock at this point.
3496 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3502 /* Clear snapshot if freshly captured and no target was found */
3503 if (new_snapshot
&& (kill_count
== 0)) {
3504 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
3507 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
3508 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
3510 if (kill_count
> 0) {
3521 memorystatus_kill_hiwat_proc(uint32_t *errors
)
3524 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
3525 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
3530 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
3531 memorystatus_available_pages
, 0, 0, 0, 0);
3535 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3541 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
3544 aPid_ep
= p
->p_memstat_effectivepriority
;
3546 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
3550 /* skip if no limit set */
3551 if (p
->p_memstat_memlimit
<= 0) {
3557 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
3558 * Background limits are described via the inactive limit slots.
3559 * Their fatal/non-fatal setting will drive whether or not to be
3560 * considered in this kill path.
3563 /* skip if a currently inapplicable limit is encountered */
3564 if ((p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_BACKGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
3569 footprint
= (uint32_t)(get_task_phys_footprint(p
->task
) / (1024 * 1024));
3570 skip
= (((int32_t)footprint
) <= p
->p_memstat_memlimit
);
3572 #if DEVELOPMENT || DEBUG
3573 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
3574 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
3578 #endif /* DEVELOPMENT || DEBUG */
3582 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
3593 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %d Mb > 1 (%d Mb)\n",
3594 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing", aPid
, p
->p_comm
, footprint
, p
->p_memstat_memlimit
);
3596 if (memorystatus_jetsam_snapshot_count
== 0) {
3597 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3598 new_snapshot
= TRUE
;
3601 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3603 #if DEVELOPMENT || DEBUG
3604 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
3605 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid
, memorystatus_available_pages
);
3606 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
);
3607 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
3609 p
= proc_ref_locked(p
);
3612 task_suspend(p
->task
);
3619 #endif /* DEVELOPMENT || DEBUG */
3621 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledHiwat
);
3623 if (proc_ref_locked(p
) == p
) {
3626 printf("memorystatus: jetsam killing pid %d [%s] (highwater %d) - memorystatus_available_pages: %d\n",
3627 aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"), aPid_ep
, memorystatus_available_pages
);
3629 killed
= memorystatus_do_kill(p
, kMemorystatusKilledHiwat
);
3639 * Failure - first unwind the state,
3640 * then fall through to restart the search.
3643 proc_rele_locked(p
);
3644 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3645 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
3650 * Failure - restart the search.
3652 * We might have raced with "p" exiting on another core, resulting in no
3653 * ref on "p". Or, we may have failed to kill "p".
3655 * Either way, we fall thru to here, leaving the proc in the
3656 * P_MEMSTAT_TERMINATED state.
3658 * And, we hold the the proc_list_lock at this point.
3662 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3670 /* Clear snapshot if freshly captured and no target was found */
3671 if (new_snapshot
&& !killed
) {
3672 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
3675 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
3676 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
3681 #endif /* LEGACY_HIWATER */
3684 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
) {
3685 /* TODO: allow a general async path */
3686 if ((victim_pid
!= -1) || (cause
!= kMemorystatusKilledVMPageShortage
&& cause
!= kMemorystatusKilledVMThrashing
&&
3687 cause
!= kMemorystatusKilledFCThrashing
)) {
3691 kill_under_pressure_cause
= cause
;
3692 memorystatus_thread_wake();
3697 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
) {
3699 uint32_t errors
= 0;
3701 if (victim_pid
== -1) {
3702 /* No pid, so kill first process */
3703 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, NULL
, &errors
);
3705 res
= memorystatus_kill_specific_process(victim_pid
, cause
);
3709 memorystatus_clear_errors();
3713 /* Fire off snapshot notification */
3714 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3715 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
3716 uint64_t timestamp_now
= mach_absolute_time();
3717 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3718 if (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3719 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
) {
3720 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3723 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3733 memorystatus_kill_on_VM_page_shortage(boolean_t async
) {
3735 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
3737 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
);
3742 memorystatus_kill_on_VM_thrashing(boolean_t async
) {
3744 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing
);
3746 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing
);
3751 memorystatus_kill_on_FC_thrashing(boolean_t async
) {
3753 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
3755 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
);
3760 memorystatus_kill_on_vnode_limit(void) {
3761 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
);
3764 #endif /* CONFIG_JETSAM */
3768 __private_extern__
void
3769 memorystatus_freeze_init(void)
3771 kern_return_t result
;
3774 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
3775 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
3777 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
3779 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
3780 if (result
== KERN_SUCCESS
) {
3781 thread_deallocate(thread
);
3783 panic("Could not create memorystatus_freeze_thread");
3788 * Synchronously freeze the passed proc. Called with a reference to the proc held.
3790 * Returns EINVAL or the value returned by task_freeze().
3793 memorystatus_freeze_process_sync(proc_t p
)
3797 boolean_t memorystatus_freeze_swap_low
= FALSE
;
3799 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
3800 memorystatus_available_pages
, 0, 0, 0, 0);
3802 lck_mtx_lock(&freezer_mutex
);
3808 if (memorystatus_freeze_enabled
== FALSE
) {
3812 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
3816 if (memorystatus_freeze_update_throttle()) {
3817 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
3818 memorystatus_freeze_throttle_count
++;
3825 uint32_t purgeable
, wired
, clean
, dirty
, state
;
3826 uint32_t max_pages
, pages
, i
;
3830 state
= p
->p_memstat_state
;
3832 /* Ensure the process is eligible for freezing */
3833 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
3838 /* Only freeze processes meeting our minimum resident page criteria */
3839 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3840 if (pages
< memorystatus_freeze_pages_min
) {
3845 if (DEFAULT_FREEZER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
3847 unsigned int avail_swap_space
= 0; /* in pages. */
3849 if (DEFAULT_FREEZER_IS_ACTIVE
) {
3851 * Freezer backed by default pager and swap file(s).
3853 avail_swap_space
= default_pager_swap_pages_free();
3856 * Freezer backed by the compressor and swap file(s)
3857 * while will hold compressed data.
3859 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
3862 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
3864 if (max_pages
< memorystatus_freeze_pages_min
) {
3870 * We only have the compressor without any swap.
3872 max_pages
= UINT32_MAX
- 1;
3875 /* Mark as locked temporarily to avoid kill */
3876 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
3879 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
3881 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
3882 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, shared %d, free swap: %d\n",
3883 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"),
3884 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, shared
, default_pager_swap_pages_free());
3887 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
3889 if (ret
== KERN_SUCCESS
) {
3890 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
3892 memorystatus_frozen_count
++;
3894 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
3896 if (DEFAULT_FREEZER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
3898 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
3899 throttle_intervals
[i
].pageouts
+= dirty
;
3903 memorystatus_freeze_pageouts
+= dirty
;
3904 memorystatus_freeze_count
++;
3908 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3915 lck_mtx_unlock(&freezer_mutex
);
3916 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
3917 memorystatus_available_pages
, aPid
, 0, 0, 0);
3923 memorystatus_freeze_top_process(boolean_t
*memorystatus_freeze_swap_low
)
3927 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
3930 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
3931 memorystatus_available_pages
, 0, 0, 0, 0);
3935 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
3938 uint32_t purgeable
, wired
, clean
, dirty
;
3941 uint32_t max_pages
= 0;
3945 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
3948 state
= p
->p_memstat_state
;
3950 /* Ensure the process is eligible for freezing */
3951 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
3952 continue; // with lock held
3955 /* Only freeze processes meeting our minimum resident page criteria */
3956 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3957 if (pages
< memorystatus_freeze_pages_min
) {
3958 continue; // with lock held
3961 if (DEFAULT_FREEZER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
3963 /* Ensure there's enough free space to freeze this process. */
3965 unsigned int avail_swap_space
= 0; /* in pages. */
3967 if (DEFAULT_FREEZER_IS_ACTIVE
) {
3969 * Freezer backed by default pager and swap file(s).
3971 avail_swap_space
= default_pager_swap_pages_free();
3974 * Freezer backed by the compressor and swap file(s)
3975 * while will hold compressed data.
3977 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
3980 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
3982 if (max_pages
< memorystatus_freeze_pages_min
) {
3983 *memorystatus_freeze_swap_low
= TRUE
;
3989 * We only have the compressor pool.
3991 max_pages
= UINT32_MAX
- 1;
3994 /* Mark as locked temporarily to avoid kill */
3995 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
3997 p
= proc_ref_locked(p
);
4003 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
4005 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
4006 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, shared %d, free swap: %d\n",
4007 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (p
->p_comm
? p
->p_comm
: "(unknown)"),
4008 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, shared
, default_pager_swap_pages_free());
4011 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
4014 if (KERN_SUCCESS
== kr
) {
4015 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
4017 memorystatus_frozen_count
++;
4019 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
4021 if (DEFAULT_FREEZER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
4023 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
4024 throttle_intervals
[i
].pageouts
+= dirty
;
4028 memorystatus_freeze_pageouts
+= dirty
;
4029 memorystatus_freeze_count
++;
4033 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
4035 /* Return KERN_SUCESS */
4049 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
4050 memorystatus_available_pages
, aPid
, 0, 0, 0);
4055 static inline boolean_t
4056 memorystatus_can_freeze_processes(void)
4062 if (memorystatus_suspended_count
) {
4063 uint32_t average_resident_pages
, estimated_processes
;
4065 /* Estimate the number of suspended processes we can fit */
4066 average_resident_pages
= memorystatus_suspended_footprint_total
/ memorystatus_suspended_count
;
4067 estimated_processes
= memorystatus_suspended_count
+
4068 ((memorystatus_available_pages
- memorystatus_available_pages_critical
) / average_resident_pages
);
4070 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
4071 if (estimated_processes
<= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
) {
4072 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_LOW
;
4074 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
4077 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
4078 memorystatus_suspended_count
, average_resident_pages
, estimated_processes
);
4080 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
4095 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
4097 boolean_t can_freeze
= TRUE
;
4099 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
4100 after boot, and is generally is a no-op once we've reached steady state. */
4101 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
4105 /* Check minimum suspended process threshold. */
4106 if (!memorystatus_can_freeze_processes()) {
4110 if (COMPRESSED_PAGER_IS_SWAPLESS
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPLESS
) {
4112 * In-core compressor used for freezing WITHOUT on-disk swap support.
4115 if (vm_compressor_low_on_space()) {
4116 if (*memorystatus_freeze_swap_low
) {
4117 *memorystatus_freeze_swap_low
= TRUE
;
4123 if (*memorystatus_freeze_swap_low
) {
4124 *memorystatus_freeze_swap_low
= FALSE
;
4131 * Freezing WITH on-disk swap support.
4134 if (DEFAULT_FREEZER_COMPRESSED_PAGER_IS_SWAPBACKED
) {
4136 * In-core compressor fronts the swap.
4138 if (vm_swap_low_on_space()) {
4139 if (*memorystatus_freeze_swap_low
) {
4140 *memorystatus_freeze_swap_low
= TRUE
;
4146 } else if (DEFAULT_FREEZER_IS_ACTIVE
) {
4148 * Legacy freeze mode with no compressor support.
4150 if (default_pager_swap_pages_free() < memorystatus_freeze_pages_min
) {
4151 if (*memorystatus_freeze_swap_low
) {
4152 *memorystatus_freeze_swap_low
= TRUE
;
4158 panic("Not a valid freeze configuration.\n");
4166 memorystatus_freeze_update_throttle_interval(mach_timespec_t
*ts
, struct throttle_interval_t
*interval
)
4168 unsigned int freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
4169 if (CMP_MACH_TIMESPEC(ts
, &interval
->ts
) >= 0) {
4170 if (!interval
->max_pageouts
) {
4171 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / (24 * 60)));
4173 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval
->mins
);
4175 interval
->ts
.tv_sec
= interval
->mins
* 60;
4176 interval
->ts
.tv_nsec
= 0;
4177 ADD_MACH_TIMESPEC(&interval
->ts
, ts
);
4178 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
4179 if (interval
->pageouts
> interval
->max_pageouts
) {
4180 interval
->pageouts
-= interval
->max_pageouts
;
4182 interval
->pageouts
= 0;
4184 interval
->throttle
= FALSE
;
4185 } else if (!interval
->throttle
&& interval
->pageouts
>= interval
->max_pageouts
) {
4186 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval
->mins
);
4187 interval
->throttle
= TRUE
;
4190 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
4191 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
4192 interval
->throttle
? "on" : "off");
4196 memorystatus_freeze_update_throttle(void)
4202 boolean_t throttled
= FALSE
;
4204 #if DEVELOPMENT || DEBUG
4205 if (!memorystatus_freeze_throttle_enabled
)
4209 clock_get_system_nanotime(&sec
, &nsec
);
4213 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
4215 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
4216 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
4217 * order to allow for bursts of activity.
4219 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
4220 memorystatus_freeze_update_throttle_interval(&ts
, &throttle_intervals
[i
]);
4221 if (throttle_intervals
[i
].throttle
== TRUE
)
4229 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
4231 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
4233 lck_mtx_lock(&freezer_mutex
);
4234 if (memorystatus_freeze_enabled
) {
4235 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
4236 /* Only freeze if we've not exceeded our pageout budgets.*/
4237 if (!memorystatus_freeze_update_throttle()) {
4238 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low
);
4240 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
4241 memorystatus_freeze_throttle_count
++; /* Throttled, update stats */
4245 lck_mtx_unlock(&freezer_mutex
);
4247 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
4248 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
4251 #endif /* CONFIG_FREEZE */
4253 #if VM_PRESSURE_EVENTS
4255 #if CONFIG_MEMORYSTATUS
4258 memorystatus_send_note(int event_code
, void *data
, size_t data_length
) {
4260 struct kev_msg ev_msg
;
4262 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
4263 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
4264 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
4266 ev_msg
.event_code
= event_code
;
4268 ev_msg
.dv
[0].data_length
= data_length
;
4269 ev_msg
.dv
[0].data_ptr
= data
;
4270 ev_msg
.dv
[1].data_length
= 0;
4272 ret
= kev_post_msg(&ev_msg
);
4274 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
4281 memorystatus_warn_process(pid_t pid
, boolean_t critical
) {
4283 boolean_t ret
= FALSE
;
4284 boolean_t found_knote
= FALSE
;
4285 struct knote
*kn
= NULL
;
4288 * See comment in sysctl_memorystatus_vm_pressure_send.
4291 memorystatus_klist_lock();
4293 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
4294 proc_t knote_proc
= kn
->kn_kq
->kq_p
;
4295 pid_t knote_pid
= knote_proc
->p_pid
;
4297 if (knote_pid
== pid
) {
4299 * By setting the "fflags" here, we are forcing
4300 * a process to deal with the case where it's
4301 * bumping up into its memory limits. If we don't
4302 * do this here, we will end up depending on the
4303 * system pressure snapshot evaluation in
4304 * filt_memorystatus().
4308 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
4309 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
4310 } else if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
4311 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
4314 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
4315 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
4324 KNOTE(&memorystatus_klist
, 0);
4327 if (vm_dispatch_pressure_note_to_pid(pid
, FALSE
) == 0) {
4332 memorystatus_klist_unlock();
4338 * Can only be set by the current task on itself.
4341 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
4343 boolean_t set_privilege
= FALSE
;
4345 * Need an entitlement check here?
4347 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
4348 set_privilege
= TRUE
;
4349 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
4350 set_privilege
= FALSE
;
4355 return (task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
));
4359 memorystatus_send_pressure_note(pid_t pid
) {
4360 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
4361 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
4365 memorystatus_send_low_swap_note(void) {
4367 struct knote
*kn
= NULL
;
4369 memorystatus_klist_lock();
4370 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
4371 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
4372 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
4373 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
4374 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
4375 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
4376 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
4381 memorystatus_klist_unlock();
4385 memorystatus_bg_pressure_eligible(proc_t p
) {
4386 boolean_t eligible
= FALSE
;
4390 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
4392 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
4393 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
4403 memorystatus_is_foreground_locked(proc_t p
) {
4404 return ((p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
4405 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
));
4407 #endif /* CONFIG_MEMORYSTATUS */
4410 * Trigger levels to test the mechanism.
4411 * Can be used via a sysctl.
4413 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
4414 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
4415 #define TEST_PURGEABLE_TRIGGER_ONE 3
4416 #define TEST_PURGEABLE_TRIGGER_ALL 4
4417 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
4418 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
4420 boolean_t memorystatus_manual_testing_on
= FALSE
;
4421 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
4423 extern struct knote
*
4424 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
4427 kern_return_t
vm_pressure_notification_without_levels(boolean_t
);
4429 extern void vm_pressure_klist_lock(void);
4430 extern void vm_pressure_klist_unlock(void);
4432 extern void vm_reset_active_list(void);
4434 extern void delay(int);
4436 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
4438 void memorystatus_on_pageout_scan_end(void) {
4445 * knote_pressure_level - to check if the knote is registered for this notification level.
4447 * task - task whose bits we'll be modifying
4449 * 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.
4451 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
4456 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
)
4458 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
4460 if (task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
4462 task_clear_has_been_notified(task
, pressure_level_to_clear
);
4465 task_mark_has_been_notified(task
, pressure_level_to_set
);
4472 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
4474 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
4477 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
4479 struct knote
*kn_max
= NULL
;
4480 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
4481 pid_t target_pid
= -1;
4482 struct klist dispatch_klist
= { NULL
};
4483 proc_t target_proc
= PROC_NULL
;
4484 struct task
*task
= NULL
;
4485 boolean_t found_candidate
= FALSE
;
4487 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
4488 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
4489 boolean_t smoothing_window_started
= FALSE
;
4490 struct timeval smoothing_window_start_tstamp
= {0, 0};
4491 struct timeval curr_tstamp
= {0, 0};
4492 int elapsed_msecs
= 0;
4495 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
4497 int idle_kill_counter
= 0;
4500 * On desktop we take this opportunity to free up memory pressure
4501 * by immediately killing idle exitable processes. We use a delay
4502 * to avoid overkill. And we impose a max counter as a fail safe
4503 * in case daemons re-launch too fast.
4505 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
4506 if (memorystatus_idle_exit_from_VM() == FALSE
) {
4507 /* No idle exitable processes left to kill */
4510 idle_kill_counter
++;
4512 if (memorystatus_manual_testing_on
== TRUE
) {
4514 * Skip the delay when testing
4515 * the pressure notification scheme.
4518 delay(1000000); /* 1 second */
4521 #endif /* !CONFIG_JETSAM */
4526 * There is a race window here. But it's not clear
4527 * how much we benefit from having extra synchronization.
4529 level_snapshot
= memorystatus_vm_pressure_level
;
4531 if (prev_level_snapshot
> level_snapshot
) {
4533 * Pressure decreased? Let's take a little breather
4534 * and see if this condition stays.
4536 if (smoothing_window_started
== FALSE
) {
4538 smoothing_window_started
= TRUE
;
4539 microuptime(&smoothing_window_start_tstamp
);
4542 microuptime(&curr_tstamp
);
4543 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
4544 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
4546 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
4548 delay(INTER_NOTIFICATION_DELAY
);
4553 prev_level_snapshot
= level_snapshot
;
4554 smoothing_window_started
= FALSE
;
4556 memorystatus_klist_lock();
4557 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
4559 if (kn_max
== NULL
) {
4560 memorystatus_klist_unlock();
4563 * No more level-based clients to notify.
4564 * Try the non-level based notification clients.
4566 * However, these non-level clients don't understand
4567 * the "return-to-normal" notification.
4569 * So don't consider them for those notifications. Just
4574 if (level_snapshot
!= kVMPressureNormal
) {
4575 goto try_dispatch_vm_clients
;
4577 return KERN_FAILURE
;
4581 target_proc
= kn_max
->kn_kq
->kq_p
;
4584 if (target_proc
!= proc_ref_locked(target_proc
)) {
4585 target_proc
= PROC_NULL
;
4587 memorystatus_klist_unlock();
4592 target_pid
= target_proc
->p_pid
;
4594 task
= (struct task
*)(target_proc
->task
);
4596 if (level_snapshot
!= kVMPressureNormal
) {
4598 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
4600 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, kVMPressureCritical
, kVMPressureWarning
) == TRUE
) {
4601 found_candidate
= TRUE
;
4604 if (level_snapshot
== kVMPressureCritical
) {
4606 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, kVMPressureWarning
, kVMPressureCritical
) == TRUE
) {
4607 found_candidate
= TRUE
;
4612 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
4614 task_clear_has_been_notified(task
, kVMPressureWarning
);
4615 task_clear_has_been_notified(task
, kVMPressureCritical
);
4617 found_candidate
= TRUE
;
4621 if (found_candidate
== FALSE
) {
4622 proc_rele(target_proc
);
4623 memorystatus_klist_unlock();
4627 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
4628 proc_t knote_proc
= kn_cur
->kn_kq
->kq_p
;
4629 pid_t knote_pid
= knote_proc
->p_pid
;
4630 if (knote_pid
== target_pid
) {
4631 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
4632 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
4636 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
4638 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
4639 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
4640 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
4643 memorystatus_klist_unlock();
4645 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
4646 proc_rele(target_proc
);
4648 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
4652 try_dispatch_vm_clients
:
4653 if (kn_max
== NULL
&& level_snapshot
!= kVMPressureNormal
) {
4655 * We will exit this loop when we are done with
4656 * notification clients (level and non-level based).
4658 if ((vm_pressure_notify_dispatch_vm_clients(target_foreground_process
) == KERN_FAILURE
) && (kn_max
== NULL
)) {
4660 * kn_max == NULL i.e. we didn't find any eligible clients for the level-based notifications
4662 * we have failed to find any eligible clients for the non-level based notifications too.
4666 return KERN_FAILURE
;
4671 * LD: This block of code below used to be invoked in the older memory notification scheme on embedded everytime
4672 * a process was sent a memory pressure notification. The "memorystatus_klist" list was used to hold these
4673 * privileged listeners. But now we have moved to the newer scheme and are trying to move away from the extra
4674 * notifications. So the code is here in case we break compat. and need to send out notifications to the privileged
4680 if (memorystatus_manual_testing_on
== TRUE
) {
4682 * Testing out the pressure notification scheme.
4683 * No need for delays etc.
4687 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
4689 unsigned int page_delta
= 0;
4690 unsigned int skip_delay_page_threshold
= 0;
4692 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
4694 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
4695 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
4697 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
4699 * We are nearing the critcal mark fast and can't afford to wait between
4704 #endif /* CONFIG_JETSAM */
4706 if (sleep_interval
) {
4707 delay(sleep_interval
);
4712 return KERN_SUCCESS
;
4716 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
4719 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
4721 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
4723 switch (internal_pressure_level
) {
4725 case kVMPressureNormal
:
4727 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
4731 case kVMPressureWarning
:
4732 case kVMPressureUrgent
:
4734 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
4738 case kVMPressureCritical
:
4740 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
4748 return dispatch_level
;
4752 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
4754 #pragma unused(arg1, arg2, oidp)
4755 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
4757 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
4760 #if DEBUG || DEVELOPMENT
4762 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
,
4763 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
4765 #else /* DEBUG || DEVELOPMENT */
4767 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
4768 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
4770 #endif /* DEBUG || DEVELOPMENT */
4772 extern int memorystatus_purge_on_warning
;
4773 extern int memorystatus_purge_on_critical
;
4776 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
4778 #pragma unused(arg1, arg2)
4782 int pressure_level
= 0;
4783 int trigger_request
= 0;
4786 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
4787 if (error
|| !req
->newptr
) {
4791 memorystatus_manual_testing_on
= TRUE
;
4793 trigger_request
= (level
>> 16) & 0xFFFF;
4794 pressure_level
= (level
& 0xFFFF);
4796 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
4797 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
4800 switch (pressure_level
) {
4801 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
4802 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
4803 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
4810 * The pressure level is being set from user-space.
4811 * And user-space uses the constants in sys/event.h
4812 * So we translate those events to our internal levels here.
4814 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
4816 memorystatus_manual_testing_level
= kVMPressureNormal
;
4819 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
4821 memorystatus_manual_testing_level
= kVMPressureWarning
;
4822 force_purge
= memorystatus_purge_on_warning
;
4824 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
4826 memorystatus_manual_testing_level
= kVMPressureCritical
;
4827 force_purge
= memorystatus_purge_on_critical
;
4830 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
4832 /* purge according to the new pressure level */
4833 switch (trigger_request
) {
4834 case TEST_PURGEABLE_TRIGGER_ONE
:
4835 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
4836 if (force_purge
== 0) {
4837 /* no purging requested */
4840 vm_purgeable_object_purge_one_unlocked(force_purge
);
4842 case TEST_PURGEABLE_TRIGGER_ALL
:
4843 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
4844 if (force_purge
== 0) {
4845 /* no purging requested */
4848 while (vm_purgeable_object_purge_one_unlocked(force_purge
));
4852 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
4853 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
4855 memorystatus_update_vm_pressure(TRUE
);
4858 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
4859 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
4861 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
4866 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
4867 memorystatus_manual_testing_on
= FALSE
;
4869 vm_pressure_klist_lock();
4870 vm_reset_active_list();
4871 vm_pressure_klist_unlock();
4874 vm_pressure_klist_lock();
4875 vm_pressure_notification_without_levels(FALSE
);
4876 vm_pressure_klist_unlock();
4882 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
4883 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
4886 extern int memorystatus_purge_on_warning
;
4887 extern int memorystatus_purge_on_urgent
;
4888 extern int memorystatus_purge_on_critical
;
4890 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_warning
, 0, "");
4891 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_urgent
, 0, "");
4892 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_critical
, 0, "");
4895 #endif /* VM_PRESSURE_EVENTS */
4897 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
4899 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
4901 uint32_t list_count
, i
= 0;
4902 memorystatus_priority_entry_t
*list_entry
;
4905 list_count
= memorystatus_list_count
;
4906 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
4908 /* Just a size check? */
4913 /* Otherwise, validate the size of the buffer */
4914 if (*buffer_size
< *list_size
) {
4918 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
4923 memset(*list_ptr
, 0, *list_size
);
4925 *buffer_size
= *list_size
;
4928 list_entry
= *list_ptr
;
4932 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4933 while (p
&& (*list_size
< *buffer_size
)) {
4934 list_entry
->pid
= p
->p_pid
;
4935 list_entry
->priority
= p
->p_memstat_effectivepriority
;
4936 list_entry
->user_data
= p
->p_memstat_userdata
;
4940 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
4941 * Background limits are described via the inactive limit slots.
4942 * So, here, the cached limit should always be valid.
4945 if (p
->p_memstat_memlimit
<= 0) {
4946 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
4948 list_entry
->limit
= p
->p_memstat_memlimit
;
4951 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
4953 list_entry
->state
= memorystatus_build_state(p
);
4956 *list_size
+= sizeof(memorystatus_priority_entry_t
);
4958 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4963 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
4969 memorystatus_cmd_get_priority_list(user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
4971 boolean_t size_only
;
4972 memorystatus_priority_entry_t
*list
= NULL
;
4975 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
4977 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
4983 error
= copyout(list
, buffer
, list_size
);
4987 *retval
= list_size
;
4992 kfree(list
, buffer_size
);
5001 memorystatus_clear_errors(void)
5006 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
5010 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5012 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
5013 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
5015 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5020 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
5024 memorystatus_update_levels_locked(boolean_t critical_only
) {
5026 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
5029 * If there's an entry in the first bucket, we have idle processes.
5031 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
5032 if (first_bucket
->count
) {
5033 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
5035 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
5037 * The critical threshold must never exceed the pressure threshold
5039 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
5043 #if DEBUG || DEVELOPMENT
5044 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5045 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
5047 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
5049 * The critical threshold must never exceed the pressure threshold
5051 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
5056 if (critical_only
) {
5060 #if VM_PRESSURE_EVENTS
5061 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
5062 #if DEBUG || DEVELOPMENT
5063 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5064 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
5071 * Get the at_boot snapshot
5074 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
5075 size_t input_size
= *snapshot_size
;
5078 * The at_boot snapshot has no entry list.
5080 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
5087 * Validate the size of the snapshot buffer
5089 if (input_size
< *snapshot_size
) {
5094 * Update the notification_time only
5096 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
5097 *snapshot
= &memorystatus_at_boot_snapshot
;
5099 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
5100 (long)input_size
, (long)*snapshot_size
, 0);
5105 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
5106 size_t input_size
= *snapshot_size
;
5107 uint32_t ods_list_count
= memorystatus_list_count
;
5108 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
5110 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
5117 * Validate the size of the snapshot buffer.
5118 * This is inherently racey. May want to revisit
5119 * this error condition and trim the output when
5122 if (input_size
< *snapshot_size
) {
5127 * Allocate and initialize a snapshot buffer.
5129 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
5134 memset(ods
, 0, *snapshot_size
);
5137 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
5141 * Return the kernel allocated, on_demand buffer.
5142 * The caller of this routine will copy the data out
5143 * to user space and then free the kernel allocated
5148 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
5149 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
5155 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
5156 size_t input_size
= *snapshot_size
;
5158 if (memorystatus_jetsam_snapshot_count
> 0) {
5159 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
5168 if (input_size
< *snapshot_size
) {
5172 *snapshot
= memorystatus_jetsam_snapshot
;
5174 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
5175 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
5182 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
5184 boolean_t size_only
;
5185 boolean_t is_default_snapshot
= FALSE
;
5186 boolean_t is_on_demand_snapshot
= FALSE
;
5187 boolean_t is_at_boot_snapshot
= FALSE
;
5188 memorystatus_jetsam_snapshot_t
*snapshot
;
5190 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
5194 is_default_snapshot
= TRUE
;
5195 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
5197 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
5199 * Unsupported bit set in flag.
5204 if ((flags
& (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) ==
5205 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
5207 * Can't have both set at the same time.
5212 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
5213 is_on_demand_snapshot
= TRUE
;
5215 * When not requesting the size only, the following call will allocate
5216 * an on_demand snapshot buffer, which is freed below.
5218 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
5220 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
5221 is_at_boot_snapshot
= TRUE
;
5222 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
5225 * Invalid flag setting.
5236 * Copy the data out to user space and clear the snapshot buffer.
5237 * If working with the jetsam snapshot,
5238 * clearing the buffer means, reset the count.
5239 * If working with an on_demand snapshot
5240 * clearing the buffer means, free it.
5241 * If working with the at_boot snapshot
5242 * there is nothing to clear or update.
5245 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
5246 if (is_default_snapshot
) {
5248 * The jetsam snapshot is never freed, its count is simply reset.
5250 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5253 memorystatus_jetsam_snapshot_last_timestamp
= 0;
5258 if (is_on_demand_snapshot
) {
5260 * The on_demand snapshot is always freed,
5261 * even if the copyout failed.
5264 kfree(snapshot
, buffer_size
);
5270 *retval
= buffer_size
;
5277 * Routine: memorystatus_cmd_grp_set_properties
5278 * Purpose: Update properties for a group of processes.
5280 * Supported Properties:
5282 * Move each process out of its effective priority
5283 * band and into a new priority band.
5284 * Maintains relative order from lowest to highest priority.
5285 * In single band, maintains relative order from head to tail.
5287 * eg: before [effectivepriority | pid]
5289 * [17 | p55, p67, p19 ]
5294 * after [ new band | pid]
5295 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
5297 * Returns: 0 on success, else non-zero.
5299 * Caveat: We know there is a race window regarding recycled pids.
5300 * A process could be killed before the kernel can act on it here.
5301 * If a pid cannot be found in any of the jetsam priority bands,
5302 * then we simply ignore it. No harm.
5303 * But, if the pid has been recycled then it could be an issue.
5304 * In that scenario, we might move an unsuspecting process to the new
5305 * priority band. It's not clear how the kernel can safeguard
5306 * against this, but it would be an extremely rare case anyway.
5307 * The caller of this api might avoid such race conditions by
5308 * ensuring that the processes passed in the pid list are suspended.
5312 /* This internal structure can expand when we add support for more properties */
5313 typedef struct memorystatus_internal_properties
5316 int32_t priority
; /* see memorytstatus_priority_entry_t : priority */
5317 } memorystatus_internal_properties_t
;
5321 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
5323 #pragma unused (flags)
5326 * We only handle setting priority
5331 memorystatus_priority_entry_t
*entries
= NULL
;
5332 uint32_t entry_count
= 0;
5334 /* This will be the ordered proc list */
5335 memorystatus_internal_properties_t
*table
= NULL
;
5336 size_t table_size
= 0;
5337 uint32_t table_count
= 0;
5340 uint32_t bucket_index
= 0;
5341 boolean_t head_insert
;
5342 int32_t new_priority
;
5347 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0) || ((buffer_size
% sizeof(memorystatus_priority_entry_t
)) != 0)) {
5352 entry_count
= (buffer_size
/ sizeof(memorystatus_priority_entry_t
));
5353 if ((entries
= (memorystatus_priority_entry_t
*)kalloc(buffer_size
)) == NULL
) {
5358 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_START
, entry_count
, 0, 0, 0, 0);
5360 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
5364 /* Verify sanity of input priorities */
5365 for (i
=0; i
< entry_count
; i
++) {
5366 if (entries
[i
].priority
== -1) {
5367 /* Use as shorthand for default priority */
5368 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
5369 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
5370 /* JETSAM_PRIORITY_IDLE_DEFERRED is reserved for internal use;
5371 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
5372 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
5373 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
5374 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
5376 /* Deal with this later */
5377 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
5384 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
5385 if ( (table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
5389 memset(table
, 0, table_size
);
5393 * For each jetsam bucket entry, spin through the input property list.
5394 * When a matching pid is found, populate an adjacent table with the
5395 * appropriate proc pointer and new property values.
5396 * This traversal automatically preserves order from lowest
5397 * to highest priority.
5404 /* Create the ordered table */
5405 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
5406 while (p
&& (table_count
< entry_count
)) {
5407 for (i
=0; i
< entry_count
; i
++ ) {
5408 if (p
->p_pid
== entries
[i
].pid
) {
5409 /* Build the table data */
5410 table
[table_count
].proc
= p
;
5411 table
[table_count
].priority
= entries
[i
].priority
;
5416 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
5419 /* We now have ordered list of procs ready to move */
5420 for (i
=0; i
< table_count
; i
++) {
5424 /* Allow head inserts -- but relative order is now */
5425 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
5426 new_priority
= JETSAM_PRIORITY_IDLE
;
5429 new_priority
= table
[i
].priority
;
5430 head_insert
= false;
5434 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
5439 * Take appropriate steps if moving proc out of the
5440 * JETSAM_PRIORITY_IDLE_DEFERRED band.
5442 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE_DEFERRED
) {
5443 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
5446 memorystatus_update_priority_locked(p
, new_priority
, head_insert
);
5452 * if (table_count != entry_count)
5453 * then some pids were not found in a jetsam band.
5454 * harmless but interesting...
5456 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_END
, entry_count
, table_count
, 0, 0, 0);
5460 kfree(entries
, buffer_size
);
5462 kfree(table
, table_size
);
5469 * This routine is used to update a process's jetsam priority position and stored user_data.
5470 * It is not used for the setting of memory limits, which is why the last 6 args to the
5471 * memorystatus_update() call are 0 or FALSE.
5475 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
5477 memorystatus_priority_properties_t mpp_entry
;
5479 /* Validate inputs */
5480 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
5484 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
5494 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
5499 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
, FALSE
);
5507 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
5509 memorystatus_memlimit_properties_t mmp_entry
;
5511 /* Validate inputs */
5512 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
5516 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
5519 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
5526 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
5527 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
5528 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
5529 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
5530 * to the task's ledgers via task_set_phys_footprint_limit().
5533 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
5535 memorystatus_memlimit_properties_t mmp_entry
;
5537 /* Validate inputs */
5538 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
5542 memset (&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
5544 proc_t p
= proc_find(pid
);
5550 * Get the active limit and attributes.
5551 * No locks taken since we hold a reference to the proc.
5554 if (p
->p_memstat_memlimit_active
> 0 ) {
5555 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
5557 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
5560 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
5561 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
5565 * Get the inactive limit and attributes
5567 if (p
->p_memstat_memlimit_inactive
<= 0) {
5568 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
5570 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
5572 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
5573 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
5577 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
5584 memorystatus_cmd_get_pressure_status(int32_t *retval
) {
5587 /* Need privilege for check */
5588 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
5593 /* Inherently racy, so it's not worth taking a lock here */
5594 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
5600 memorystatus_get_pressure_status_kdp() {
5601 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
5605 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
5607 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
5608 * So, with 2-level HWM preserving previous behavior will map as follows.
5609 * - treat the limit passed in as both an active and inactive limit.
5610 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
5612 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
5613 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
5614 * - so mapping is (active/non-fatal, inactive/non-fatal)
5616 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
5617 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
5618 * - so mapping is (active/fatal, inactive/fatal)
5622 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
) {
5624 memorystatus_memlimit_properties_t entry
;
5626 entry
.memlimit_active
= high_water_mark
;
5627 entry
.memlimit_active_attr
= 0;
5628 entry
.memlimit_inactive
= high_water_mark
;
5629 entry
.memlimit_inactive_attr
= 0;
5631 if (is_fatal_limit
== TRUE
) {
5632 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
5633 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
5636 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
5641 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
) {
5643 int32_t memlimit_active
;
5644 boolean_t memlimit_active_is_fatal
;
5645 int32_t memlimit_inactive
;
5646 boolean_t memlimit_inactive_is_fatal
;
5647 uint32_t valid_attrs
= 0;
5650 proc_t p
= proc_find(pid
);
5656 * Check for valid attribute flags.
5658 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
5659 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
5663 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
5669 * Setup the active memlimit properties
5671 memlimit_active
= entry
->memlimit_active
;
5672 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
5673 memlimit_active_is_fatal
= TRUE
;
5675 memlimit_active_is_fatal
= FALSE
;
5679 * Setup the inactive memlimit properties
5681 memlimit_inactive
= entry
->memlimit_inactive
;
5682 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
5683 memlimit_inactive_is_fatal
= TRUE
;
5685 memlimit_inactive_is_fatal
= FALSE
;
5689 * Setting a limit of <= 0 implies that the process has no
5690 * high-water-mark and has no per-task-limit. That means
5691 * the system_wide task limit is in place, which by the way,
5695 if (memlimit_active
<= 0) {
5697 * Enforce the fatal system_wide task limit while process is active.
5699 memlimit_active
= -1;
5700 memlimit_active_is_fatal
= TRUE
;
5703 if (memlimit_inactive
<= 0) {
5705 * Enforce the fatal system_wide task limit while process is inactive.
5707 memlimit_inactive
= -1;
5708 memlimit_inactive_is_fatal
= TRUE
;
5714 * Store the active limit variants in the proc.
5716 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
5719 * Store the inactive limit variants in the proc.
5721 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
5724 * Enforce appropriate limit variant by updating the cached values
5725 * and writing the ledger.
5726 * Limit choice is based on process active/inactive state.
5729 if (memorystatus_highwater_enabled
) {
5730 boolean_t trigger_exception
;
5732 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
5733 * Background limits are described via the inactive limit slots.
5736 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
5737 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
5739 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
5742 /* Enforce the limit by writing to the ledgers */
5743 assert(trigger_exception
== TRUE
);
5744 error
= (task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, trigger_exception
) == 0) ? 0 : EINVAL
;
5746 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
5747 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
5748 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
5749 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
5759 * Returns the jetsam priority (effective or requested) of the process
5760 * associated with this task.
5763 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
5766 if (effective_priority
) {
5767 return p
->p_memstat_effectivepriority
;
5769 return p
->p_memstat_requestedpriority
;
5777 * Evaluates active vs. inactive process state.
5778 * Processes that opt into dirty tracking are evaluated
5779 * based on clean vs dirty state.
5781 * clean ==> inactive
5783 * Process that do not opt into dirty tracking are
5784 * evalulated based on priority level.
5785 * Foreground or above ==> active
5786 * Below Foreground ==> inactive
5788 * Return: TRUE if active
5793 proc_jetsam_state_is_active_locked(proc_t p
) {
5795 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
5797 * process has opted into dirty tracking
5798 * active state is based on dirty vs. clean
5800 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
5803 * implies active state
5809 * implies inactive state
5813 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
5815 * process is Foreground or higher
5816 * implies active state
5821 * process found below Foreground
5822 * implies inactive state
5828 #endif /* CONFIG_JETSAM */
5831 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
) {
5838 /* Root only for now */
5839 if (!kauth_cred_issuser(kauth_cred_get())) {
5845 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
5850 switch (args
->command
) {
5851 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
5852 error
= memorystatus_cmd_get_priority_list(args
->buffer
, args
->buffersize
, ret
);
5855 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
5856 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
5858 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
5859 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
5861 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
5862 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
5864 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
5865 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
5867 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
5868 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
5870 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
5871 error
= memorystatus_cmd_get_pressure_status(ret
);
5873 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
5875 * This call does not distinguish between active and inactive limits.
5876 * Default behavior in 2-level HWM world is to set both.
5877 * Non-fatal limit is also assumed for both.
5879 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
5881 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
5883 * This call does not distinguish between active and inactive limits.
5884 * Default behavior in 2-level HWM world is to set both.
5885 * Fatal limit is also assumed for both.
5887 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
5890 #if DEVELOPMENT || DEBUG
5891 case MEMORYSTATUS_CMD_TEST_JETSAM
:
5892 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
) ? 0 : EINVAL
;
5894 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
5895 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
5897 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
5898 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
5900 #endif /* DEVELOPMENT || DEBUG */
5901 #endif /* CONFIG_JETSAM */
5902 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
5903 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
5904 error
= memorystatus_low_mem_privileged_listener(args
->command
);
5916 filt_memorystatusattach(struct knote
*kn
)
5918 kn
->kn_flags
|= EV_CLEAR
;
5919 return memorystatus_knote_register(kn
);
5923 filt_memorystatusdetach(struct knote
*kn
)
5925 memorystatus_knote_unregister(kn
);
5929 filt_memorystatus(struct knote
*kn __unused
, long hint
)
5933 case kMemorystatusNoPressure
:
5934 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
5935 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
5938 case kMemorystatusPressure
:
5939 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
5940 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
5941 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
5943 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
5945 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
5946 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
5950 case kMemorystatusLowSwap
:
5951 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
5952 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
5960 return (kn
->kn_fflags
!= 0);
5964 memorystatus_klist_lock(void) {
5965 lck_mtx_lock(&memorystatus_klist_mutex
);
5969 memorystatus_klist_unlock(void) {
5970 lck_mtx_unlock(&memorystatus_klist_mutex
);
5974 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
) {
5975 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
5976 klist_init(&memorystatus_klist
);
5980 memorystatus_knote_register(struct knote
*kn
) {
5983 memorystatus_klist_lock();
5985 if (kn
->kn_sfflags
& (NOTE_MEMORYSTATUS_PRESSURE_NORMAL
| NOTE_MEMORYSTATUS_PRESSURE_WARN
| NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
| NOTE_MEMORYSTATUS_LOW_SWAP
)) {
5987 KNOTE_ATTACH(&memorystatus_klist
, kn
);
5993 memorystatus_klist_unlock();
5999 memorystatus_knote_unregister(struct knote
*kn __unused
) {
6000 memorystatus_klist_lock();
6001 KNOTE_DETACH(&memorystatus_klist
, kn
);
6002 memorystatus_klist_unlock();
6007 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
6009 memorystatus_issue_pressure_kevent(boolean_t pressured
) {
6010 memorystatus_klist_lock();
6011 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
6012 memorystatus_klist_unlock();
6015 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
6019 /* Coalition support */
6021 /* sorting info for a particular priority bucket */
6022 typedef struct memstat_sort_info
{
6023 coalition_t msi_coal
;
6024 uint64_t msi_page_count
;
6027 } memstat_sort_info_t
;
6030 * qsort from smallest page count to largest page count
6032 * return < 0 for a < b
6036 static int memstat_asc_cmp(const void *a
, const void *b
)
6038 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
6039 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
6041 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
6045 * Return the number of pids rearranged during this sort.
6048 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
6050 #define MAX_SORT_PIDS 80
6051 #define MAX_COAL_LEADERS 10
6053 unsigned int b
= bucket_index
;
6057 coalition_t coal
= COALITION_NULL
;
6059 int total_pids_moved
= 0;
6063 * The system is typically under memory pressure when in this
6064 * path, hence, we want to avoid dynamic memory allocation.
6066 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
6067 pid_t pid_list
[MAX_SORT_PIDS
];
6069 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
6074 * Clear the array that holds coalition leader information
6076 for (i
=0; i
< MAX_COAL_LEADERS
; i
++) {
6077 leaders
[i
].msi_coal
= COALITION_NULL
;
6078 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
6079 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
6080 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
6083 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
6085 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
6086 if (nleaders
< MAX_COAL_LEADERS
) {
6087 int coal_ntasks
= 0;
6088 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
6089 leaders
[nleaders
].msi_coal
= coal
;
6090 leaders
[nleaders
].msi_page_count
= coal_page_count
;
6091 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
6092 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
6096 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
6097 * Abandoned coalitions will linger at the tail of the priority band
6098 * when this sort session ends.
6099 * TODO: should this be an assert?
6101 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
6102 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
6106 p
=memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
6109 if (nleaders
== 0) {
6110 /* Nothing to sort */
6115 * Sort the coalition leader array, from smallest coalition page count
6116 * to largest coalition page count. When inserted in the priority bucket,
6117 * smallest coalition is handled first, resulting in the last to be jetsammed.
6120 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
6124 for (i
= 0; i
< nleaders
; i
++) {
6125 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
6126 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
6127 leaders
[i
].msi_ntasks
);
6132 * During coalition sorting, processes in a priority band are rearranged
6133 * by being re-inserted at the head of the queue. So, when handling a
6134 * list, the first process that gets moved to the head of the queue,
6135 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
6137 * So, for example, the coalition leader is expected to jetsam last,
6138 * after its coalition members. Therefore, the coalition leader is
6139 * inserted at the head of the queue first.
6141 * After processing a coalition, the jetsam order is as follows:
6142 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
6146 * Coalition members are rearranged in the priority bucket here,
6147 * based on their coalition role.
6149 total_pids_moved
= 0;
6150 for (i
=0; i
< nleaders
; i
++) {
6152 /* a bit of bookkeeping */
6155 /* Coalition leaders are jetsammed last, so move into place first */
6156 pid_list
[0] = leaders
[i
].msi_pid
;
6157 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
6159 /* xpc services should jetsam after extensions */
6160 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
6161 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
6164 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
6165 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
6168 /* extensions should jetsam after unmarked processes */
6169 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
6170 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
6173 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
6174 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
6177 /* undefined coalition members should be the first to jetsam */
6178 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
6179 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
6182 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
6183 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
6187 if (pids_moved
== leaders
[i
].msi_ntasks
) {
6189 * All the pids in the coalition were found in this band.
6191 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
6192 pids_moved
, leaders
[i
].msi_ntasks
);
6193 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
6195 * Apparently new coalition members showed up during the sort?
6197 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
6198 pids_moved
, leaders
[i
].msi_ntasks
);
6201 * Apparently not all the pids in the coalition were found in this band?
6203 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
6204 pids_moved
, leaders
[i
].msi_ntasks
);
6208 total_pids_moved
+= pids_moved
;
6212 return(total_pids_moved
);
6217 * Traverse a list of pids, searching for each within the priority band provided.
6218 * If pid is found, move it to the front of the priority band.
6219 * Never searches outside the priority band provided.
6222 * bucket_index - jetsam priority band.
6223 * pid_list - pointer to a list of pids.
6224 * list_sz - number of pids in the list.
6226 * Pid list ordering is important in that,
6227 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
6228 * The sort_order is set by the coalition default.
6231 * the number of pids found and hence moved within the priority band.
6234 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
6236 memstat_bucket_t
*current_bucket
;
6240 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
6244 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
6248 current_bucket
= &memstat_bucket
[bucket_index
];
6249 for (i
=0; i
< list_sz
; i
++) {
6250 unsigned int b
= bucket_index
;
6252 proc_t aProc
= NULL
;
6256 list_index
= ((list_sz
- 1) - i
);
6257 aPid
= pid_list
[list_index
];
6259 /* never search beyond bucket_index provided */
6260 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
6262 if (p
->p_pid
== aPid
) {
6266 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
6269 if (aProc
== NULL
) {
6270 /* pid not found in this band, just skip it */
6273 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
6274 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
6280 #endif /* CONFIG_JETSAM */