2 * Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 #include <kern/sched_prim.h>
31 #include <kern/kalloc.h>
32 #include <kern/assert.h>
33 #include <kern/debug.h>
34 #include <kern/locks.h>
35 #include <kern/task.h>
36 #include <kern/thread.h>
37 #include <kern/host.h>
38 #include <kern/policy_internal.h>
40 #include <IOKit/IOBSD.h>
42 #include <libkern/libkern.h>
43 #include <mach/coalition.h>
44 #include <mach/mach_time.h>
45 #include <mach/task.h>
46 #include <mach/host_priv.h>
47 #include <mach/mach_host.h>
48 #include <pexpert/pexpert.h>
49 #include <sys/coalition.h>
50 #include <sys/kern_event.h>
52 #include <sys/proc_info.h>
53 #include <sys/reason.h>
54 #include <sys/signal.h>
55 #include <sys/signalvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
61 #include <vm/vm_pageout.h>
62 #include <vm/vm_protos.h>
65 #include <vm/vm_map.h>
66 #endif /* CONFIG_FREEZE */
68 #include <sys/kern_memorystatus.h>
70 #include <mach/machine/sdt.h>
72 /* For logging clarity */
73 static const char *jetsam_kill_cause_name
[] = {
75 "jettisoned" , /* kMemorystatusKilled */
76 "highwater" , /* kMemorystatusKilledHiwat */
77 "vnode-limit" , /* kMemorystatusKilledVnodes */
78 "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
79 "vm-thrashing" , /* kMemorystatusKilledVMThrashing */
80 "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
81 "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
82 "diagnostic" , /* kMemorystatusKilledDiagnostic */
83 "idle-exit" , /* kMemorystatusKilledIdleExit */
87 /* Does cause indicate vm or fc thrashing? */
89 is_thrashing(unsigned cause
)
92 case kMemorystatusKilledVMThrashing
:
93 case kMemorystatusKilledFCThrashing
:
100 /* Callback into vm_compressor.c to signal that thrashing has been mitigated. */
101 extern void vm_thrashing_jetsam_done(void);
102 #endif /* CONFIG_JETSAM */
104 /* These are very verbose printfs(), enable with
105 * MEMORYSTATUS_DEBUG_LOG
107 #if MEMORYSTATUS_DEBUG_LOG
108 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
110 if (cond) { printf(format, ##__VA_ARGS__); } \
113 #define MEMORYSTATUS_DEBUG(cond, format, ...)
117 * Active / Inactive limit support
118 * proc list must be locked
120 * The SET_*** macros are used to initialize a limit
121 * for the first time.
123 * The CACHE_*** macros are use to cache the limit that will
124 * soon be in effect down in the ledgers.
127 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
129 (p)->p_memstat_memlimit_active = (limit); \
130 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED; \
132 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
134 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
138 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
140 (p)->p_memstat_memlimit_inactive = (limit); \
141 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED; \
143 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
145 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
149 #define CACHE_ACTIVE_LIMITS_LOCKED(p, trigger_exception) \
151 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
152 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
153 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
155 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
157 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED) { \
158 trigger_exception = FALSE; \
160 trigger_exception = TRUE; \
164 #define CACHE_INACTIVE_LIMITS_LOCKED(p, trigger_exception) \
166 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
167 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
168 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
170 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
172 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED) { \
173 trigger_exception = FALSE; \
175 trigger_exception = TRUE; \
180 /* General tunables */
182 unsigned long delta_percentage
= 5;
183 unsigned long critical_threshold_percentage
= 5;
184 unsigned long idle_offset_percentage
= 5;
185 unsigned long pressure_threshold_percentage
= 15;
186 unsigned long freeze_threshold_percentage
= 50;
187 unsigned long policy_more_free_offset_percentage
= 5;
189 /* General memorystatus stuff */
191 struct klist memorystatus_klist
;
192 static lck_mtx_t memorystatus_klist_mutex
;
194 static void memorystatus_klist_lock(void);
195 static void memorystatus_klist_unlock(void);
197 static uint64_t memorystatus_sysprocs_idle_delay_time
= 0;
198 static uint64_t memorystatus_apps_idle_delay_time
= 0;
201 * Memorystatus kevents
204 static int filt_memorystatusattach(struct knote
*kn
);
205 static void filt_memorystatusdetach(struct knote
*kn
);
206 static int filt_memorystatus(struct knote
*kn
, long hint
);
207 static int filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
208 static int filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
210 struct filterops memorystatus_filtops
= {
211 .f_attach
= filt_memorystatusattach
,
212 .f_detach
= filt_memorystatusdetach
,
213 .f_event
= filt_memorystatus
,
214 .f_touch
= filt_memorystatustouch
,
215 .f_process
= filt_memorystatusprocess
,
219 kMemorystatusNoPressure
= 0x1,
220 kMemorystatusPressure
= 0x2,
221 kMemorystatusLowSwap
= 0x4,
222 kMemorystatusProcLimitWarn
= 0x8,
223 kMemorystatusProcLimitCritical
= 0x10
226 /* Idle guard handling */
228 static int32_t memorystatus_scheduled_idle_demotions_sysprocs
= 0;
229 static int32_t memorystatus_scheduled_idle_demotions_apps
= 0;
231 static thread_call_t memorystatus_idle_demotion_call
;
233 static void memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
);
234 static void memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
);
235 static void memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clean_state
);
236 static void memorystatus_reschedule_idle_demotion_locked(void);
238 static void memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
);
240 vm_pressure_level_t
convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
242 boolean_t
is_knote_registered_modify_task_pressure_bits(struct knote
*, int, task_t
, vm_pressure_level_t
, vm_pressure_level_t
);
243 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
);
244 void memorystatus_send_low_swap_note(void);
246 int memorystatus_wakeup
= 0;
248 unsigned int memorystatus_level
= 0;
250 static int memorystatus_list_count
= 0;
252 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
254 typedef struct memstat_bucket
{
255 TAILQ_HEAD(, proc
) list
;
259 memstat_bucket_t memstat_bucket
[MEMSTAT_BUCKET_COUNT
];
261 uint64_t memstat_idle_demotion_deadline
= 0;
263 int system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
264 int applications_aging_band
= JETSAM_PRIORITY_IDLE
;
266 #define isProcessInAgingBands(p) ((isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) || (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)))
267 #define isApp(p) (! (p->p_memstat_dirty & P_DIRTY_TRACK))
268 #define isSysProc(p) ((p->p_memstat_dirty & P_DIRTY_TRACK))
270 #define kJetsamAgingPolicyNone (0)
271 #define kJetsamAgingPolicyLegacy (1)
272 #define kJetsamAgingPolicySysProcsReclaimedFirst (2)
273 #define kJetsamAgingPolicyAppsReclaimedFirst (3)
274 #define kJetsamAgingPolicyMax kJetsamAgingPolicyAppsReclaimedFirst
276 unsigned int jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
278 extern int corpse_for_fatal_memkill
;
279 extern unsigned long total_corpses_count
;
280 extern void task_purge_all_corpses(void);
284 /* Keeping around for future use if we need a utility that can do this OR an app that needs a dynamic adjustment. */
287 sysctl_set_jetsam_aging_policy SYSCTL_HANDLER_ARGS
289 #pragma unused(oidp, arg1, arg2)
291 int error
= 0, val
= 0;
292 memstat_bucket_t
*old_bucket
= 0;
293 int old_system_procs_aging_band
= 0, new_system_procs_aging_band
= 0;
294 int old_applications_aging_band
= 0, new_applications_aging_band
= 0;
295 proc_t p
= NULL
, next_proc
= NULL
;
298 error
= sysctl_io_number(req
, jetsam_aging_policy
, sizeof(int), &val
, NULL
);
299 if (error
|| !req
->newptr
) {
303 if ((val
< 0) || (val
> kJetsamAgingPolicyMax
)) {
304 printf("jetsam: ordering policy sysctl has invalid value - %d\n", val
);
309 * We need to synchronize with any potential adding/removal from aging bands
310 * that might be in progress currently. We use the proc_list_lock() just for
311 * consistency with all the routines dealing with 'aging' processes. We need
312 * a lighterweight lock.
316 old_system_procs_aging_band
= system_procs_aging_band
;
317 old_applications_aging_band
= applications_aging_band
;
321 case kJetsamAgingPolicyNone
:
322 new_system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
323 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
326 case kJetsamAgingPolicyLegacy
:
328 * Legacy behavior where some daemons get a 10s protection once and only before the first clean->dirty->clean transition before going into IDLE band.
330 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
331 new_applications_aging_band
= JETSAM_PRIORITY_IDLE
;
334 case kJetsamAgingPolicySysProcsReclaimedFirst
:
335 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
336 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
339 case kJetsamAgingPolicyAppsReclaimedFirst
:
340 new_system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
341 new_applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
348 if (old_system_procs_aging_band
&& (old_system_procs_aging_band
!= new_system_procs_aging_band
)) {
350 old_bucket
= &memstat_bucket
[old_system_procs_aging_band
];
351 p
= TAILQ_FIRST(&old_bucket
->list
);
355 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
358 if (new_system_procs_aging_band
== JETSAM_PRIORITY_IDLE
) {
359 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
362 memorystatus_update_priority_locked(p
, new_system_procs_aging_band
, false, true);
370 if (old_applications_aging_band
&& (old_applications_aging_band
!= new_applications_aging_band
)) {
372 old_bucket
= &memstat_bucket
[old_applications_aging_band
];
373 p
= TAILQ_FIRST(&old_bucket
->list
);
377 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
380 if (new_applications_aging_band
== JETSAM_PRIORITY_IDLE
) {
381 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
384 memorystatus_update_priority_locked(p
, new_applications_aging_band
, false, true);
392 jetsam_aging_policy
= val
;
393 system_procs_aging_band
= new_system_procs_aging_band
;
394 applications_aging_band
= new_applications_aging_band
;
401 SYSCTL_PROC(_kern
, OID_AUTO
, set_jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RW
,
402 0, 0, sysctl_set_jetsam_aging_policy
, "I", "Jetsam Aging Policy");
406 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
408 #pragma unused(oidp, arg1, arg2)
410 int error
= 0, val
= 0, old_time_in_secs
= 0;
411 uint64_t old_time_in_ns
= 0;
413 absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time
, &old_time_in_ns
);
414 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
416 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
417 if (error
|| !req
->newptr
) {
421 if ((val
< 0) || (val
> INT32_MAX
)) {
422 printf("jetsam: new idle delay interval has invalid value.\n");
426 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
431 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_sysprocs_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
432 0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time
, "I", "Aging window for system processes");
436 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
438 #pragma unused(oidp, arg1, arg2)
440 int error
= 0, val
= 0, old_time_in_secs
= 0;
441 uint64_t old_time_in_ns
= 0;
443 absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time
, &old_time_in_ns
);
444 old_time_in_secs
= old_time_in_ns
/ NSEC_PER_SEC
;
446 error
= sysctl_io_number(req
, old_time_in_secs
, sizeof(int), &val
, NULL
);
447 if (error
|| !req
->newptr
) {
451 if ((val
< 0) || (val
> INT32_MAX
)) {
452 printf("jetsam: new idle delay interval has invalid value.\n");
456 nanoseconds_to_absolutetime((uint64_t)val
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
461 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_apps_idle_delay_time
, CTLTYPE_INT
|CTLFLAG_RW
,
462 0, 0, sysctl_jetsam_set_apps_idle_delay_time
, "I", "Aging window for applications");
464 SYSCTL_INT(_kern
, OID_AUTO
, jetsam_aging_policy
, CTLTYPE_INT
|CTLFLAG_RD
, &jetsam_aging_policy
, 0, "");
466 static unsigned int memorystatus_dirty_count
= 0;
468 SYSCTL_INT(_kern
, OID_AUTO
, max_task_pmem
, CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
, &max_task_footprint_mb
, 0, "");
472 memorystatus_get_level(__unused
struct proc
*p
, struct memorystatus_get_level_args
*args
, __unused
int *ret
)
474 user_addr_t level
= 0;
478 if (copyout(&memorystatus_level
, level
, sizeof(memorystatus_level
)) != 0) {
485 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
);
486 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
);
488 static void memorystatus_thread(void *param __unused
, wait_result_t wr __unused
);
492 static int memorystatus_highwater_enabled
= 1; /* Update the cached memlimit data. */
494 static boolean_t
proc_jetsam_state_is_active_locked(proc_t
);
495 static boolean_t
memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
496 static boolean_t
memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
);
503 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
);
505 static int memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
507 static int memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
);
509 static int memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
511 static int memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
);
513 int proc_get_memstat_priority(proc_t
, boolean_t
);
515 static boolean_t memorystatus_idle_snapshot
= 0;
517 unsigned int memorystatus_delta
= 0;
519 static unsigned int memorystatus_available_pages_critical_base
= 0;
520 //static unsigned int memorystatus_last_foreground_pressure_pages = (unsigned int)-1;
521 static unsigned int memorystatus_available_pages_critical_idle_offset
= 0;
523 /* Jetsam Loop Detection */
524 static boolean_t memorystatus_jld_enabled
= TRUE
; /* Enables jetsam loop detection on all devices */
525 static uint32_t memorystatus_jld_eval_period_msecs
= 0; /* Init pass sets this based on device memory size */
526 static int memorystatus_jld_eval_aggressive_count
= 3; /* Raise the priority max after 'n' aggressive loops */
527 static int memorystatus_jld_eval_aggressive_priority_band_max
= 15; /* Kill aggressively up through this band */
530 * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
531 * --- if aggressive jetsam kills an app in the FG band and gets back >=AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD memory, it will stop the aggressive march further into and up the jetsam bands.
534 * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
535 * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
537 * - If the app is still in the FG band and aggressive jetsam is needed again, there will be no stop-and-check the next time around.
539 * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
542 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD 25
543 boolean_t memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
544 boolean_t memorystatus_aggressive_jetsam_lenient
= FALSE
;
546 #if DEVELOPMENT || DEBUG
548 * Jetsam Loop Detection tunables.
551 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_period_msecs
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_period_msecs
, 0, "");
552 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_count
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_count
, 0, "");
553 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jld_eval_aggressive_priority_band_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jld_eval_aggressive_priority_band_max
, 0, "");
554 #endif /* DEVELOPMENT || DEBUG */
556 #if DEVELOPMENT || DEBUG
557 static unsigned int memorystatus_jetsam_panic_debug
= 0;
558 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic
= 0;
561 static unsigned int memorystatus_jetsam_policy
= kPolicyDefault
;
562 static unsigned int memorystatus_thread_wasted_wakeup
= 0;
564 static uint32_t kill_under_pressure_cause
= 0;
567 * default jetsam snapshot support
569 static memorystatus_jetsam_snapshot_t
*memorystatus_jetsam_snapshot
;
570 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
571 static unsigned int memorystatus_jetsam_snapshot_count
= 0;
572 static unsigned int memorystatus_jetsam_snapshot_max
= 0;
573 static uint64_t memorystatus_jetsam_snapshot_last_timestamp
= 0;
574 static uint64_t memorystatus_jetsam_snapshot_timeout
= 0;
575 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
578 * snapshot support for memstats collected at boot.
580 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot
;
582 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
);
583 static boolean_t
memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
);
584 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
);
586 static void memorystatus_clear_errors(void);
587 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
);
588 static void memorystatus_get_task_phys_footprint_page_counts(task_t task
,
589 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
590 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
591 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
592 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
);
594 static void memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
);
596 static uint32_t memorystatus_build_state(proc_t p
);
597 static void memorystatus_update_levels_locked(boolean_t critical_only
);
598 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
600 static boolean_t
memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
, int32_t *priority
, uint32_t *errors
);
601 static boolean_t
memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, int32_t priority_max
, uint32_t *errors
);
602 static boolean_t
memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
);
603 static boolean_t
memorystatus_kill_hiwat_proc(uint32_t *errors
);
605 static boolean_t
memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
);
607 /* Priority Band Sorting Routines */
608 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
);
609 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
);
610 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
);
611 static int memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
);
614 typedef int (*cmpfunc_t
)(const void *a
, const void *b
);
615 extern void qsort(void *a
, size_t n
, size_t es
, cmpfunc_t cmp
);
616 static int memstat_asc_cmp(const void *a
, const void *b
);
618 #endif /* CONFIG_JETSAM */
622 extern unsigned int vm_page_free_count
;
623 extern unsigned int vm_page_active_count
;
624 extern unsigned int vm_page_inactive_count
;
625 extern unsigned int vm_page_throttled_count
;
626 extern unsigned int vm_page_purgeable_count
;
627 extern unsigned int vm_page_wire_count
;
628 #if CONFIG_SECLUDED_MEMORY
629 extern unsigned int vm_page_secluded_count
;
630 #endif /* CONFIG_SECLUDED_MEMORY */
632 #if VM_PRESSURE_EVENTS
634 boolean_t
memorystatus_warn_process(pid_t pid
, boolean_t exceeded
);
636 vm_pressure_level_t memorystatus_vm_pressure_level
= kVMPressureNormal
;
638 #if CONFIG_MEMORYSTATUS
639 unsigned int memorystatus_available_pages
= (unsigned int)-1;
640 unsigned int memorystatus_available_pages_pressure
= 0;
641 unsigned int memorystatus_available_pages_critical
= 0;
642 unsigned int memorystatus_frozen_count
= 0;
643 unsigned int memorystatus_suspended_count
= 0;
644 unsigned int memorystatus_policy_more_free_offset_pages
= 0;
647 * We use this flag to signal if we have any HWM offenders
648 * on the system. This way we can reduce the number of wakeups
649 * of the memorystatus_thread when the system is between the
650 * "pressure" and "critical" threshold.
652 * The (re-)setting of this variable is done without any locks
653 * or synchronization simply because it is not possible (currently)
654 * to keep track of HWM offenders that drop down below their memory
655 * limit and/or exit. So, we choose to burn a couple of wasted wakeups
656 * by allowing the unguarded modification of this variable.
658 boolean_t memorystatus_hwm_candidates
= 0;
660 static int memorystatus_send_note(int event_code
, void *data
, size_t data_length
);
661 #endif /* CONFIG_MEMORYSTATUS */
663 #endif /* VM_PRESSURE_EVENTS */
666 #if DEVELOPMENT || DEBUG
668 lck_grp_attr_t
*disconnect_page_mappings_lck_grp_attr
;
669 lck_grp_t
*disconnect_page_mappings_lck_grp
;
670 static lck_mtx_t disconnect_page_mappings_mutex
;
679 boolean_t memorystatus_freeze_enabled
= FALSE
;
680 int memorystatus_freeze_wakeup
= 0;
682 lck_grp_attr_t
*freezer_lck_grp_attr
;
683 lck_grp_t
*freezer_lck_grp
;
684 static lck_mtx_t freezer_mutex
;
686 static inline boolean_t
memorystatus_can_freeze_processes(void);
687 static boolean_t
memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
);
689 static void memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
);
692 static unsigned int memorystatus_freeze_threshold
= 0;
694 static unsigned int memorystatus_freeze_pages_min
= 0;
695 static unsigned int memorystatus_freeze_pages_max
= 0;
697 static unsigned int memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
699 static unsigned int memorystatus_freeze_daily_mb_max
= FREEZE_DAILY_MB_MAX_DEFAULT
;
702 static uint64_t memorystatus_freeze_count
= 0;
703 static uint64_t memorystatus_freeze_pageouts
= 0;
706 static throttle_interval_t throttle_intervals
[] = {
707 { 60, 8, 0, 0, { 0, 0 }, FALSE
}, /* 1 hour intermediate interval, 8x burst */
708 { 24 * 60, 1, 0, 0, { 0, 0 }, FALSE
}, /* 24 hour long interval, no burst */
711 static uint64_t memorystatus_freeze_throttle_count
= 0;
713 static unsigned int memorystatus_suspended_footprint_total
= 0; /* pages */
715 extern uint64_t vm_swap_get_free_space(void);
717 static boolean_t
memorystatus_freeze_update_throttle();
719 #endif /* CONFIG_FREEZE */
723 extern struct knote
*vm_find_knote_from_pid(pid_t
, struct klist
*);
725 #if DEVELOPMENT || DEBUG
727 static unsigned int memorystatus_debug_dump_this_bucket
= 0;
730 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index
)
734 int ledger_limit
= 0;
735 unsigned int b
= bucket_index
;
736 boolean_t traverse_all_buckets
= FALSE
;
738 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
739 traverse_all_buckets
= TRUE
;
742 traverse_all_buckets
= FALSE
;
747 * footprint reported in [pages / MB ]
748 * limits reported as:
749 * L-limit proc's Ledger limit
750 * C-limit proc's Cached limit, should match Ledger
751 * A-limit proc's Active limit
752 * IA-limit proc's Inactive limit
753 * F==Fatal, NF==NonFatal
756 printf("memorystatus_debug_dump ***START*(PAGE_SIZE_64=%llu)**\n", PAGE_SIZE_64
);
757 printf("bucket [pid] [pages / MB] [state] [EP / RP] dirty deadline [L-limit / C-limit / A-limit / IA-limit] name\n");
758 p
= memorystatus_get_first_proc_locked(&b
, traverse_all_buckets
);
760 bytes
= get_task_phys_footprint(p
->task
);
761 task_get_phys_footprint_limit(p
->task
, &ledger_limit
);
762 printf("%2d [%5d] [%5lld /%3lldMB] 0x%-8x [%2d / %2d] 0x%-3x %10lld [%3d / %3d%s / %3d%s / %3d%s] %s\n",
764 (bytes
/ PAGE_SIZE_64
), /* task's footprint converted from bytes to pages */
765 (bytes
/ (1024ULL * 1024ULL)), /* task's footprint converted from bytes to MB */
766 p
->p_memstat_state
, p
->p_memstat_effectivepriority
, p
->p_memstat_requestedpriority
, p
->p_memstat_dirty
, p
->p_memstat_idledeadline
,
768 p
->p_memstat_memlimit
,
769 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"),
770 p
->p_memstat_memlimit_active
,
771 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
? "F " : "NF"),
772 p
->p_memstat_memlimit_inactive
,
773 (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
? "F " : "NF"),
774 (*p
->p_name
? p
->p_name
: "unknown"));
775 p
= memorystatus_get_next_proc_locked(&b
, p
, traverse_all_buckets
);
777 printf("memorystatus_debug_dump ***END***\n");
781 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
783 #pragma unused(oidp, arg2)
784 int bucket_index
= 0;
786 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
787 if (error
|| !req
->newptr
) {
790 error
= SYSCTL_IN(req
, &bucket_index
, sizeof(int));
791 if (error
|| !req
->newptr
) {
794 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
796 * All jetsam buckets will be dumped.
800 * Only a single bucket will be dumped.
805 memorystatus_debug_dump_bucket_locked(bucket_index
);
807 memorystatus_debug_dump_this_bucket
= bucket_index
;
812 * Debug aid to look at jetsam buckets and proc jetsam fields.
813 * Use this sysctl to act on a particular jetsam bucket.
814 * Writing the sysctl triggers the dump.
815 * Usage: sysctl kern.memorystatus_debug_dump_this_bucket=<bucket_index>
818 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_debug_dump_this_bucket
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_debug_dump_this_bucket
, 0, sysctl_memorystatus_debug_dump_bucket
, "I", "");
821 /* Debug aid to aid determination of limit */
824 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
826 #pragma unused(oidp, arg2)
829 int error
, enable
= 0;
831 error
= SYSCTL_OUT(req
, arg1
, sizeof(int));
832 if (error
|| !req
->newptr
) {
836 error
= SYSCTL_IN(req
, &enable
, sizeof(int));
837 if (error
|| !req
->newptr
) {
841 if (!(enable
== 0 || enable
== 1)) {
847 p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
849 boolean_t trigger_exception
;
853 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
854 * Background limits are described via the inactive limit slots.
857 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
858 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
860 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
865 * Disabling limits does not touch the stored variants.
866 * Set the cached limit fields to system_wide defaults.
868 p
->p_memstat_memlimit
= -1;
869 p
->p_memstat_state
|= P_MEMSTAT_FATAL_MEMLIMIT
;
870 trigger_exception
= TRUE
;
874 * Enforce the cached limit by writing to the ledger.
876 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, trigger_exception
);
878 p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
881 memorystatus_highwater_enabled
= enable
;
889 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_highwater_enabled
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_highwater_enabled
, 0, sysctl_memorystatus_highwater_enable
, "I", "");
891 #if VM_PRESSURE_EVENTS
894 * This routine is used for targeted notifications
895 * regardless of system memory pressure.
896 * "memnote" is the current user.
900 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
902 #pragma unused(arg1, arg2)
904 int error
= 0, pid
= 0;
905 struct knote
*kn
= NULL
;
906 boolean_t found_knote
= FALSE
;
907 int fflags
= 0; /* filter flags for EVFILT_MEMORYSTATUS */
910 error
= sysctl_handle_quad(oidp
, &value
, 0, req
);
911 if (error
|| !req
->newptr
)
915 * Find the pid in the low 32 bits of value passed in.
917 pid
= (int)(value
& 0xFFFFFFFF);
920 * Find notification in the high 32 bits of the value passed in.
922 fflags
= (int)((value
>> 32) & 0xFFFFFFFF);
925 * For backwards compatibility, when no notification is
926 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
929 fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
930 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
934 * See event.h ... fflags for EVFILT_MEMORYSTATUS
936 if (!((fflags
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
)||
937 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) ||
938 (fflags
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) ||
939 (fflags
== NOTE_MEMORYSTATUS_LOW_SWAP
) ||
940 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) ||
941 (fflags
== NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
))) {
943 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags
);
949 * Forcibly send pid a memorystatus notification.
952 memorystatus_klist_lock();
954 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
955 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
956 pid_t knote_pid
= knote_proc
->p_pid
;
958 if (knote_pid
== pid
) {
960 * Forcibly send this pid a memorystatus notification.
962 kn
->kn_fflags
= fflags
;
968 KNOTE(&memorystatus_klist
, 0);
969 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value
, fflags
, pid
);
972 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value
, fflags
, pid
);
976 memorystatus_klist_unlock();
981 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_send
, CTLTYPE_QUAD
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
982 0, 0, &sysctl_memorystatus_vm_pressure_send
, "Q", "");
984 #endif /* VM_PRESSURE_EVENTS */
988 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_idle_snapshot
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_idle_snapshot
, 0, "");
990 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages
, 0, "");
991 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical
, 0, "");
992 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_base
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_base
, 0, "");
993 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_critical_idle_offset
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_critical_idle_offset
, 0, "");
994 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_policy_more_free_offset_pages
, CTLFLAG_RW
, &memorystatus_policy_more_free_offset_pages
, 0, "");
996 /* Diagnostic code */
999 kJetsamDiagnosticModeNone
= 0,
1000 kJetsamDiagnosticModeAll
= 1,
1001 kJetsamDiagnosticModeStopAtFirstActive
= 2,
1002 kJetsamDiagnosticModeCount
1003 } jetsam_diagnostic_mode
= kJetsamDiagnosticModeNone
;
1005 static int jetsam_diagnostic_suspended_one_active_proc
= 0;
1008 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1010 #pragma unused(arg1, arg2)
1012 const char *diagnosticStrings
[] = {
1013 "jetsam: diagnostic mode: resetting critical level.",
1014 "jetsam: diagnostic mode: will examine all processes",
1015 "jetsam: diagnostic mode: will stop at first active process"
1018 int error
, val
= jetsam_diagnostic_mode
;
1019 boolean_t changed
= FALSE
;
1021 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
1022 if (error
|| !req
->newptr
)
1024 if ((val
< 0) || (val
>= kJetsamDiagnosticModeCount
)) {
1025 printf("jetsam: diagnostic mode: invalid value - %d\n", val
);
1031 if ((unsigned int) val
!= jetsam_diagnostic_mode
) {
1032 jetsam_diagnostic_mode
= val
;
1034 memorystatus_jetsam_policy
&= ~kPolicyDiagnoseActive
;
1036 switch (jetsam_diagnostic_mode
) {
1037 case kJetsamDiagnosticModeNone
:
1038 /* Already cleared */
1040 case kJetsamDiagnosticModeAll
:
1041 memorystatus_jetsam_policy
|= kPolicyDiagnoseAll
;
1043 case kJetsamDiagnosticModeStopAtFirstActive
:
1044 memorystatus_jetsam_policy
|= kPolicyDiagnoseFirst
;
1047 /* Already validated */
1051 memorystatus_update_levels_locked(FALSE
);
1058 printf("%s\n", diagnosticStrings
[val
]);
1064 SYSCTL_PROC(_debug
, OID_AUTO
, jetsam_diagnostic_mode
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
|CTLFLAG_ANYBODY
,
1065 &jetsam_diagnostic_mode
, 0, sysctl_jetsam_diagnostic_mode
, "I", "Jetsam Diagnostic Mode");
1067 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_jetsam_policy_offset_pages_diagnostic
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_jetsam_policy_offset_pages_diagnostic
, 0, "");
1069 #if VM_PRESSURE_EVENTS
1071 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_available_pages_pressure
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_available_pages_pressure
, 0, "");
1073 #endif /* VM_PRESSURE_EVENTS */
1075 #endif /* CONFIG_JETSAM */
1079 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_daily_mb_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_daily_mb_max
, 0, "");
1081 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_threshold
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_threshold
, 0, "");
1083 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_min
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_min
, 0, "");
1084 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_pages_max
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_pages_max
, 0, "");
1086 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_count
, "");
1087 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_pageouts
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_pageouts
, "");
1088 SYSCTL_QUAD(_kern
, OID_AUTO
, memorystatus_freeze_throttle_count
, CTLFLAG_RD
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_count
, "");
1089 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_min_processes
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_suspended_threshold
, 0, "");
1091 boolean_t memorystatus_freeze_throttle_enabled
= TRUE
;
1092 SYSCTL_UINT(_kern
, OID_AUTO
, memorystatus_freeze_throttle_enabled
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_freeze_throttle_enabled
, 0, "");
1095 * Manual trigger of freeze and thaw for dev / debug kernels only.
1098 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1100 #pragma unused(arg1, arg2)
1104 if (memorystatus_freeze_enabled
== FALSE
) {
1108 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1109 if (error
|| !req
->newptr
)
1113 vm_pageout_anonymous_pages();
1118 lck_mtx_lock(&freezer_mutex
);
1122 uint32_t purgeable
, wired
, clean
, dirty
;
1124 uint32_t max_pages
= 0;
1126 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
1128 unsigned int avail_swap_space
= 0; /* in pages. */
1131 * Freezer backed by the compressor and swap file(s)
1132 * while will hold compressed data.
1134 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
1136 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
1140 * We only have the compressor without any swap.
1142 max_pages
= UINT32_MAX
- 1;
1145 error
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
1151 lck_mtx_unlock(&freezer_mutex
);
1155 lck_mtx_unlock(&freezer_mutex
);
1159 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_freeze
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1160 0, 0, &sysctl_memorystatus_freeze
, "I", "");
1163 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1165 #pragma unused(arg1, arg2)
1170 if (memorystatus_freeze_enabled
== FALSE
) {
1174 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1175 if (error
|| !req
->newptr
)
1180 error
= task_thaw(p
->task
);
1191 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_thaw
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1192 0, 0, &sysctl_memorystatus_available_pages_thaw
, "I", "");
1194 #endif /* CONFIG_FREEZE */
1196 #endif /* DEVELOPMENT || DEBUG */
1198 extern kern_return_t
kernel_thread_start_priority(thread_continue_t continuation
,
1201 thread_t
*new_thread
);
1203 #if DEVELOPMENT || DEBUG
1206 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1208 #pragma unused(arg1, arg2)
1209 int error
= 0, pid
= 0;
1212 error
= sysctl_handle_int(oidp
, &pid
, 0, req
);
1213 if (error
|| !req
->newptr
)
1216 lck_mtx_lock(&disconnect_page_mappings_mutex
);
1219 vm_pageout_disconnect_all_pages();
1224 error
= task_disconnect_page_mappings(p
->task
);
1233 lck_mtx_unlock(&disconnect_page_mappings_mutex
);
1238 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_disconnect_page_mappings
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
1239 0, 0, &sysctl_memorystatus_disconnect_page_mappings
, "I", "");
1241 #endif /* DEVELOPMENT || DEBUG */
1247 * Picks the sorting routine for a given jetsam priority band.
1250 * bucket_index - jetsam priority band to be sorted.
1251 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1252 * Currently sort_order is only meaningful when handling
1259 static int memorystatus_sort_bucket(unsigned int bucket_index
, int sort_order
)
1261 int coal_sort_order
;
1264 * Verify the jetsam priority
1266 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1270 #if DEVELOPMENT || DEBUG
1271 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1272 coal_sort_order
= COALITION_SORT_DEFAULT
;
1274 coal_sort_order
= sort_order
; /* only used for testing scenarios */
1277 /* Verify default */
1278 if (sort_order
== JETSAM_SORT_DEFAULT
) {
1279 coal_sort_order
= COALITION_SORT_DEFAULT
;
1286 switch (bucket_index
) {
1287 case JETSAM_PRIORITY_FOREGROUND
:
1288 if (memorystatus_sort_by_largest_coalition_locked(bucket_index
, coal_sort_order
) == 0) {
1290 * Fall back to per process sorting when zero coalitions are found.
1292 memorystatus_sort_by_largest_process_locked(bucket_index
);
1296 memorystatus_sort_by_largest_process_locked(bucket_index
);
1305 * Sort processes by size for a single jetsam bucket.
1308 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index
)
1310 proc_t p
= NULL
, insert_after_proc
= NULL
, max_proc
= NULL
;
1311 proc_t next_p
= NULL
, prev_max_proc
= NULL
;
1312 uint32_t pages
= 0, max_pages
= 0;
1313 memstat_bucket_t
*current_bucket
;
1315 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
1319 current_bucket
= &memstat_bucket
[bucket_index
];
1321 p
= TAILQ_FIRST(¤t_bucket
->list
);
1324 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1329 while ((next_p
= TAILQ_NEXT(p
, p_memstat_list
)) != NULL
) {
1330 /* traversing list until we find next largest process */
1332 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
1333 if (pages
> max_pages
) {
1339 if (prev_max_proc
!= max_proc
) {
1340 /* found a larger process, place it in the list */
1341 TAILQ_REMOVE(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1342 if (insert_after_proc
== NULL
) {
1343 TAILQ_INSERT_HEAD(¤t_bucket
->list
, max_proc
, p_memstat_list
);
1345 TAILQ_INSERT_AFTER(¤t_bucket
->list
, insert_after_proc
, max_proc
, p_memstat_list
);
1347 prev_max_proc
= max_proc
;
1350 insert_after_proc
= max_proc
;
1352 p
= TAILQ_NEXT(max_proc
, p_memstat_list
);
1356 #endif /* CONFIG_JETSAM */
1358 static proc_t
memorystatus_get_first_proc_locked(unsigned int *bucket_index
, boolean_t search
) {
1359 memstat_bucket_t
*current_bucket
;
1362 if ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
) {
1366 current_bucket
= &memstat_bucket
[*bucket_index
];
1367 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1368 if (!next_p
&& search
) {
1369 while (!next_p
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1370 current_bucket
= &memstat_bucket
[*bucket_index
];
1371 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1378 static proc_t
memorystatus_get_next_proc_locked(unsigned int *bucket_index
, proc_t p
, boolean_t search
) {
1379 memstat_bucket_t
*current_bucket
;
1382 if (!p
|| ((*bucket_index
) >= MEMSTAT_BUCKET_COUNT
)) {
1386 next_p
= TAILQ_NEXT(p
, p_memstat_list
);
1387 while (!next_p
&& search
&& (++(*bucket_index
) < MEMSTAT_BUCKET_COUNT
)) {
1388 current_bucket
= &memstat_bucket
[*bucket_index
];
1389 next_p
= TAILQ_FIRST(¤t_bucket
->list
);
1395 __private_extern__
void
1396 memorystatus_init(void)
1398 thread_t thread
= THREAD_NULL
;
1399 kern_return_t result
;
1403 memorystatus_freeze_pages_min
= FREEZE_PAGES_MIN
;
1404 memorystatus_freeze_pages_max
= FREEZE_PAGES_MAX
;
1407 #if DEVELOPMENT || DEBUG
1408 disconnect_page_mappings_lck_grp_attr
= lck_grp_attr_alloc_init();
1409 disconnect_page_mappings_lck_grp
= lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr
);
1411 lck_mtx_init(&disconnect_page_mappings_mutex
, disconnect_page_mappings_lck_grp
, NULL
);
1414 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_sysprocs_idle_delay_time
);
1415 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS
* NSEC_PER_SEC
, &memorystatus_apps_idle_delay_time
);
1418 for (i
= 0; i
< MEMSTAT_BUCKET_COUNT
; i
++) {
1419 TAILQ_INIT(&memstat_bucket
[i
].list
);
1420 memstat_bucket
[i
].count
= 0;
1423 memorystatus_idle_demotion_call
= thread_call_allocate((thread_call_func_t
)memorystatus_perform_idle_demotion
, NULL
);
1425 /* Apply overrides */
1426 PE_get_default("kern.jetsam_delta", &delta_percentage
, sizeof(delta_percentage
));
1427 if (delta_percentage
== 0) {
1428 delta_percentage
= 5;
1430 assert(delta_percentage
< 100);
1431 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage
, sizeof(critical_threshold_percentage
));
1432 assert(critical_threshold_percentage
< 100);
1433 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage
, sizeof(idle_offset_percentage
));
1434 assert(idle_offset_percentage
< 100);
1435 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage
, sizeof(pressure_threshold_percentage
));
1436 assert(pressure_threshold_percentage
< 100);
1437 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage
, sizeof(freeze_threshold_percentage
));
1438 assert(freeze_threshold_percentage
< 100);
1440 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy
,
1441 sizeof (jetsam_aging_policy
))) {
1443 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy
,
1444 sizeof(jetsam_aging_policy
))) {
1446 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1450 if (jetsam_aging_policy
> kJetsamAgingPolicyMax
) {
1451 jetsam_aging_policy
= kJetsamAgingPolicyLegacy
;
1454 switch (jetsam_aging_policy
) {
1456 case kJetsamAgingPolicyNone
:
1457 system_procs_aging_band
= JETSAM_PRIORITY_IDLE
;
1458 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1461 case kJetsamAgingPolicyLegacy
:
1463 * Legacy behavior where some daemons get a 10s protection once
1464 * AND only before the first clean->dirty->clean transition before
1465 * going into IDLE band.
1467 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1468 applications_aging_band
= JETSAM_PRIORITY_IDLE
;
1471 case kJetsamAgingPolicySysProcsReclaimedFirst
:
1472 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1473 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1476 case kJetsamAgingPolicyAppsReclaimedFirst
:
1477 system_procs_aging_band
= JETSAM_PRIORITY_AGING_BAND2
;
1478 applications_aging_band
= JETSAM_PRIORITY_AGING_BAND1
;
1486 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1487 * band and must be below it in priority. This is so that we don't have to make
1488 * our 'aging' code worry about a mix of processes, some of which need to age
1489 * and some others that need to stay elevated in the jetsam bands.
1491 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> system_procs_aging_band
);
1492 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE
> applications_aging_band
);
1495 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1496 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof (memorystatus_idle_snapshot
))) {
1497 /* ...no boot-arg, so check the device tree */
1498 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot
, sizeof(memorystatus_idle_snapshot
));
1501 memorystatus_delta
= delta_percentage
* atop_64(max_mem
) / 100;
1502 memorystatus_available_pages_critical_idle_offset
= idle_offset_percentage
* atop_64(max_mem
) / 100;
1503 memorystatus_available_pages_critical_base
= (critical_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1504 memorystatus_policy_more_free_offset_pages
= (policy_more_free_offset_percentage
/ delta_percentage
) * memorystatus_delta
;
1506 memorystatus_jetsam_snapshot_max
= maxproc
;
1507 memorystatus_jetsam_snapshot
=
1508 (memorystatus_jetsam_snapshot_t
*)kalloc(sizeof(memorystatus_jetsam_snapshot_t
) +
1509 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_max
);
1510 if (!memorystatus_jetsam_snapshot
) {
1511 panic("Could not allocate memorystatus_jetsam_snapshot");
1514 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS
* NSEC_PER_SEC
, &memorystatus_jetsam_snapshot_timeout
);
1516 memset(&memorystatus_at_boot_snapshot
, 0, sizeof(memorystatus_jetsam_snapshot_t
));
1518 /* No contention at this point */
1519 memorystatus_update_levels_locked(FALSE
);
1521 /* Jetsam Loop Detection */
1522 if (max_mem
<= (512 * 1024 * 1024)) {
1523 /* 512 MB devices */
1524 memorystatus_jld_eval_period_msecs
= 8000; /* 8000 msecs == 8 second window */
1526 /* 1GB and larger devices */
1527 memorystatus_jld_eval_period_msecs
= 6000; /* 6000 msecs == 6 second window */
1532 memorystatus_freeze_threshold
= (freeze_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
1535 result
= kernel_thread_start_priority(memorystatus_thread
, NULL
, 95 /* MAXPRI_KERNEL */, &thread
);
1536 if (result
== KERN_SUCCESS
) {
1537 thread_deallocate(thread
);
1539 panic("Could not create memorystatus_thread");
1543 /* Centralised for the purposes of allowing panic-on-jetsam */
1545 vm_run_compactor(void);
1548 * The jetsam no frills kill call
1549 * Return: 0 on success
1550 * error code on failure (EINVAL...)
1553 jetsam_do_kill(proc_t p
, int jetsam_flags
, os_reason_t jetsam_reason
) {
1555 error
= exit_with_reason(p
, W_EXITCODE(0, SIGKILL
), (int *)NULL
, FALSE
, FALSE
, jetsam_flags
, jetsam_reason
);
1560 * Wrapper for processes exiting with memorystatus details
1563 memorystatus_do_kill(proc_t p
, uint32_t cause
, os_reason_t jetsam_reason
) {
1566 __unused pid_t victim_pid
= p
->p_pid
;
1568 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_START
,
1569 victim_pid
, cause
, vm_page_free_count
, 0, 0);
1571 DTRACE_MEMORYSTATUS3(memorystatus_do_kill
, proc_t
, p
, os_reason_t
, jetsam_reason
, uint32_t, cause
);
1572 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1573 if (memorystatus_jetsam_panic_debug
& (1 << cause
)) {
1574 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause
);
1577 #pragma unused(cause)
1579 int jetsam_flags
= P_LTERM_JETSAM
;
1581 case kMemorystatusKilledHiwat
: jetsam_flags
|= P_JETSAM_HIWAT
; break;
1582 case kMemorystatusKilledVnodes
: jetsam_flags
|= P_JETSAM_VNODE
; break;
1583 case kMemorystatusKilledVMPageShortage
: jetsam_flags
|= P_JETSAM_VMPAGESHORTAGE
; break;
1584 case kMemorystatusKilledVMThrashing
: jetsam_flags
|= P_JETSAM_VMTHRASHING
; break;
1585 case kMemorystatusKilledFCThrashing
: jetsam_flags
|= P_JETSAM_FCTHRASHING
; break;
1586 case kMemorystatusKilledPerProcessLimit
: jetsam_flags
|= P_JETSAM_PID
; break;
1587 case kMemorystatusKilledIdleExit
: jetsam_flags
|= P_JETSAM_IDLEEXIT
; break;
1589 error
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
1591 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DO_KILL
)) | DBG_FUNC_END
,
1592 victim_pid
, cause
, vm_page_free_count
, error
, 0);
1596 return (error
== 0);
1604 memorystatus_check_levels_locked(void) {
1607 memorystatus_update_levels_locked(TRUE
);
1612 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1613 * For an application: that means no longer in the FG band
1614 * For a daemon: that means no longer in its 'requested' jetsam priority band
1618 memorystatus_update_inactive_jetsam_priority_band(pid_t pid
, uint32_t op_flags
, boolean_t effective_now
)
1621 boolean_t enable
= FALSE
;
1624 if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
) {
1626 } else if (op_flags
== MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
) {
1635 if ((enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) ||
1636 (!enable
&& ((p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) == 0))) {
1638 * No change in state.
1646 p
->p_memstat_state
|= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1647 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1649 if (effective_now
) {
1650 if (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1651 boolean_t trigger_exception
;
1652 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
1653 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, trigger_exception
);
1654 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_ELEVATED_INACTIVE
, FALSE
, FALSE
);
1657 if (isProcessInAgingBands(p
)) {
1658 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1663 p
->p_memstat_state
&= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
;
1664 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1666 if (effective_now
) {
1667 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_ELEVATED_INACTIVE
) {
1668 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1671 if (isProcessInAgingBands(p
)) {
1672 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
1690 memorystatus_perform_idle_demotion(__unused
void *spare1
, __unused
void *spare2
)
1693 uint64_t current_time
= 0, idle_delay_time
= 0;
1694 int demote_prio_band
= 0;
1695 memstat_bucket_t
*demotion_bucket
;
1697 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1699 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1701 current_time
= mach_absolute_time();
1705 demote_prio_band
= JETSAM_PRIORITY_IDLE
+ 1;
1707 for (; demote_prio_band
< JETSAM_PRIORITY_MAX
; demote_prio_band
++) {
1709 if (demote_prio_band
!= system_procs_aging_band
&& demote_prio_band
!= applications_aging_band
)
1712 demotion_bucket
= &memstat_bucket
[demote_prio_band
];
1713 p
= TAILQ_FIRST(&demotion_bucket
->list
);
1716 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p
->p_pid
);
1718 assert(p
->p_memstat_idledeadline
);
1720 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
1722 if (current_time
>= p
->p_memstat_idledeadline
) {
1724 if ((isSysProc(p
) &&
1725 ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) != P_DIRTY_IDLE_EXIT_ENABLED
)) || /* system proc marked dirty*/
1726 task_has_assertions((struct task
*)(p
->task
))) { /* has outstanding assertions which might indicate outstanding work too */
1727 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1729 p
->p_memstat_idledeadline
+= idle_delay_time
;
1730 p
= TAILQ_NEXT(p
, p_memstat_list
);
1734 proc_t next_proc
= NULL
;
1736 next_proc
= TAILQ_NEXT(p
, p_memstat_list
);
1737 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
1739 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, false, true);
1746 // No further candidates
1753 memorystatus_reschedule_idle_demotion_locked();
1757 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_IDLE_DEMOTE
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
1761 memorystatus_schedule_idle_demotion_locked(proc_t p
, boolean_t set_state
)
1763 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1764 boolean_t present_in_apps_aging_bucket
= FALSE
;
1765 uint64_t idle_delay_time
= 0;
1767 if (jetsam_aging_policy
== kJetsamAgingPolicyNone
) {
1771 if (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
) {
1773 * This process isn't going to be making the trip to the lower bands.
1778 if (isProcessInAgingBands(p
)){
1780 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1781 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) != P_DIRTY_AGING_IN_PROGRESS
);
1784 if (isSysProc(p
) && system_procs_aging_band
) {
1785 present_in_sysprocs_aging_bucket
= TRUE
;
1787 } else if (isApp(p
) && applications_aging_band
) {
1788 present_in_apps_aging_bucket
= TRUE
;
1792 assert(!present_in_sysprocs_aging_bucket
);
1793 assert(!present_in_apps_aging_bucket
);
1795 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",
1796 p
->p_pid
, p
->p_memstat_dirty
, set_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1799 assert((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
);
1802 idle_delay_time
= (isSysProc(p
)) ? memorystatus_sysprocs_idle_delay_time
: memorystatus_apps_idle_delay_time
;
1805 p
->p_memstat_dirty
|= P_DIRTY_AGING_IN_PROGRESS
;
1806 p
->p_memstat_idledeadline
= mach_absolute_time() + idle_delay_time
;
1809 assert(p
->p_memstat_idledeadline
);
1811 if (isSysProc(p
) && present_in_sysprocs_aging_bucket
== FALSE
) {
1812 memorystatus_scheduled_idle_demotions_sysprocs
++;
1814 } else if (isApp(p
) && present_in_apps_aging_bucket
== FALSE
) {
1815 memorystatus_scheduled_idle_demotions_apps
++;
1820 memorystatus_invalidate_idle_demotion_locked(proc_t p
, boolean_t clear_state
)
1822 boolean_t present_in_sysprocs_aging_bucket
= FALSE
;
1823 boolean_t present_in_apps_aging_bucket
= FALSE
;
1825 if (!system_procs_aging_band
&& !applications_aging_band
) {
1829 if ((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0) {
1833 if (isProcessInAgingBands(p
)) {
1835 if (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) {
1836 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == P_DIRTY_AGING_IN_PROGRESS
);
1839 if (isSysProc(p
) && system_procs_aging_band
) {
1840 assert(p
->p_memstat_effectivepriority
== system_procs_aging_band
);
1841 assert(p
->p_memstat_idledeadline
);
1842 present_in_sysprocs_aging_bucket
= TRUE
;
1844 } else if (isApp(p
) && applications_aging_band
) {
1845 assert(p
->p_memstat_effectivepriority
== applications_aging_band
);
1846 assert(p
->p_memstat_idledeadline
);
1847 present_in_apps_aging_bucket
= TRUE
;
1851 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1852 p
->p_pid
, clear_state
, (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
));
1856 p
->p_memstat_idledeadline
= 0;
1857 p
->p_memstat_dirty
&= ~P_DIRTY_AGING_IN_PROGRESS
;
1860 if (isSysProc(p
) &&present_in_sysprocs_aging_bucket
== TRUE
) {
1861 memorystatus_scheduled_idle_demotions_sysprocs
--;
1862 assert(memorystatus_scheduled_idle_demotions_sysprocs
>= 0);
1864 } else if (isApp(p
) && present_in_apps_aging_bucket
== TRUE
) {
1865 memorystatus_scheduled_idle_demotions_apps
--;
1866 assert(memorystatus_scheduled_idle_demotions_apps
>= 0);
1869 assert((memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
) >= 0);
1873 memorystatus_reschedule_idle_demotion_locked(void) {
1874 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs
+ memorystatus_scheduled_idle_demotions_apps
)) {
1875 if (memstat_idle_demotion_deadline
) {
1876 /* Transitioned 1->0, so cancel next call */
1877 thread_call_cancel(memorystatus_idle_demotion_call
);
1878 memstat_idle_demotion_deadline
= 0;
1881 memstat_bucket_t
*demotion_bucket
;
1882 proc_t p
= NULL
, p1
= NULL
, p2
= NULL
;
1884 if (system_procs_aging_band
) {
1886 demotion_bucket
= &memstat_bucket
[system_procs_aging_band
];
1887 p1
= TAILQ_FIRST(&demotion_bucket
->list
);
1892 if (applications_aging_band
) {
1894 demotion_bucket
= &memstat_bucket
[applications_aging_band
];
1895 p2
= TAILQ_FIRST(&demotion_bucket
->list
);
1898 p
= (p1
->p_memstat_idledeadline
> p2
->p_memstat_idledeadline
) ? p2
: p1
;
1900 p
= (p1
== NULL
) ? p2
: p1
;
1908 assert(p
&& p
->p_memstat_idledeadline
);
1909 if (memstat_idle_demotion_deadline
!= p
->p_memstat_idledeadline
){
1910 thread_call_enter_delayed(memorystatus_idle_demotion_call
, p
->p_memstat_idledeadline
);
1911 memstat_idle_demotion_deadline
= p
->p_memstat_idledeadline
;
1922 memorystatus_add(proc_t p
, boolean_t locked
)
1924 memstat_bucket_t
*bucket
;
1926 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p
->p_pid
, p
->p_memstat_effectivepriority
);
1932 DTRACE_MEMORYSTATUS2(memorystatus_add
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
);
1934 /* Processes marked internal do not have priority tracked */
1935 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
1939 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
1941 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
1942 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
- 1);
1944 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
1945 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
- 1);
1947 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
1949 * Entering the idle band.
1950 * Record idle start time.
1952 p
->p_memstat_idle_start
= mach_absolute_time();
1955 TAILQ_INSERT_TAIL(&bucket
->list
, p
, p_memstat_list
);
1958 memorystatus_list_count
++;
1960 memorystatus_check_levels_locked();
1972 * Moves a process from one jetsam bucket to another.
1973 * which changes the LRU position of the process.
1975 * Monitors transition between buckets and if necessary
1976 * will update cached memory limits accordingly.
1978 * skip_demotion_check:
1979 * - if the 'jetsam aging policy' is NOT 'legacy':
1980 * When this flag is TRUE, it means we are going
1981 * to age the ripe processes out of the aging bands and into the
1982 * IDLE band and apply their inactive memory limits.
1984 * - if the 'jetsam aging policy' is 'legacy':
1985 * When this flag is TRUE, it might mean the above aging mechanism
1987 * It might be that we have a process that has used up its 'idle deferral'
1988 * stay that is given to it once per lifetime. And in this case, the process
1989 * won't be going through any aging codepaths. But we still need to apply
1990 * the right inactive limits and so we explicitly set this to TRUE if the
1991 * new priority for the process is the IDLE band.
1994 memorystatus_update_priority_locked(proc_t p
, int priority
, boolean_t head_insert
, boolean_t skip_demotion_check
)
1996 memstat_bucket_t
*old_bucket
, *new_bucket
;
1998 assert(priority
< MEMSTAT_BUCKET_COUNT
);
2000 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2001 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2005 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2006 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, head_insert
? "head" : "tail");
2008 DTRACE_MEMORYSTATUS3(memorystatus_update_priority
, proc_t
, p
, int32_t, p
->p_memstat_effectivepriority
, int, priority
);
2010 #if DEVELOPMENT || DEBUG
2011 if (priority
== JETSAM_PRIORITY_IDLE
&& /* if the process is on its way into the IDLE band */
2012 skip_demotion_check
== FALSE
&& /* and it isn't via the path that will set the INACTIVE memlimits */
2013 (p
->p_memstat_dirty
& P_DIRTY_TRACK
) && /* and it has 'DIRTY' tracking enabled */
2014 ((p
->p_memstat_memlimit
!= p
->p_memstat_memlimit_inactive
) || /* and we notice that the current limit isn't the right value (inactive) */
2015 ((p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) ? ( ! (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
)) : (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
)))) /* OR type (fatal vs non-fatal) */
2016 panic("memorystatus_update_priority_locked: on %s with 0x%x, prio: %d and %d\n", p
->p_name
, p
->p_memstat_state
, priority
, p
->p_memstat_memlimit
); /* then we must catch this */
2017 #endif /* DEVELOPMENT || DEBUG */
2019 old_bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2021 if (skip_demotion_check
== FALSE
) {
2025 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2026 * the processes from the aging bands and balancing the demotion counts.
2027 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2030 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2031 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2033 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2035 } else if (isApp(p
)) {
2038 * Check to see if the application is being lowered in jetsam priority. If so, and:
2039 * - it has an 'elevated inactive jetsam band' attribute, then put it in the JETSAM_PRIORITY_ELEVATED_INACTIVE band.
2040 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2043 if (priority
<= JETSAM_PRIORITY_ELEVATED_INACTIVE
&& (p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
2044 priority
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
2047 if (applications_aging_band
) {
2048 if (p
->p_memstat_effectivepriority
== applications_aging_band
) {
2049 assert(old_bucket
->count
== (memorystatus_scheduled_idle_demotions_apps
+ 1));
2052 if ((jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) && (priority
<= applications_aging_band
)) {
2053 assert(! (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
));
2054 priority
= applications_aging_band
;
2055 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2062 if ((system_procs_aging_band
&& (priority
== system_procs_aging_band
)) || (applications_aging_band
&& (priority
== applications_aging_band
))) {
2063 assert(p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
);
2066 TAILQ_REMOVE(&old_bucket
->list
, p
, p_memstat_list
);
2067 old_bucket
->count
--;
2069 new_bucket
= &memstat_bucket
[priority
];
2071 TAILQ_INSERT_HEAD(&new_bucket
->list
, p
, p_memstat_list
);
2073 TAILQ_INSERT_TAIL(&new_bucket
->list
, p
, p_memstat_list
);
2074 new_bucket
->count
++;
2076 if (memorystatus_highwater_enabled
) {
2077 boolean_t trigger_exception
;
2080 * If cached limit data is updated, then the limits
2081 * will be enforced by writing to the ledgers.
2083 boolean_t ledger_update_needed
= TRUE
;
2086 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
2087 * Background limits are described via the inactive limit slots.
2089 * Here, we must update the cached memory limit if the task
2090 * is transitioning between:
2091 * active <--> inactive
2094 * dirty <--> clean is ignored
2096 * We bypass non-idle processes that have opted into dirty tracking because
2097 * a move between buckets does not imply a transition between the
2098 * dirty <--> clean state.
2101 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
2103 if (skip_demotion_check
== TRUE
&& priority
== JETSAM_PRIORITY_IDLE
) {
2104 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2106 ledger_update_needed
= FALSE
;
2109 } else if ((priority
>= JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
< JETSAM_PRIORITY_FOREGROUND
)) {
2111 * inactive --> active
2113 * assign active state
2115 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2117 } else if ((priority
< JETSAM_PRIORITY_FOREGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
2119 * active --> inactive
2121 * assign inactive state
2123 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2126 * The transition between jetsam priority buckets apparently did
2127 * not affect active/inactive state.
2128 * This is not unusual... especially during startup when
2129 * processes are getting established in their respective bands.
2131 ledger_update_needed
= FALSE
;
2135 * Enforce the new limits by writing to the ledger
2137 if (ledger_update_needed
) {
2138 task_set_phys_footprint_limit_internal(p
->task
, (p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1, NULL
, trigger_exception
);
2140 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2141 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2142 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, priority
, p
->p_memstat_dirty
,
2143 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2148 * Record idle start or idle delta.
2150 if (p
->p_memstat_effectivepriority
== priority
) {
2152 * This process is not transitioning between
2153 * jetsam priority buckets. Do nothing.
2155 } else if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2158 * Transitioning out of the idle priority bucket.
2159 * Record idle delta.
2161 assert(p
->p_memstat_idle_start
!= 0);
2162 now
= mach_absolute_time();
2163 if (now
> p
->p_memstat_idle_start
) {
2164 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2166 } else if (priority
== JETSAM_PRIORITY_IDLE
) {
2168 * Transitioning into the idle priority bucket.
2169 * Record idle start.
2171 p
->p_memstat_idle_start
= mach_absolute_time();
2174 p
->p_memstat_effectivepriority
= priority
;
2176 #if CONFIG_SECLUDED_MEMORY
2177 if (secluded_for_apps
&&
2178 task_could_use_secluded_mem(p
->task
)) {
2179 task_set_can_use_secluded_mem(
2181 (priority
>= JETSAM_PRIORITY_FOREGROUND
));
2183 #endif /* CONFIG_SECLUDED_MEMORY */
2185 memorystatus_check_levels_locked();
2190 * Description: Update the jetsam priority and memory limit attributes for a given process.
2193 * p init this process's jetsam information.
2194 * priority The jetsam priority band
2195 * user_data user specific data, unused by the kernel
2196 * effective guards against race if process's update already occurred
2197 * update_memlimit When true we know this is the init step via the posix_spawn path.
2199 * memlimit_active Value in megabytes; The monitored footprint level while the
2200 * process is active. Exceeding it may result in termination
2201 * based on it's associated fatal flag.
2203 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2204 * this describes whether or not it should be immediately fatal.
2206 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2207 * process is inactive. Exceeding it may result in termination
2208 * based on it's associated fatal flag.
2210 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2211 * this describes whether or not it should be immediatly fatal.
2213 * memlimit_background This process has a high-water-mark while in the background.
2214 * No longer meaningful. Background limits are described via
2215 * the inactive slots. Flag is ignored.
2218 * Returns: 0 Success
2223 memorystatus_update(proc_t p
, int priority
, uint64_t user_data
, boolean_t effective
, boolean_t update_memlimit
,
2224 int32_t memlimit_active
, boolean_t memlimit_active_is_fatal
,
2225 int32_t memlimit_inactive
, boolean_t memlimit_inactive_is_fatal
,
2226 __unused boolean_t memlimit_background
)
2229 boolean_t head_insert
= false;
2231 MEMORYSTATUS_DEBUG(1, "memorystatus_update: changing (%s) pid %d: priority %d, user_data 0x%llx\n", (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
, priority
, user_data
);
2233 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_START
, p
->p_pid
, priority
, user_data
, effective
, 0);
2235 if (priority
== -1) {
2236 /* Use as shorthand for default priority */
2237 priority
= JETSAM_PRIORITY_DEFAULT
;
2238 } else if ((priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
2239 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2240 priority
= JETSAM_PRIORITY_IDLE
;
2241 } else if (priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
2242 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2243 priority
= JETSAM_PRIORITY_IDLE
;
2245 } else if ((priority
< 0) || (priority
>= MEMSTAT_BUCKET_COUNT
)) {
2253 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2255 if (effective
&& (p
->p_memstat_state
& P_MEMSTAT_PRIORITYUPDATED
)) {
2258 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p
->p_pid
);
2262 if ((p
->p_memstat_state
& P_MEMSTAT_TERMINATED
) || ((p
->p_listflag
& P_LIST_EXITED
) != 0)) {
2264 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2271 p
->p_memstat_state
|= P_MEMSTAT_PRIORITYUPDATED
;
2272 p
->p_memstat_userdata
= user_data
;
2273 p
->p_memstat_requestedpriority
= priority
;
2275 if (update_memlimit
) {
2276 boolean_t trigger_exception
;
2279 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2280 * Forked processes do not come through this path, so no ledger limits exist.
2281 * (That's why forked processes can consume unlimited memory.)
2284 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2285 p
->p_pid
, priority
, p
->p_memstat_dirty
,
2286 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2287 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2289 if (memlimit_background
) {
2292 * With 2-level HWM support, we no longer honor P_MEMSTAT_MEMLIMIT_BACKGROUND.
2293 * Background limits are described via the inactive limit slots.
2296 // p->p_memstat_state |= P_MEMSTAT_MEMLIMIT_BACKGROUND;
2298 #if DEVELOPMENT || DEBUG
2299 printf("memorystatus_update: WARNING %s[%d] set unused flag P_MEMSTAT_MEMLIMIT_BACKGROUND [A==%dMB %s] [IA==%dMB %s]\n",
2300 (*p
->p_name
? p
->p_name
: "unknown"), p
->p_pid
,
2301 memlimit_active
, (memlimit_active_is_fatal
? "F " : "NF"),
2302 memlimit_inactive
, (memlimit_inactive_is_fatal
? "F " : "NF"));
2303 #endif /* DEVELOPMENT || DEBUG */
2306 if (memlimit_active
<= 0) {
2308 * This process will have a system_wide task limit when active.
2309 * System_wide task limit is always fatal.
2310 * It's quite common to see non-fatal flag passed in here.
2311 * It's not an error, we just ignore it.
2315 * For backward compatibility with some unexplained launchd behavior,
2316 * we allow a zero sized limit. But we still enforce system_wide limit
2317 * when written to the ledgers.
2320 if (memlimit_active
< 0) {
2321 memlimit_active
= -1; /* enforces system_wide task limit */
2323 memlimit_active_is_fatal
= TRUE
;
2326 if (memlimit_inactive
<= 0) {
2328 * This process will have a system_wide task limit when inactive.
2329 * System_wide task limit is always fatal.
2332 memlimit_inactive
= -1;
2333 memlimit_inactive_is_fatal
= TRUE
;
2337 * Initialize the active limit variants for this process.
2339 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
2342 * Initialize the inactive limit variants for this process.
2344 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
2347 * Initialize the cached limits for target process.
2348 * When the target process is dirty tracked, it's typically
2349 * in a clean state. Non dirty tracked processes are
2350 * typically active (Foreground or above).
2351 * But just in case, we don't make assumptions...
2354 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2355 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2357 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2361 * Enforce the cached limit by writing to the ledger.
2363 if (memorystatus_highwater_enabled
) {
2365 assert(trigger_exception
== TRUE
);
2366 task_set_phys_footprint_limit_internal(p
->task
, ((p
->p_memstat_memlimit
> 0) ? p
->p_memstat_memlimit
: -1), NULL
, trigger_exception
);
2368 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2369 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2370 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), priority
, p
->p_memstat_dirty
,
2371 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2376 * We can't add to the aging bands buckets here.
2377 * But, we could be removing it from those buckets.
2378 * Check and take appropriate steps if so.
2381 if (isProcessInAgingBands(p
)) {
2383 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2384 memorystatus_update_priority_locked(p
, JETSAM_PRIORITY_IDLE
, FALSE
, TRUE
);
2386 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
&& priority
== JETSAM_PRIORITY_IDLE
) {
2388 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2389 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2390 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2391 * is any other aging policy, then we don't need to worry because all processes
2392 * will go through the aging bands and then the demotion thread will take care to
2393 * move them into the IDLE band and apply the required limits.
2395 memorystatus_update_priority_locked(p
, priority
, head_insert
, TRUE
);
2399 memorystatus_update_priority_locked(p
, priority
, head_insert
, FALSE
);
2405 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_UPDATE
) | DBG_FUNC_END
, ret
, 0, 0, 0, 0);
2411 memorystatus_remove(proc_t p
, boolean_t locked
)
2414 memstat_bucket_t
*bucket
;
2415 boolean_t reschedule
= FALSE
;
2417 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p
->p_pid
);
2423 assert(!(p
->p_memstat_state
& P_MEMSTAT_INTERNAL
));
2425 bucket
= &memstat_bucket
[p
->p_memstat_effectivepriority
];
2427 if (isSysProc(p
) && system_procs_aging_band
&& (p
->p_memstat_effectivepriority
== system_procs_aging_band
)) {
2429 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_sysprocs
);
2432 } else if (isApp(p
) && applications_aging_band
&& (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
2434 assert(bucket
->count
== memorystatus_scheduled_idle_demotions_apps
);
2442 if (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_IDLE
) {
2443 uint64_t now
= mach_absolute_time();
2444 if (now
> p
->p_memstat_idle_start
) {
2445 p
->p_memstat_idle_delta
= now
- p
->p_memstat_idle_start
;
2449 TAILQ_REMOVE(&bucket
->list
, p
, p_memstat_list
);
2452 memorystatus_list_count
--;
2454 /* If awaiting demotion to the idle band, clean up */
2456 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2457 memorystatus_reschedule_idle_demotion_locked();
2460 memorystatus_check_levels_locked();
2463 if (p
->p_memstat_state
& (P_MEMSTAT_FROZEN
)) {
2464 memorystatus_frozen_count
--;
2467 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
2468 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
2469 memorystatus_suspended_count
--;
2487 * Validate dirty tracking flags with process state.
2493 * The proc_list_lock is held by the caller.
2497 memorystatus_validate_track_flags(struct proc
*target_p
, uint32_t pcontrol
) {
2498 /* See that the process isn't marked for termination */
2499 if (target_p
->p_memstat_dirty
& P_DIRTY_TERMINATED
) {
2503 /* Idle exit requires that process be tracked */
2504 if ((pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) &&
2505 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2509 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2510 if ((pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) &&
2511 !(pcontrol
& PROC_DIRTY_TRACK
)) {
2515 /* Deferral is only relevant if idle exit is specified */
2516 if ((pcontrol
& PROC_DIRTY_DEFER
) &&
2517 !(pcontrol
& PROC_DIRTY_ALLOWS_IDLE_EXIT
)) {
2525 memorystatus_update_idle_priority_locked(proc_t p
) {
2528 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p
->p_pid
, p
->p_memstat_dirty
);
2530 assert(isSysProc(p
));
2532 if ((p
->p_memstat_dirty
& (P_DIRTY_IDLE_EXIT_ENABLED
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2534 priority
= (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) ? system_procs_aging_band
: JETSAM_PRIORITY_IDLE
;
2536 priority
= p
->p_memstat_requestedpriority
;
2539 if (priority
!= p
->p_memstat_effectivepriority
) {
2541 if ((jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) &&
2542 (priority
== JETSAM_PRIORITY_IDLE
)) {
2545 * This process is on its way into the IDLE band. The system is
2546 * using 'legacy' jetsam aging policy. That means, this process
2547 * has already used up its idle-deferral aging time that is given
2548 * once per its lifetime. So we need to set the INACTIVE limits
2549 * explicitly because it won't be going through the demotion paths
2550 * that take care to apply the limits appropriately.
2552 assert((p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) == 0);
2553 memorystatus_update_priority_locked(p
, priority
, false, true);
2556 memorystatus_update_priority_locked(p
, priority
, false, false);
2562 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
2563 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2564 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2565 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2567 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2568 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2569 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2570 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2571 * band. The deferral can be cleared early by clearing the appropriate flag.
2573 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2574 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2575 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2579 memorystatus_dirty_track(proc_t p
, uint32_t pcontrol
) {
2580 unsigned int old_dirty
;
2581 boolean_t reschedule
= FALSE
;
2582 boolean_t already_deferred
= FALSE
;
2583 boolean_t defer_now
= FALSE
;
2586 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_TRACK
),
2587 p
->p_pid
, p
->p_memstat_dirty
, pcontrol
, 0, 0);
2591 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2593 * Process is on its way out.
2599 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2604 if ((ret
= memorystatus_validate_track_flags(p
, pcontrol
)) != 0) {
2609 old_dirty
= p
->p_memstat_dirty
;
2611 /* These bits are cumulative, as per <rdar://problem/11159924> */
2612 if (pcontrol
& PROC_DIRTY_TRACK
) {
2613 p
->p_memstat_dirty
|= P_DIRTY_TRACK
;
2616 if (pcontrol
& PROC_DIRTY_ALLOW_IDLE_EXIT
) {
2617 p
->p_memstat_dirty
|= P_DIRTY_ALLOW_IDLE_EXIT
;
2620 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2621 p
->p_memstat_dirty
|= P_DIRTY_LAUNCH_IN_PROGRESS
;
2624 if (old_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2625 already_deferred
= TRUE
;
2629 /* This can be set and cleared exactly once. */
2630 if (pcontrol
& PROC_DIRTY_DEFER
) {
2632 if ( !(old_dirty
& P_DIRTY_DEFER
)) {
2633 p
->p_memstat_dirty
|= P_DIRTY_DEFER
;
2639 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2640 ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) ? "Y" : "N",
2641 defer_now
? "Y" : "N",
2642 p
->p_memstat_dirty
& P_DIRTY
? "Y" : "N",
2645 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
2646 if (!(p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)) {
2647 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2649 if (defer_now
&& !already_deferred
) {
2652 * Request to defer a clean process that's idle-exit enabled
2653 * and not already in the jetsam deferred band. Most likely a
2656 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2659 } else if (!defer_now
) {
2662 * The process isn't asking for the 'aging' facility.
2663 * Could be that it is:
2666 if (already_deferred
) {
2668 * already in the aging bands. Traditionally,
2669 * some processes have tried to use this to
2670 * opt out of the 'aging' facility.
2673 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2676 * agnostic to the 'aging' facility. In that case,
2677 * we'll go ahead and opt it in because this is likely
2678 * a new launch (clean process, dirty tracking enabled)
2681 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2690 * We are trying to operate on a dirty process. Dirty processes have to
2691 * be removed from the deferred band. The question is do we reset the
2692 * deferred state or not?
2694 * This could be a legal request like:
2695 * - this process had opted into the 'aging' band
2696 * - but it's now dirty and requests to opt out.
2697 * In this case, we remove the process from the band and reset its
2698 * state too. It'll opt back in properly when needed.
2700 * OR, this request could be a user-space bug. E.g.:
2701 * - this process had opted into the 'aging' band when clean
2702 * - and, then issues another request to again put it into the band except
2703 * this time the process is dirty.
2704 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
2705 * the deferred band with its state intact. So our request below is no-op.
2706 * But we do it here anyways for coverage.
2708 * memorystatus_update_idle_priority_locked()
2709 * single-mindedly treats a dirty process as "cannot be in the aging band".
2712 if (!defer_now
&& already_deferred
) {
2713 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2717 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2719 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2724 memorystatus_update_idle_priority_locked(p
);
2727 memorystatus_reschedule_idle_demotion_locked();
2739 memorystatus_dirty_set(proc_t p
, boolean_t self
, uint32_t pcontrol
) {
2741 boolean_t kill
= false;
2742 boolean_t reschedule
= FALSE
;
2743 boolean_t was_dirty
= FALSE
;
2744 boolean_t now_dirty
= FALSE
;
2746 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self
, p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2747 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_SET
), p
->p_pid
, self
, pcontrol
, 0, 0);
2751 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2753 * Process is on its way out.
2759 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2764 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2767 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2768 /* Dirty tracking not enabled */
2770 } else if (pcontrol
&& (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2772 * Process is set to be terminated and we're attempting to mark it dirty.
2773 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2777 int flag
= (self
== TRUE
) ? P_DIRTY
: P_DIRTY_SHUTDOWN
;
2778 if (pcontrol
&& !(p
->p_memstat_dirty
& flag
)) {
2779 /* Mark the process as having been dirtied at some point */
2780 p
->p_memstat_dirty
|= (flag
| P_DIRTY_MARKED
);
2781 memorystatus_dirty_count
++;
2783 } else if ((pcontrol
== 0) && (p
->p_memstat_dirty
& flag
)) {
2784 if ((flag
== P_DIRTY_SHUTDOWN
) && (!(p
->p_memstat_dirty
& P_DIRTY
))) {
2785 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2786 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
2788 } else if ((flag
== P_DIRTY
) && (p
->p_memstat_dirty
& P_DIRTY_TERMINATED
)) {
2789 /* Kill previously terminated processes if set clean */
2792 p
->p_memstat_dirty
&= ~flag
;
2793 memorystatus_dirty_count
--;
2805 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
)
2808 if ((was_dirty
== TRUE
&& now_dirty
== FALSE
) ||
2809 (was_dirty
== FALSE
&& now_dirty
== TRUE
)) {
2811 /* Manage idle exit deferral, if applied */
2812 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
2815 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
2816 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
2818 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
2819 * in that band on it's way to IDLE.
2822 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
2824 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2826 * The process will move from its aging band to its higher requested
2829 boolean_t reset_state
= (jetsam_aging_policy
!= kJetsamAgingPolicyLegacy
) ? TRUE
: FALSE
;
2831 memorystatus_invalidate_idle_demotion_locked(p
, reset_state
);
2836 * Process is back from "dirty" to "clean".
2839 if (jetsam_aging_policy
== kJetsamAgingPolicyLegacy
) {
2840 if (mach_absolute_time() >= p
->p_memstat_idledeadline
) {
2842 * The process' deadline has expired. It currently
2843 * does not reside in any of the aging buckets.
2845 * It's on its way to the JETSAM_PRIORITY_IDLE
2846 * bucket via memorystatus_update_idle_priority_locked()
2849 * So all we need to do is reset all the state on the
2850 * process that's related to the aging bucket i.e.
2851 * the AGING_IN_PROGRESS flag and the timer deadline.
2854 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
2858 * It still has some protection window left and so
2859 * we just re-arm the timer without modifying any
2860 * state on the process iff it still wants into that band.
2863 if (p
->p_memstat_dirty
& P_DIRTY_AGING_IN_PROGRESS
) {
2864 memorystatus_schedule_idle_demotion_locked(p
, FALSE
);
2870 memorystatus_schedule_idle_demotion_locked(p
, TRUE
);
2876 memorystatus_update_idle_priority_locked(p
);
2878 if (memorystatus_highwater_enabled
) {
2879 boolean_t trigger_exception
= FALSE
, ledger_update_needed
= TRUE
;
2881 * We are in this path because this process transitioned between
2882 * dirty <--> clean state. Update the cached memory limits.
2885 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
2889 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2890 ledger_update_needed
= TRUE
;
2893 * process is clean...but if it has opted into pressured-exit
2894 * we don't apply the INACTIVE limit till the process has aged
2895 * out and is entering the IDLE band.
2896 * See memorystatus_update_priority_locked() for that.
2899 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
2900 ledger_update_needed
= FALSE
;
2902 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
2903 ledger_update_needed
= TRUE
;
2908 * Enforce the new limits by writing to the ledger.
2910 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
2911 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
2912 * We aren't traversing the jetsam bucket list here, so we should be safe.
2913 * See rdar://21394491.
2916 if (ledger_update_needed
&& proc_ref_locked(p
) == p
) {
2918 if (p
->p_memstat_memlimit
> 0) {
2919 ledger_limit
= p
->p_memstat_memlimit
;
2924 task_set_phys_footprint_limit_internal(p
->task
, ledger_limit
, NULL
, trigger_exception
);
2926 proc_rele_locked(p
);
2928 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
2929 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
2930 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
2931 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
2936 /* If the deferral state changed, reschedule the demotion timer */
2938 memorystatus_reschedule_idle_demotion_locked();
2943 if (proc_ref_locked(p
) == p
) {
2945 psignal(p
, SIGKILL
);
2947 proc_rele_locked(p
);
2958 memorystatus_dirty_clear(proc_t p
, uint32_t pcontrol
) {
2962 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p
->p_pid
, pcontrol
, p
->p_memstat_dirty
);
2964 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_DIRTY_CLEAR
), p
->p_pid
, pcontrol
, 0, 0, 0);
2968 if ((p
->p_listflag
& P_LIST_EXITED
) != 0) {
2970 * Process is on its way out.
2976 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
2981 if (!(p
->p_memstat_dirty
& P_DIRTY_TRACK
)) {
2982 /* Dirty tracking not enabled */
2987 if (!pcontrol
|| (pcontrol
& (PROC_DIRTY_LAUNCH_IN_PROGRESS
| PROC_DIRTY_DEFER
)) == 0) {
2992 if (pcontrol
& PROC_DIRTY_LAUNCH_IN_PROGRESS
) {
2993 p
->p_memstat_dirty
&= ~P_DIRTY_LAUNCH_IN_PROGRESS
;
2996 /* This can be set and cleared exactly once. */
2997 if (pcontrol
& PROC_DIRTY_DEFER
) {
2999 if (p
->p_memstat_dirty
& P_DIRTY_DEFER
) {
3001 p
->p_memstat_dirty
&= ~P_DIRTY_DEFER
;
3003 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
3004 memorystatus_update_idle_priority_locked(p
);
3005 memorystatus_reschedule_idle_demotion_locked();
3017 memorystatus_dirty_get(proc_t p
) {
3022 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3023 ret
|= PROC_DIRTY_TRACKED
;
3024 if (p
->p_memstat_dirty
& P_DIRTY_ALLOW_IDLE_EXIT
) {
3025 ret
|= PROC_DIRTY_ALLOWS_IDLE_EXIT
;
3027 if (p
->p_memstat_dirty
& P_DIRTY
) {
3028 ret
|= PROC_DIRTY_IS_DIRTY
;
3030 if (p
->p_memstat_dirty
& P_DIRTY_LAUNCH_IN_PROGRESS
) {
3031 ret
|= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS
;
3041 memorystatus_on_terminate(proc_t p
) {
3046 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3048 if ((p
->p_memstat_dirty
& (P_DIRTY_TRACK
|P_DIRTY_IS_DIRTY
)) == P_DIRTY_TRACK
) {
3049 /* Clean; mark as terminated and issue SIGKILL */
3052 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3062 memorystatus_on_suspend(proc_t p
)
3066 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
3070 p
->p_memstat_suspendedfootprint
= pages
;
3071 memorystatus_suspended_footprint_total
+= pages
;
3072 memorystatus_suspended_count
++;
3074 p
->p_memstat_state
|= P_MEMSTAT_SUSPENDED
;
3079 memorystatus_on_resume(proc_t p
)
3089 frozen
= (p
->p_memstat_state
& P_MEMSTAT_FROZEN
);
3091 memorystatus_frozen_count
--;
3092 p
->p_memstat_state
|= P_MEMSTAT_PRIOR_THAW
;
3095 memorystatus_suspended_footprint_total
-= p
->p_memstat_suspendedfootprint
;
3096 memorystatus_suspended_count
--;
3101 p
->p_memstat_state
&= ~(P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
);
3107 memorystatus_freeze_entry_t data
= { pid
, FALSE
, 0 };
3108 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
3114 memorystatus_on_inactivity(proc_t p
)
3118 /* Wake the freeze thread */
3119 thread_wakeup((event_t
)&memorystatus_freeze_wakeup
);
3124 * The proc_list_lock is held by the caller.
3127 memorystatus_build_state(proc_t p
) {
3128 uint32_t snapshot_state
= 0;
3131 if (p
->p_memstat_state
& P_MEMSTAT_SUSPENDED
) {
3132 snapshot_state
|= kMemorystatusSuspended
;
3134 if (p
->p_memstat_state
& P_MEMSTAT_FROZEN
) {
3135 snapshot_state
|= kMemorystatusFrozen
;
3137 if (p
->p_memstat_state
& P_MEMSTAT_PRIOR_THAW
) {
3138 snapshot_state
|= kMemorystatusWasThawed
;
3142 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3143 snapshot_state
|= kMemorystatusTracked
;
3145 if ((p
->p_memstat_dirty
& P_DIRTY_IDLE_EXIT_ENABLED
) == P_DIRTY_IDLE_EXIT_ENABLED
) {
3146 snapshot_state
|= kMemorystatusSupportsIdleExit
;
3148 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3149 snapshot_state
|= kMemorystatusDirty
;
3152 return snapshot_state
;
3158 kill_idle_exit_proc(void)
3160 proc_t p
, victim_p
= PROC_NULL
;
3161 uint64_t current_time
;
3162 boolean_t killed
= FALSE
;
3164 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3166 /* Pick next idle exit victim. */
3167 current_time
= mach_absolute_time();
3169 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_IDLE_EXIT
);
3170 if (jetsam_reason
== OS_REASON_NULL
) {
3171 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3176 p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
3178 /* No need to look beyond the idle band */
3179 if (p
->p_memstat_effectivepriority
!= JETSAM_PRIORITY_IDLE
) {
3183 if ((p
->p_memstat_dirty
& (P_DIRTY_ALLOW_IDLE_EXIT
|P_DIRTY_IS_DIRTY
|P_DIRTY_TERMINATED
)) == (P_DIRTY_ALLOW_IDLE_EXIT
)) {
3184 if (current_time
>= p
->p_memstat_idledeadline
) {
3185 p
->p_memstat_dirty
|= P_DIRTY_TERMINATED
;
3186 victim_p
= proc_ref_locked(p
);
3191 p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
3197 printf("memorystatus_thread: idle exiting pid %d [%s]\n", victim_p
->p_pid
, (*victim_p
->p_name
? victim_p
->p_name
: "(unknown)"));
3198 killed
= memorystatus_do_kill(victim_p
, kMemorystatusKilledIdleExit
, jetsam_reason
);
3199 proc_rele(victim_p
);
3201 os_reason_free(jetsam_reason
);
3210 memorystatus_thread_wake(void) {
3211 thread_wakeup((event_t
)&memorystatus_wakeup
);
3213 #endif /* CONFIG_JETSAM */
3215 extern void vm_pressure_response(void);
3218 memorystatus_thread_block(uint32_t interval_ms
, thread_continue_t continuation
)
3221 assert_wait_timeout(&memorystatus_wakeup
, THREAD_UNINT
, interval_ms
, 1000 * NSEC_PER_USEC
);
3223 assert_wait(&memorystatus_wakeup
, THREAD_UNINT
);
3226 return thread_block(continuation
);
3230 memorystatus_thread(void *param __unused
, wait_result_t wr __unused
)
3232 static boolean_t is_vm_privileged
= FALSE
;
3235 boolean_t post_snapshot
= FALSE
;
3236 uint32_t errors
= 0;
3237 uint32_t hwm_kill
= 0;
3238 boolean_t sort_flag
= TRUE
;
3239 boolean_t corpse_list_purged
= FALSE
;
3241 /* Jetsam Loop Detection - locals */
3242 memstat_bucket_t
*bucket
;
3243 int jld_bucket_count
= 0;
3244 struct timeval jld_now_tstamp
= {0,0};
3245 uint64_t jld_now_msecs
= 0;
3246 int elevated_bucket_count
= 0;
3248 /* Jetsam Loop Detection - statics */
3249 static uint64_t jld_timestamp_msecs
= 0;
3250 static int jld_idle_kill_candidates
= 0; /* Number of available processes in band 0,1 at start */
3251 static int jld_idle_kills
= 0; /* Number of procs killed during eval period */
3252 static int jld_eval_aggressive_count
= 0; /* Bumps the max priority in aggressive loop */
3253 static int32_t jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3256 if (is_vm_privileged
== FALSE
) {
3258 * It's the first time the thread has run, so just mark the thread as privileged and block.
3259 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
3261 thread_wire(host_priv_self(), current_thread(), TRUE
);
3262 is_vm_privileged
= TRUE
;
3264 if (vm_restricted_to_single_processor
== TRUE
)
3265 thread_vm_bind_group_add();
3267 memorystatus_thread_block(0, memorystatus_thread
);
3272 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_START
,
3273 memorystatus_available_pages
, memorystatus_jld_enabled
, memorystatus_jld_eval_period_msecs
, memorystatus_jld_eval_aggressive_count
,0);
3276 * Jetsam aware version.
3278 * The VM pressure notification thread is working it's way through clients in parallel.
3280 * So, while the pressure notification thread is targeting processes in order of
3281 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
3282 * any processes that have exceeded their highwater mark.
3284 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
3285 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
3287 while (is_thrashing(kill_under_pressure_cause
) ||
3288 memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3292 uint64_t jetsam_reason_code
= JETSAM_REASON_INVALID
;
3293 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3295 cause
= kill_under_pressure_cause
;
3297 case kMemorystatusKilledFCThrashing
:
3298 jetsam_reason_code
= JETSAM_REASON_MEMORY_FCTHRASHING
;
3300 case kMemorystatusKilledVMThrashing
:
3301 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMTHRASHING
;
3303 case kMemorystatusKilledVMPageShortage
:
3306 jetsam_reason_code
= JETSAM_REASON_MEMORY_VMPAGESHORTAGE
;
3307 cause
= kMemorystatusKilledVMPageShortage
;
3312 killed
= memorystatus_kill_hiwat_proc(&errors
);
3315 post_snapshot
= TRUE
;
3318 memorystatus_hwm_candidates
= FALSE
;
3321 /* No highwater processes to kill. Continue or stop for now? */
3322 if (!is_thrashing(kill_under_pressure_cause
) &&
3323 (memorystatus_available_pages
> memorystatus_available_pages_critical
)) {
3325 * We are _not_ out of pressure but we are above the critical threshold and there's:
3326 * - no compressor thrashing
3327 * - no more HWM processes left.
3328 * For now, don't kill any other processes.
3331 if (hwm_kill
== 0) {
3332 memorystatus_thread_wasted_wakeup
++;
3338 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, jetsam_reason_code
);
3339 if (jetsam_reason
== OS_REASON_NULL
) {
3340 printf("memorystatus_thread: failed to allocate jetsam reason\n");
3343 if (memorystatus_jld_enabled
== TRUE
) {
3346 * Jetsam Loop Detection: attempt to detect
3347 * rapid daemon relaunches in the lower bands.
3350 microuptime(&jld_now_tstamp
);
3353 * Ignore usecs in this calculation.
3354 * msecs granularity is close enough.
3356 jld_now_msecs
= (jld_now_tstamp
.tv_sec
* 1000);
3359 switch (jetsam_aging_policy
) {
3360 case kJetsamAgingPolicyLegacy
:
3361 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3362 jld_bucket_count
= bucket
->count
;
3363 bucket
= &memstat_bucket
[JETSAM_PRIORITY_AGING_BAND1
];
3364 jld_bucket_count
+= bucket
->count
;
3366 case kJetsamAgingPolicySysProcsReclaimedFirst
:
3367 case kJetsamAgingPolicyAppsReclaimedFirst
:
3368 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3369 jld_bucket_count
= bucket
->count
;
3370 bucket
= &memstat_bucket
[system_procs_aging_band
];
3371 jld_bucket_count
+= bucket
->count
;
3372 bucket
= &memstat_bucket
[applications_aging_band
];
3373 jld_bucket_count
+= bucket
->count
;
3375 case kJetsamAgingPolicyNone
:
3377 bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
3378 jld_bucket_count
= bucket
->count
;
3382 bucket
= &memstat_bucket
[JETSAM_PRIORITY_ELEVATED_INACTIVE
];
3383 elevated_bucket_count
= bucket
->count
;
3388 * memorystatus_jld_eval_period_msecs is a tunable
3389 * memorystatus_jld_eval_aggressive_count is a tunable
3390 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
3392 if ( (jld_bucket_count
== 0) ||
3393 (jld_now_msecs
> (jld_timestamp_msecs
+ memorystatus_jld_eval_period_msecs
))) {
3396 * Refresh evaluation parameters
3398 jld_timestamp_msecs
= jld_now_msecs
;
3399 jld_idle_kill_candidates
= jld_bucket_count
;
3401 jld_eval_aggressive_count
= 0;
3402 jld_priority_band_max
= JETSAM_PRIORITY_UI_SUPPORT
;
3405 if (jld_idle_kills
> jld_idle_kill_candidates
) {
3406 jld_eval_aggressive_count
++;
3408 #if DEVELOPMENT || DEBUG
3409 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
3410 jld_eval_aggressive_count
,
3411 jld_timestamp_msecs
,
3413 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
3414 jld_eval_aggressive_count
,
3415 jld_idle_kill_candidates
,
3417 #endif /* DEVELOPMENT || DEBUG */
3419 if ((jld_eval_aggressive_count
== memorystatus_jld_eval_aggressive_count
) &&
3420 (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3422 * If we reach this aggressive cycle, corpses might be causing memory pressure.
3423 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
3424 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
3426 task_purge_all_corpses();
3427 corpse_list_purged
= TRUE
;
3429 else if (jld_eval_aggressive_count
> memorystatus_jld_eval_aggressive_count
) {
3431 * Bump up the jetsam priority limit (eg: the bucket index)
3432 * Enforce bucket index sanity.
3434 if ((memorystatus_jld_eval_aggressive_priority_band_max
< 0) ||
3435 (memorystatus_jld_eval_aggressive_priority_band_max
>= MEMSTAT_BUCKET_COUNT
)) {
3437 * Do nothing. Stick with the default level.
3440 jld_priority_band_max
= memorystatus_jld_eval_aggressive_priority_band_max
;
3444 /* Visit elevated processes first */
3445 while (elevated_bucket_count
) {
3447 elevated_bucket_count
--;
3450 * memorystatus_kill_elevated_process() drops a reference,
3451 * so take another one so we can continue to use this exit reason
3452 * even after it returns.
3455 os_reason_ref(jetsam_reason
);
3456 killed
= memorystatus_kill_elevated_process(
3457 kMemorystatusKilledVMThrashing
,
3459 jld_eval_aggressive_count
,
3463 post_snapshot
= TRUE
;
3464 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
3466 * Still under pressure.
3467 * Find another pinned processes.
3475 * No pinned processes left to kill.
3476 * Abandon elevated band.
3483 * memorystatus_kill_top_process_aggressive() drops a reference,
3484 * so take another one so we can continue to use this exit reason
3485 * even after it returns
3487 os_reason_ref(jetsam_reason
);
3488 killed
= memorystatus_kill_top_process_aggressive(
3490 kMemorystatusKilledVMThrashing
,
3492 jld_eval_aggressive_count
,
3493 jld_priority_band_max
,
3497 /* Always generate logs after aggressive kill */
3498 post_snapshot
= TRUE
;
3506 * memorystatus_kill_top_process() drops a reference,
3507 * so take another one so we can continue to use this exit reason
3508 * even after it returns
3510 os_reason_ref(jetsam_reason
);
3513 killed
= memorystatus_kill_top_process(TRUE
, sort_flag
, cause
, jetsam_reason
, &priority
, &errors
);
3518 * Don't generate logs for steady-state idle-exit kills,
3519 * unless it is overridden for debug or by the device
3522 if ((priority
!= JETSAM_PRIORITY_IDLE
) || memorystatus_idle_snapshot
) {
3523 post_snapshot
= TRUE
;
3526 /* Jetsam Loop Detection */
3527 if (memorystatus_jld_enabled
== TRUE
) {
3528 if ((priority
== JETSAM_PRIORITY_IDLE
) || (priority
== system_procs_aging_band
) || (priority
== applications_aging_band
)) {
3532 * We've reached into bands beyond idle deferred.
3533 * We make no attempt to monitor them
3538 if ((priority
>= JETSAM_PRIORITY_UI_SUPPORT
) && (total_corpses_count
> 0) && (corpse_list_purged
== FALSE
)) {
3540 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
3541 * then we attempt to relieve pressure by purging corpse memory.
3543 task_purge_all_corpses();
3544 corpse_list_purged
= TRUE
;
3549 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3551 * Still under pressure and unable to kill a process - purge corpse memory
3553 if (total_corpses_count
> 0) {
3554 task_purge_all_corpses();
3555 corpse_list_purged
= TRUE
;
3558 if (memorystatus_available_pages
<= memorystatus_available_pages_critical
) {
3560 * Still under pressure and unable to kill a process - panic
3562 panic("memorystatus_jetsam_thread: no victim! available pages:%d\n", memorystatus_available_pages
);
3569 * We do not want to over-kill when thrashing has been detected.
3570 * To avoid that, we reset the flag here and notify the
3573 if (is_thrashing(kill_under_pressure_cause
)) {
3574 kill_under_pressure_cause
= 0;
3575 vm_thrashing_jetsam_done();
3578 os_reason_free(jetsam_reason
);
3581 kill_under_pressure_cause
= 0;
3584 memorystatus_clear_errors();
3587 #if VM_PRESSURE_EVENTS
3589 * LD: We used to target the foreground process first and foremost here.
3590 * Now, we target all processes, starting from the non-suspended, background
3591 * processes first. We will target foreground too.
3593 * memorystatus_update_vm_pressure(TRUE);
3595 //vm_pressure_response();
3598 if (post_snapshot
) {
3600 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3601 sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
);
3602 uint64_t timestamp_now
= mach_absolute_time();
3603 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3604 memorystatus_jetsam_snapshot
->js_gencount
++;
3605 if (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3606 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
) {
3608 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3611 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3619 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_SCAN
) | DBG_FUNC_END
,
3620 memorystatus_available_pages
, 0, 0, 0, 0);
3622 #else /* CONFIG_JETSAM */
3625 * Jetsam not enabled
3628 #endif /* CONFIG_JETSAM */
3630 memorystatus_thread_block(0, memorystatus_thread
);
3636 * when an idle-exitable proc was killed
3638 * when there are no more idle-exitable procs found
3639 * when the attempt to kill an idle-exitable proc failed
3641 boolean_t
memorystatus_idle_exit_from_VM(void) {
3642 return(kill_idle_exit_proc());
3644 #endif /* !CONFIG_JETSAM */
3648 * when exceeding ledger footprint is fatal.
3650 * when exceeding ledger footprint is non fatal.
3653 memorystatus_turnoff_exception_and_get_fatalness(boolean_t warning
, const int max_footprint_mb
)
3655 proc_t p
= current_proc();
3660 is_fatal
= (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
);
3662 if (warning
== FALSE
) {
3663 boolean_t is_active
;
3664 boolean_t state_changed
= FALSE
;
3667 * We are here because a process has exceeded its ledger limit.
3668 * That is, the process is no longer in the limit warning range.
3670 * When a process exceeds its ledger limit, we want an EXC_RESOURCE
3671 * to trigger, but only once per process per limit. We enforce that
3672 * here, by identifying the active/inactive limit type. We then turn
3673 * off the exception state by marking the limit as exception triggered.
3676 is_active
= proc_jetsam_state_is_active_locked(p
);
3678 if (is_active
== TRUE
) {
3680 * turn off exceptions for active state
3682 if (!(p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED
)) {
3683 p
->p_memstat_state
|= P_MEMSTAT_MEMLIMIT_ACTIVE_EXC_TRIGGERED
;
3684 state_changed
= TRUE
;
3688 * turn off exceptions for inactive state
3690 if (!(p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED
)) {
3691 p
->p_memstat_state
|= P_MEMSTAT_MEMLIMIT_INACTIVE_EXC_TRIGGERED
;
3692 state_changed
= TRUE
;
3697 * The limit violation is logged here, but only once per process per limit.
3698 * This avoids excessive logging when a process consistently exceeds a soft limit.
3699 * Soft memory limit is a non-fatal high-water-mark
3700 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
3703 printf("process %d (%s) exceeded physical memory footprint, the %s%sMemoryLimit of %d MB\n",
3704 p
->p_pid
, (*p
->p_name
? p
->p_name
: "unknown"), (is_active
? "Active" : "Inactive"),
3705 (is_fatal
? "Hard" : "Soft"), max_footprint_mb
);
3715 * Callback invoked when allowable physical memory footprint exceeded
3716 * (dirty pages + IOKit mappings)
3718 * This is invoked for both advisory, non-fatal per-task high watermarks,
3719 * as well as the fatal task memory limits.
3722 memorystatus_on_ledger_footprint_exceeded(boolean_t warning
, boolean_t is_fatal
)
3724 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3726 proc_t p
= current_proc();
3728 #if VM_PRESSURE_EVENTS
3729 if (warning
== TRUE
) {
3731 * This is a warning path which implies that the current process is close, but has
3732 * not yet exceeded its per-process memory limit.
3734 if (memorystatus_warn_process(p
->p_pid
, FALSE
/* not exceeded */) != TRUE
) {
3735 /* Print warning, since it's possible that task has not registered for pressure notifications */
3736 printf("task_exceeded_footprint: failed to warn the current task (%d exiting, or no handler registered?).\n", p
->p_pid
);
3740 #endif /* VM_PRESSURE_EVENTS */
3744 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
3745 * has violated either the system-wide per-task memory limit OR its own task limit.
3747 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_PERPROCESSLIMIT
);
3748 if (jetsam_reason
== NULL
) {
3749 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
3750 } else if (corpse_for_fatal_memkill
!= 0) {
3751 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
3752 jetsam_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
3755 if (memorystatus_kill_process_sync(p
->p_pid
, kMemorystatusKilledPerProcessLimit
, jetsam_reason
) != TRUE
) {
3756 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
3760 * HWM offender exists. Done without locks or synchronization.
3761 * See comment near its declaration for more details.
3763 memorystatus_hwm_candidates
= TRUE
;
3765 #if VM_PRESSURE_EVENTS
3767 * The current process is not in the warning path.
3768 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
3769 * Failure to send note is ignored here.
3771 (void)memorystatus_warn_process(p
->p_pid
, TRUE
/* exceeded */);
3773 #endif /* VM_PRESSURE_EVENTS */
3779 * Evaluates active vs. inactive process state.
3780 * Processes that opt into dirty tracking are evaluated
3781 * based on clean vs dirty state.
3783 * clean ==> inactive
3785 * Process that do not opt into dirty tracking are
3786 * evalulated based on priority level.
3787 * Foreground or above ==> active
3788 * Below Foreground ==> inactive
3790 * Return: TRUE if active
3795 proc_jetsam_state_is_active_locked(proc_t p
) {
3797 if (p
->p_memstat_dirty
& P_DIRTY_TRACK
) {
3799 * process has opted into dirty tracking
3800 * active state is based on dirty vs. clean
3802 if (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) {
3805 * implies active state
3811 * implies inactive state
3815 } else if (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
) {
3817 * process is Foreground or higher
3818 * implies active state
3823 * process found below Foreground
3824 * implies inactive state
3831 memorystatus_kill_process_sync(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3835 uint32_t errors
= 0;
3837 if (victim_pid
== -1) {
3838 /* No pid, so kill first process */
3839 res
= memorystatus_kill_top_process(TRUE
, TRUE
, cause
, jetsam_reason
, NULL
, &errors
);
3841 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3845 memorystatus_clear_errors();
3849 /* Fire off snapshot notification */
3851 size_t snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) +
3852 sizeof(memorystatus_jetsam_snapshot_entry_t
) * memorystatus_jetsam_snapshot_count
;
3853 uint64_t timestamp_now
= mach_absolute_time();
3854 memorystatus_jetsam_snapshot
->notification_time
= timestamp_now
;
3855 if (memorystatus_jetsam_snapshot_last_timestamp
== 0 ||
3856 timestamp_now
> memorystatus_jetsam_snapshot_last_timestamp
+ memorystatus_jetsam_snapshot_timeout
) {
3858 int ret
= memorystatus_send_note(kMemorystatusSnapshotNote
, &snapshot_size
, sizeof(snapshot_size
));
3861 memorystatus_jetsam_snapshot_last_timestamp
= timestamp_now
;
3868 #else /* !CONFIG_JETSAM */
3870 res
= memorystatus_kill_specific_process(victim_pid
, cause
, jetsam_reason
);
3872 #endif /* CONFIG_JETSAM */
3878 * Jetsam a specific process.
3881 memorystatus_kill_specific_process(pid_t victim_pid
, uint32_t cause
, os_reason_t jetsam_reason
) {
3884 uint64_t killtime
= 0;
3886 clock_usec_t tv_usec
;
3889 /* TODO - add a victim queue and push this into the main jetsam thread */
3891 p
= proc_find(victim_pid
);
3893 os_reason_free(jetsam_reason
);
3900 if (memorystatus_jetsam_snapshot_count
== 0) {
3901 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
3904 killtime
= mach_absolute_time();
3905 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3906 tv_msec
= tv_usec
/ 1000;
3908 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
3912 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3913 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3914 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
, memorystatus_available_pages
);
3915 #else /* !CONFIG_JETSAM */
3918 killtime
= mach_absolute_time();
3919 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
3920 tv_msec
= tv_usec
/ 1000;
3921 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d)\n",
3922 (unsigned long)tv_sec
, tv_msec
, victim_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
3923 jetsam_kill_cause_name
[cause
], p
->p_memstat_effectivepriority
);
3924 #endif /* CONFIG_JETSAM */
3926 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
3934 * Toggle the P_MEMSTAT_TERMINATED state.
3935 * Takes the proc_list_lock.
3938 proc_memstat_terminated(proc_t p
, boolean_t set
)
3940 #if DEVELOPMENT || DEBUG
3944 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
3946 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
3951 #pragma unused(p, set)
3955 #endif /* DEVELOPMENT || DEBUG */
3962 * This is invoked when cpulimits have been exceeded while in fatal mode.
3963 * The jetsam_flags do not apply as those are for memory related kills.
3964 * We call this routine so that the offending process is killed with
3965 * a non-zero exit status.
3968 jetsam_on_ledger_cpulimit_exceeded(void)
3971 int jetsam_flags
= 0; /* make it obvious */
3972 proc_t p
= current_proc();
3973 os_reason_t jetsam_reason
= OS_REASON_NULL
;
3975 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
3976 p
->p_pid
, (*p
->p_name
? p
->p_name
: "(unknown)"));
3978 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_CPULIMIT
);
3979 if (jetsam_reason
== OS_REASON_NULL
) {
3980 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
3983 retval
= jetsam_do_kill(p
, jetsam_flags
, jetsam_reason
);
3986 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
3991 memorystatus_get_task_memory_region_count(task_t task
, uint64_t *count
)
3996 *count
= get_task_memory_region_count(task
);
4000 memorystatus_get_task_page_counts(task_t task
, uint32_t *footprint
, uint32_t *max_footprint
, uint32_t *max_footprint_lifetime
, uint32_t *purgeable_pages
)
4007 pages
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
4008 assert(((uint32_t)pages
) == pages
);
4009 *footprint
= (uint32_t)pages
;
4011 if (max_footprint
) {
4012 pages
= (get_task_phys_footprint_max(task
) / PAGE_SIZE_64
);
4013 assert(((uint32_t)pages
) == pages
);
4014 *max_footprint
= (uint32_t)pages
;
4016 if (max_footprint_lifetime
) {
4017 pages
= (get_task_resident_max(task
) / PAGE_SIZE_64
);
4018 assert(((uint32_t)pages
) == pages
);
4019 *max_footprint_lifetime
= (uint32_t)pages
;
4021 if (purgeable_pages
) {
4022 pages
= (get_task_purgeable_size(task
) / PAGE_SIZE_64
);
4023 assert(((uint32_t)pages
) == pages
);
4024 *purgeable_pages
= (uint32_t)pages
;
4029 memorystatus_get_task_phys_footprint_page_counts(task_t task
,
4030 uint64_t *internal_pages
, uint64_t *internal_compressed_pages
,
4031 uint64_t *purgeable_nonvolatile_pages
, uint64_t *purgeable_nonvolatile_compressed_pages
,
4032 uint64_t *alternate_accounting_pages
, uint64_t *alternate_accounting_compressed_pages
,
4033 uint64_t *iokit_mapped_pages
, uint64_t *page_table_pages
)
4037 if (internal_pages
) {
4038 *internal_pages
= (get_task_internal(task
) / PAGE_SIZE_64
);
4041 if (internal_compressed_pages
) {
4042 *internal_compressed_pages
= (get_task_internal_compressed(task
) / PAGE_SIZE_64
);
4045 if (purgeable_nonvolatile_pages
) {
4046 *purgeable_nonvolatile_pages
= (get_task_purgeable_nonvolatile(task
) / PAGE_SIZE_64
);
4049 if (purgeable_nonvolatile_compressed_pages
) {
4050 *purgeable_nonvolatile_compressed_pages
= (get_task_purgeable_nonvolatile_compressed(task
) / PAGE_SIZE_64
);
4053 if (alternate_accounting_pages
) {
4054 *alternate_accounting_pages
= (get_task_alternate_accounting(task
) / PAGE_SIZE_64
);
4057 if (alternate_accounting_compressed_pages
) {
4058 *alternate_accounting_compressed_pages
= (get_task_alternate_accounting_compressed(task
) / PAGE_SIZE_64
);
4061 if (iokit_mapped_pages
) {
4062 *iokit_mapped_pages
= (get_task_iokit_mapped(task
) / PAGE_SIZE_64
);
4065 if (page_table_pages
) {
4066 *page_table_pages
= (get_task_page_table(task
) / PAGE_SIZE_64
);
4071 * This routine only acts on the global jetsam event snapshot.
4072 * Updating the process's entry can race when the memorystatus_thread
4073 * has chosen to kill a process that is racing to exit on another core.
4076 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p
, uint32_t kill_cause
, uint64_t killtime
)
4078 memorystatus_jetsam_snapshot_entry_t
*entry
= NULL
;
4079 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4080 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4084 if (memorystatus_jetsam_snapshot_count
== 0) {
4086 * No active snapshot.
4093 * Sanity check as this routine should only be called
4094 * from a jetsam kill path.
4096 assert(kill_cause
!= 0 && killtime
!= 0);
4098 snapshot
= memorystatus_jetsam_snapshot
;
4099 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4101 for (i
= 0; i
< memorystatus_jetsam_snapshot_count
; i
++) {
4102 if (snapshot_list
[i
].pid
== p
->p_pid
) {
4104 entry
= &snapshot_list
[i
];
4106 if (entry
->killed
|| entry
->jse_killtime
) {
4108 * We apparently raced on the exit path
4109 * for this process, as it's snapshot entry
4110 * has already recorded a kill.
4112 assert(entry
->killed
&& entry
->jse_killtime
);
4117 * Update the entry we just found in the snapshot.
4120 entry
->killed
= kill_cause
;
4121 entry
->jse_killtime
= killtime
;
4122 entry
->jse_gencount
= snapshot
->js_gencount
;
4123 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
;
4126 * If a process has moved between bands since snapshot was
4127 * initialized, then likely these fields changed too.
4129 if (entry
->priority
!= p
->p_memstat_effectivepriority
) {
4131 strlcpy(entry
->name
, p
->p_name
, sizeof(entry
->name
));
4132 entry
->priority
= p
->p_memstat_effectivepriority
;
4133 entry
->state
= memorystatus_build_state(p
);
4134 entry
->user_data
= p
->p_memstat_userdata
;
4135 entry
->fds
= p
->p_fd
->fd_nfiles
;
4139 * Always update the page counts on a kill.
4143 uint32_t max_pages
= 0;
4144 uint32_t max_pages_lifetime
= 0;
4145 uint32_t purgeable_pages
= 0;
4147 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4148 entry
->pages
= (uint64_t)pages
;
4149 entry
->max_pages
= (uint64_t)max_pages
;
4150 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4151 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4153 uint64_t internal_pages
= 0;
4154 uint64_t internal_compressed_pages
= 0;
4155 uint64_t purgeable_nonvolatile_pages
= 0;
4156 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4157 uint64_t alternate_accounting_pages
= 0;
4158 uint64_t alternate_accounting_compressed_pages
= 0;
4159 uint64_t iokit_mapped_pages
= 0;
4160 uint64_t page_table_pages
= 0;
4162 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4163 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4164 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4165 &iokit_mapped_pages
, &page_table_pages
);
4167 entry
->jse_internal_pages
= internal_pages
;
4168 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4169 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4170 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4171 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4172 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4173 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4174 entry
->jse_page_table_pages
= page_table_pages
;
4176 uint64_t region_count
= 0;
4177 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4178 entry
->jse_memory_region_count
= region_count
;
4184 if (entry
== NULL
) {
4186 * The entry was not found in the snapshot, so the process must have
4187 * launched after the snapshot was initialized.
4188 * Let's try to append the new entry.
4190 if (memorystatus_jetsam_snapshot_count
< memorystatus_jetsam_snapshot_max
) {
4192 * A populated snapshot buffer exists
4193 * and there is room to init a new entry.
4195 assert(memorystatus_jetsam_snapshot_count
== snapshot
->entry_count
);
4197 unsigned int next
= memorystatus_jetsam_snapshot_count
;
4199 if(memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[next
], (snapshot
->js_gencount
)) == TRUE
) {
4201 entry
= &snapshot_list
[next
];
4202 entry
->killed
= kill_cause
;
4203 entry
->jse_killtime
= killtime
;
4205 snapshot
->entry_count
= ++next
;
4206 memorystatus_jetsam_snapshot_count
= next
;
4208 if (memorystatus_jetsam_snapshot_count
>= memorystatus_jetsam_snapshot_max
) {
4210 * We just used the last slot in the snapshot buffer.
4211 * We only want to log it once... so we do it here
4212 * when we notice we've hit the max.
4214 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
4215 memorystatus_jetsam_snapshot_count
);
4222 if (entry
== NULL
) {
4224 * If we reach here, the snapshot buffer could not be updated.
4225 * Most likely, the buffer is full, in which case we would have
4226 * logged a warning in the previous call.
4228 * For now, we will stop appending snapshot entries.
4229 * When the buffer is consumed, the snapshot state will reset.
4232 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
4233 p
->p_pid
, p
->p_memstat_effectivepriority
, memorystatus_jetsam_snapshot_count
);
4239 void memorystatus_pages_update(unsigned int pages_avail
)
4241 memorystatus_available_pages
= pages_avail
;
4243 #if VM_PRESSURE_EVENTS
4245 * Since memorystatus_available_pages changes, we should
4246 * re-evaluate the pressure levels on the system and
4247 * check if we need to wake the pressure thread.
4248 * We also update memorystatus_level in that routine.
4250 vm_pressure_response();
4252 if (memorystatus_available_pages
<= memorystatus_available_pages_pressure
) {
4254 if (memorystatus_hwm_candidates
|| (memorystatus_available_pages
<= memorystatus_available_pages_critical
)) {
4255 memorystatus_thread_wake();
4258 #else /* VM_PRESSURE_EVENTS */
4260 boolean_t critical
, delta
;
4262 if (!memorystatus_delta
) {
4266 critical
= (pages_avail
< memorystatus_available_pages_critical
) ? TRUE
: FALSE
;
4267 delta
= ((pages_avail
>= (memorystatus_available_pages
+ memorystatus_delta
))
4268 || (memorystatus_available_pages
>= (pages_avail
+ memorystatus_delta
))) ? TRUE
: FALSE
;
4270 if (critical
|| delta
) {
4271 unsigned int total_pages
;
4273 total_pages
= (unsigned int) atop_64(max_mem
);
4274 #if CONFIG_SECLUDED_MEMORY
4275 total_pages
-= vm_page_secluded_count
;
4276 #endif /* CONFIG_SECLUDED_MEMORY */
4277 memorystatus_level
= memorystatus_available_pages
* 100 / total_pages
;
4278 memorystatus_thread_wake();
4280 #endif /* VM_PRESSURE_EVENTS */
4284 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p
, memorystatus_jetsam_snapshot_entry_t
*entry
, uint64_t gencount
)
4287 clock_usec_t tv_usec
;
4289 uint32_t max_pages
= 0;
4290 uint32_t max_pages_lifetime
= 0;
4291 uint32_t purgeable_pages
= 0;
4292 uint64_t internal_pages
= 0;
4293 uint64_t internal_compressed_pages
= 0;
4294 uint64_t purgeable_nonvolatile_pages
= 0;
4295 uint64_t purgeable_nonvolatile_compressed_pages
= 0;
4296 uint64_t alternate_accounting_pages
= 0;
4297 uint64_t alternate_accounting_compressed_pages
= 0;
4298 uint64_t iokit_mapped_pages
= 0;
4299 uint64_t page_table_pages
=0;
4300 uint64_t region_count
= 0;
4301 uint64_t cids
[COALITION_NUM_TYPES
];
4303 memset(entry
, 0, sizeof(memorystatus_jetsam_snapshot_entry_t
));
4305 entry
->pid
= p
->p_pid
;
4306 strlcpy(&entry
->name
[0], p
->p_name
, sizeof(entry
->name
));
4307 entry
->priority
= p
->p_memstat_effectivepriority
;
4309 memorystatus_get_task_page_counts(p
->task
, &pages
, &max_pages
, &max_pages_lifetime
, &purgeable_pages
);
4310 entry
->pages
= (uint64_t)pages
;
4311 entry
->max_pages
= (uint64_t)max_pages
;
4312 entry
->max_pages_lifetime
= (uint64_t)max_pages_lifetime
;
4313 entry
->purgeable_pages
= (uint64_t)purgeable_pages
;
4315 memorystatus_get_task_phys_footprint_page_counts(p
->task
, &internal_pages
, &internal_compressed_pages
,
4316 &purgeable_nonvolatile_pages
, &purgeable_nonvolatile_compressed_pages
,
4317 &alternate_accounting_pages
, &alternate_accounting_compressed_pages
,
4318 &iokit_mapped_pages
, &page_table_pages
);
4320 entry
->jse_internal_pages
= internal_pages
;
4321 entry
->jse_internal_compressed_pages
= internal_compressed_pages
;
4322 entry
->jse_purgeable_nonvolatile_pages
= purgeable_nonvolatile_pages
;
4323 entry
->jse_purgeable_nonvolatile_compressed_pages
= purgeable_nonvolatile_compressed_pages
;
4324 entry
->jse_alternate_accounting_pages
= alternate_accounting_pages
;
4325 entry
->jse_alternate_accounting_compressed_pages
= alternate_accounting_compressed_pages
;
4326 entry
->jse_iokit_mapped_pages
= iokit_mapped_pages
;
4327 entry
->jse_page_table_pages
= page_table_pages
;
4329 memorystatus_get_task_memory_region_count(p
->task
, ®ion_count
);
4330 entry
->jse_memory_region_count
= region_count
;
4332 entry
->state
= memorystatus_build_state(p
);
4333 entry
->user_data
= p
->p_memstat_userdata
;
4334 memcpy(&entry
->uuid
[0], &p
->p_uuid
[0], sizeof(p
->p_uuid
));
4335 entry
->fds
= p
->p_fd
->fd_nfiles
;
4337 absolutetime_to_microtime(get_task_cpu_time(p
->task
), &tv_sec
, &tv_usec
);
4338 entry
->cpu_time
.tv_sec
= tv_sec
;
4339 entry
->cpu_time
.tv_usec
= tv_usec
;
4341 assert(p
->p_stats
!= NULL
);
4342 entry
->jse_starttime
= p
->p_stats
->ps_start
; /* abstime process started */
4343 entry
->jse_killtime
= 0; /* abstime jetsam chose to kill process */
4344 entry
->killed
= 0; /* the jetsam kill cause */
4345 entry
->jse_gencount
= gencount
; /* indicates a pass through jetsam thread, when process was targeted to be killed */
4347 entry
->jse_idle_delta
= p
->p_memstat_idle_delta
; /* Most recent timespan spent in idle-band */
4349 proc_coalitionids(p
, cids
);
4350 entry
->jse_coalition_jetsam_id
= cids
[COALITION_TYPE_JETSAM
];
4356 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t
*snapshot
)
4358 kern_return_t kr
= KERN_SUCCESS
;
4359 mach_msg_type_number_t count
= HOST_VM_INFO64_COUNT
;
4360 vm_statistics64_data_t vm_stat
;
4362 if ((kr
= host_statistics64(host_self(), HOST_VM_INFO64
, (host_info64_t
)&vm_stat
, &count
) != KERN_SUCCESS
)) {
4363 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr
);
4364 memset(&snapshot
->stats
, 0, sizeof(snapshot
->stats
));
4366 snapshot
->stats
.free_pages
= vm_stat
.free_count
;
4367 snapshot
->stats
.active_pages
= vm_stat
.active_count
;
4368 snapshot
->stats
.inactive_pages
= vm_stat
.inactive_count
;
4369 snapshot
->stats
.throttled_pages
= vm_stat
.throttled_count
;
4370 snapshot
->stats
.purgeable_pages
= vm_stat
.purgeable_count
;
4371 snapshot
->stats
.wired_pages
= vm_stat
.wire_count
;
4373 snapshot
->stats
.speculative_pages
= vm_stat
.speculative_count
;
4374 snapshot
->stats
.filebacked_pages
= vm_stat
.external_page_count
;
4375 snapshot
->stats
.anonymous_pages
= vm_stat
.internal_page_count
;
4376 snapshot
->stats
.compressions
= vm_stat
.compressions
;
4377 snapshot
->stats
.decompressions
= vm_stat
.decompressions
;
4378 snapshot
->stats
.compressor_pages
= vm_stat
.compressor_page_count
;
4379 snapshot
->stats
.total_uncompressed_pages_in_compressor
= vm_stat
.total_uncompressed_pages_in_compressor
;
4384 * Collect vm statistics at boot.
4385 * Called only once (see kern_exec.c)
4386 * Data can be consumed at any time.
4389 memorystatus_init_at_boot_snapshot() {
4390 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot
);
4391 memorystatus_at_boot_snapshot
.entry_count
= 0;
4392 memorystatus_at_boot_snapshot
.notification_time
= 0; /* updated when consumed */
4393 memorystatus_at_boot_snapshot
.snapshot_time
= mach_absolute_time();
4397 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t
*od_snapshot
, uint32_t ods_list_count
)
4400 unsigned int b
= 0, i
= 0;
4402 memorystatus_jetsam_snapshot_t
*snapshot
= NULL
;
4403 memorystatus_jetsam_snapshot_entry_t
*snapshot_list
= NULL
;
4404 unsigned int snapshot_max
= 0;
4408 * This is an on_demand snapshot
4410 snapshot
= od_snapshot
;
4411 snapshot_list
= od_snapshot
->entries
;
4412 snapshot_max
= ods_list_count
;
4415 * This is a jetsam event snapshot
4417 snapshot
= memorystatus_jetsam_snapshot
;
4418 snapshot_list
= memorystatus_jetsam_snapshot
->entries
;
4419 snapshot_max
= memorystatus_jetsam_snapshot_max
;
4423 * Init the snapshot header information
4425 memorystatus_init_snapshot_vmstats(snapshot
);
4426 snapshot
->snapshot_time
= mach_absolute_time();
4427 snapshot
->notification_time
= 0;
4428 snapshot
->js_gencount
= 0;
4430 next_p
= memorystatus_get_first_proc_locked(&b
, TRUE
);
4433 next_p
= memorystatus_get_next_proc_locked(&b
, p
, TRUE
);
4435 if (FALSE
== memorystatus_init_jetsam_snapshot_entry_locked(p
, &snapshot_list
[i
], snapshot
->js_gencount
)) {
4439 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",
4441 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],
4442 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]);
4444 if (++i
== snapshot_max
) {
4449 snapshot
->entry_count
= i
;
4452 /* update the system buffer count */
4453 memorystatus_jetsam_snapshot_count
= i
;
4457 #if DEVELOPMENT || DEBUG
4460 memorystatus_cmd_set_panic_bits(user_addr_t buffer
, uint32_t buffer_size
) {
4462 memorystatus_jetsam_panic_options_t debug
;
4464 if (buffer_size
!= sizeof(memorystatus_jetsam_panic_options_t
)) {
4468 ret
= copyin(buffer
, &debug
, buffer_size
);
4473 /* Panic bits match kMemorystatusKilled* enum */
4474 memorystatus_jetsam_panic_debug
= (memorystatus_jetsam_panic_debug
& ~debug
.mask
) | (debug
.data
& debug
.mask
);
4476 /* Copyout new value */
4477 debug
.data
= memorystatus_jetsam_panic_debug
;
4478 ret
= copyout(&debug
, buffer
, sizeof(memorystatus_jetsam_panic_options_t
));
4484 * Triggers a sort_order on a specified jetsam priority band.
4485 * This is for testing only, used to force a path through the sort
4489 memorystatus_cmd_test_jetsam_sort(int priority
, int sort_order
) {
4493 unsigned int bucket_index
= 0;
4495 if (priority
== -1) {
4496 /* Use as shorthand for default priority */
4497 bucket_index
= JETSAM_PRIORITY_DEFAULT
;
4499 bucket_index
= (unsigned int)priority
;
4502 error
= memorystatus_sort_bucket(bucket_index
, sort_order
);
4507 #endif /* DEVELOPMENT || DEBUG */
4510 * Jetsam the first process in the queue.
4513 memorystatus_kill_top_process(boolean_t any
, boolean_t sort_flag
, uint32_t cause
, os_reason_t jetsam_reason
,
4514 int32_t *priority
, uint32_t *errors
)
4517 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4518 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4522 uint64_t killtime
= 0;
4524 clock_usec_t tv_usec
;
4527 #ifndef CONFIG_FREEZE
4531 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4532 memorystatus_available_pages
, 0, 0, 0, 0);
4535 if (sort_flag
== TRUE
) {
4536 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4541 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4543 #if DEVELOPMENT || DEBUG
4545 int procSuspendedForDiagnosis
;
4546 #endif /* DEVELOPMENT || DEBUG */
4549 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4551 #if DEVELOPMENT || DEBUG
4552 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4553 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4554 #endif /* DEVELOPMENT || DEBUG */
4557 aPid_ep
= p
->p_memstat_effectivepriority
;
4559 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4560 continue; /* with lock held */
4563 #if DEVELOPMENT || DEBUG
4564 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4565 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4568 #endif /* DEVELOPMENT || DEBUG */
4570 if (cause
== kMemorystatusKilledVnodes
)
4573 * If the system runs out of vnodes, we systematically jetsam
4574 * processes in hopes of stumbling onto a vnode gain that helps
4575 * the system recover. The process that happens to trigger
4576 * this path has no known relationship to the vnode consumption.
4577 * We attempt to safeguard that process e.g: do not jetsam it.
4580 if (p
== current_proc()) {
4581 /* do not jetsam the current process */
4588 boolean_t reclaim_proc
= !(p
->p_memstat_state
& (P_MEMSTAT_LOCKED
| P_MEMSTAT_NORECLAIM
));
4589 if (any
|| reclaim_proc
) {
4601 * Capture a snapshot if none exists and:
4602 * - priority was not requested (this is something other than an ambient kill)
4603 * - the priority was requested *and* the targeted process is not at idle priority
4605 if ((memorystatus_jetsam_snapshot_count
== 0) &&
4606 (memorystatus_idle_snapshot
|| ((!priority
) || (priority
&& (aPid_ep
!= JETSAM_PRIORITY_IDLE
))))) {
4607 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4608 new_snapshot
= TRUE
;
4612 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4613 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4614 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4615 * acquisition of the proc lock.
4617 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4619 killtime
= mach_absolute_time();
4620 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4621 tv_msec
= tv_usec
/ 1000;
4623 #if DEVELOPMENT || DEBUG
4624 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && activeProcess
) {
4625 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
4626 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), memorystatus_level
);
4627 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
4628 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
4629 if (memorystatus_jetsam_policy
& kPolicyDiagnoseFirst
) {
4630 jetsam_diagnostic_suspended_one_active_proc
= 1;
4631 printf("jetsam: returning after suspending first active proc - %d\n", aPid
);
4634 p
= proc_ref_locked(p
);
4637 task_suspend(p
->task
);
4639 *priority
= aPid_ep
;
4647 #endif /* DEVELOPMENT || DEBUG */
4649 /* Shift queue, update stats */
4650 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4652 if (proc_ref_locked(p
) == p
) {
4654 printf("%lu.%02d memorystatus: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4655 (unsigned long)tv_sec
, tv_msec
,
4656 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing top process pid"),
4657 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4658 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4661 * memorystatus_do_kill() drops a reference, so take another one so we can
4662 * continue to use this exit reason even after memorystatus_do_kill()
4665 os_reason_ref(jetsam_reason
);
4667 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4672 *priority
= aPid_ep
;
4680 * Failure - first unwind the state,
4681 * then fall through to restart the search.
4684 proc_rele_locked(p
);
4685 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4686 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4691 * Failure - restart the search.
4693 * We might have raced with "p" exiting on another core, resulting in no
4694 * ref on "p". Or, we may have failed to kill "p".
4696 * Either way, we fall thru to here, leaving the proc in the
4697 * P_MEMSTAT_TERMINATED state.
4699 * And, we hold the the proc_list_lock at this point.
4703 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4711 os_reason_free(jetsam_reason
);
4713 /* Clear snapshot if freshly captured and no target was found */
4714 if (new_snapshot
&& !killed
) {
4716 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4720 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4721 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4727 * Jetsam aggressively
4730 memorystatus_kill_top_process_aggressive(boolean_t any
, uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
,
4731 int32_t priority_max
, uint32_t *errors
)
4734 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4735 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4738 int32_t aPid_ep
= 0;
4739 unsigned int memorystatus_level_snapshot
= 0;
4740 uint64_t killtime
= 0;
4742 clock_usec_t tv_usec
;
4747 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
4748 memorystatus_available_pages
, priority_max
, 0, 0, 0);
4750 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND
, JETSAM_SORT_DEFAULT
);
4754 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4756 #if DEVELOPMENT || DEBUG
4758 int procSuspendedForDiagnosis
;
4759 #endif /* DEVELOPMENT || DEBUG */
4761 if ((unsigned int)(next_p
->p_memstat_effectivepriority
) != i
) {
4764 * We have raced with next_p running on another core, as it has
4765 * moved to a different jetsam priority band. This means we have
4766 * lost our place in line while traversing the jetsam list. We
4767 * attempt to recover by rewinding to the beginning of the band
4768 * we were already traversing. By doing this, we do not guarantee
4769 * that no process escapes this aggressive march, but we can make
4770 * skipping an entire range of processes less likely. (PR-21069019)
4773 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding %s moved from band %d --> %d\n",
4774 aggr_count
, (*next_p
->p_name
? next_p
->p_name
: "unknown"), i
, next_p
->p_memstat_effectivepriority
);
4776 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4781 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4783 if (p
->p_memstat_effectivepriority
> priority_max
) {
4785 * Bail out of this killing spree if we have
4786 * reached beyond the priority_max jetsam band.
4787 * That is, we kill up to and through the
4788 * priority_max jetsam band.
4794 #if DEVELOPMENT || DEBUG
4795 activeProcess
= p
->p_memstat_state
& P_MEMSTAT_FOREGROUND
;
4796 procSuspendedForDiagnosis
= p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
;
4797 #endif /* DEVELOPMENT || DEBUG */
4800 aPid_ep
= p
->p_memstat_effectivepriority
;
4802 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4806 #if DEVELOPMENT || DEBUG
4807 if ((memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) && procSuspendedForDiagnosis
) {
4808 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid
);
4811 #endif /* DEVELOPMENT || DEBUG */
4814 * Capture a snapshot if none exists.
4816 if (memorystatus_jetsam_snapshot_count
== 0) {
4817 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
4818 new_snapshot
= TRUE
;
4822 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4823 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4824 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4825 * acquisition of the proc lock.
4827 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
4829 killtime
= mach_absolute_time();
4830 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
4831 tv_msec
= tv_usec
/ 1000;
4833 /* Shift queue, update stats */
4834 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
4837 * In order to kill the target process, we will drop the proc_list_lock.
4838 * To guaranteee that p and next_p don't disappear out from under the lock,
4839 * we must take a ref on both.
4840 * If we cannot get a reference, then it's likely we've raced with
4841 * that process exiting on another core.
4843 if (proc_ref_locked(p
) == p
) {
4845 while (next_p
&& (proc_ref_locked(next_p
) != next_p
)) {
4849 * We must have raced with next_p exiting on another core.
4850 * Recover by getting the next eligible process in the band.
4853 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
4854 aggr_count
, next_p
->p_pid
, (*next_p
->p_name
? next_p
->p_name
: "(unknown)"));
4857 next_p
= memorystatus_get_next_proc_locked(&i
, temp_p
, TRUE
);
4862 printf("%lu.%01d memorystatus: aggressive%d: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4863 (unsigned long)tv_sec
, tv_msec
, aggr_count
,
4864 ((aPid_ep
== JETSAM_PRIORITY_IDLE
) ? "idle exiting pid" : "jetsam killing pid"),
4865 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
4866 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
4868 memorystatus_level_snapshot
= memorystatus_level
;
4871 * memorystatus_do_kill() drops a reference, so take another one so we can
4872 * continue to use this exit reason even after memorystatus_do_kill()
4875 os_reason_ref(jetsam_reason
);
4876 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
4886 * Continue the killing spree.
4890 proc_rele_locked(next_p
);
4893 if (aPid_ep
== JETSAM_PRIORITY_FOREGROUND
&& memorystatus_aggressive_jetsam_lenient
== TRUE
) {
4894 if (memorystatus_level
> memorystatus_level_snapshot
&& ((memorystatus_level
- memorystatus_level_snapshot
) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD
)) {
4895 #if DEVELOPMENT || DEBUG
4896 printf("Disabling Lenient mode after one-time deployment.\n");
4897 #endif /* DEVELOPMENT || DEBUG */
4898 memorystatus_aggressive_jetsam_lenient
= FALSE
;
4907 * Failure - first unwind the state,
4908 * then fall through to restart the search.
4911 proc_rele_locked(p
);
4913 proc_rele_locked(next_p
);
4915 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
4916 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
4922 * Failure - restart the search at the beginning of
4923 * the band we were already traversing.
4925 * We might have raced with "p" exiting on another core, resulting in no
4926 * ref on "p". Or, we may have failed to kill "p".
4928 * Either way, we fall thru to here, leaving the proc in the
4929 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
4931 * And, we hold the the proc_list_lock at this point.
4934 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4940 os_reason_free(jetsam_reason
);
4942 /* Clear snapshot if freshly captured and no target was found */
4943 if (new_snapshot
&& (kill_count
== 0)) {
4944 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
4947 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
4948 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
4950 if (kill_count
> 0) {
4959 memorystatus_kill_hiwat_proc(uint32_t *errors
)
4962 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
4963 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
4967 uint64_t killtime
= 0;
4969 clock_usec_t tv_usec
;
4971 os_reason_t jetsam_reason
= OS_REASON_NULL
;
4972 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_START
,
4973 memorystatus_available_pages
, 0, 0, 0, 0);
4975 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_HIGHWATER
);
4976 if (jetsam_reason
== OS_REASON_NULL
) {
4977 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
4982 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
4984 uint64_t footprint_in_bytes
= 0;
4985 uint64_t memlimit_in_bytes
= 0;
4989 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
4992 aPid_ep
= p
->p_memstat_effectivepriority
;
4994 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
4998 /* skip if no limit set */
4999 if (p
->p_memstat_memlimit
<= 0) {
5005 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
5006 * Background limits are described via the inactive limit slots.
5007 * Their fatal/non-fatal setting will drive whether or not to be
5008 * considered in this kill path.
5011 /* skip if a currently inapplicable limit is encountered */
5012 if ((p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_BACKGROUND
) && (p
->p_memstat_effectivepriority
>= JETSAM_PRIORITY_FOREGROUND
)) {
5016 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
5017 memlimit_in_bytes
= (((uint64_t)p
->p_memstat_memlimit
) * 1024ULL * 1024ULL); /* convert MB to bytes */
5018 skip
= (footprint_in_bytes
<= memlimit_in_bytes
);
5020 #if DEVELOPMENT || DEBUG
5021 if (!skip
&& (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
)) {
5022 if (p
->p_memstat_state
& P_MEMSTAT_DIAG_SUSPENDED
) {
5026 #endif /* DEVELOPMENT || DEBUG */
5030 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5041 #if DEVELOPMENT || DEBUG
5042 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5043 (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) ? "suspending": "killing",
5044 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5045 (footprint_in_bytes
/ (1024ULL * 1024ULL)), /* converted bytes to MB */
5046 p
->p_memstat_memlimit
);
5047 #endif /* DEVELOPMENT || DEBUG */
5049 if (memorystatus_jetsam_snapshot_count
== 0) {
5050 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5051 new_snapshot
= TRUE
;
5054 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5056 killtime
= mach_absolute_time();
5057 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5058 tv_msec
= tv_usec
/ 1000;
5060 #if DEVELOPMENT || DEBUG
5061 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
5062 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid
, memorystatus_available_pages
);
5063 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledDiagnostic
, killtime
);
5064 p
->p_memstat_state
|= P_MEMSTAT_DIAG_SUSPENDED
;
5066 p
= proc_ref_locked(p
);
5069 task_suspend(p
->task
);
5076 #endif /* DEVELOPMENT || DEBUG */
5078 memorystatus_update_jetsam_snapshot_entry_locked(p
, kMemorystatusKilledHiwat
, killtime
);
5080 if (proc_ref_locked(p
) == p
) {
5083 printf("%lu.%02d memorystatus: jetsam killing pid %d [%s] (highwater %d) - memorystatus_available_pages: %d\n",
5084 (unsigned long)tv_sec
, tv_msec
, aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"), aPid_ep
, memorystatus_available_pages
);
5087 * memorystatus_do_kill drops a reference, so take another one so we can
5088 * continue to use this exit reason even after memorystatus_do_kill()
5091 os_reason_ref(jetsam_reason
);
5093 killed
= memorystatus_do_kill(p
, kMemorystatusKilledHiwat
, jetsam_reason
);
5103 * Failure - first unwind the state,
5104 * then fall through to restart the search.
5107 proc_rele_locked(p
);
5108 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5109 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5114 * Failure - restart the search.
5116 * We might have raced with "p" exiting on another core, resulting in no
5117 * ref on "p". Or, we may have failed to kill "p".
5119 * Either way, we fall thru to here, leaving the proc in the
5120 * P_MEMSTAT_TERMINATED state.
5122 * And, we hold the the proc_list_lock at this point.
5126 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5134 os_reason_free(jetsam_reason
);
5136 /* Clear snapshot if freshly captured and no target was found */
5137 if (new_snapshot
&& !killed
) {
5139 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5143 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM_HIWAT
) | DBG_FUNC_END
,
5144 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5150 * Jetsam a process pinned in the elevated band.
5152 * Return: true -- at least one pinned process was jetsammed
5153 * false -- no pinned process was jetsammed
5156 memorystatus_kill_elevated_process(uint32_t cause
, os_reason_t jetsam_reason
, int aggr_count
, uint32_t *errors
)
5159 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5160 boolean_t new_snapshot
= FALSE
, killed
= FALSE
;
5162 unsigned int i
= JETSAM_PRIORITY_ELEVATED_INACTIVE
;
5164 uint64_t killtime
= 0;
5166 clock_usec_t tv_usec
;
5170 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_START
,
5171 memorystatus_available_pages
, 0, 0, 0, 0);
5175 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5179 next_p
= memorystatus_get_next_proc_locked(&i
, p
, FALSE
);
5182 aPid_ep
= p
->p_memstat_effectivepriority
;
5185 * Only pick a process pinned in this elevated band
5187 if (!(p
->p_memstat_state
& P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND
)) {
5191 if (p
->p_memstat_state
& (P_MEMSTAT_ERROR
| P_MEMSTAT_TERMINATED
)) {
5196 if (p
->p_memstat_state
& P_MEMSTAT_LOCKED
) {
5201 #if DEVELOPMENT || DEBUG
5202 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
5204 aPid
, (*p
->p_name
? p
->p_name
: "unknown"),
5205 memorystatus_available_pages
);
5206 #endif /* DEVELOPMENT || DEBUG */
5208 if (memorystatus_jetsam_snapshot_count
== 0) {
5209 memorystatus_init_jetsam_snapshot_locked(NULL
,0);
5210 new_snapshot
= TRUE
;
5213 p
->p_memstat_state
|= P_MEMSTAT_TERMINATED
;
5215 killtime
= mach_absolute_time();
5216 absolutetime_to_microtime(killtime
, &tv_sec
, &tv_usec
);
5217 tv_msec
= tv_usec
/ 1000;
5219 memorystatus_update_jetsam_snapshot_entry_locked(p
, cause
, killtime
);
5221 if (proc_ref_locked(p
) == p
) {
5225 printf("%lu.%01d memorystatus: elevated%d: jetsam killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
5226 (unsigned long)tv_sec
, tv_msec
,
5228 aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5229 jetsam_kill_cause_name
[cause
], aPid_ep
, memorystatus_available_pages
);
5232 * memorystatus_do_kill drops a reference, so take another one so we can
5233 * continue to use this exit reason even after memorystatus_do_kill()
5236 os_reason_ref(jetsam_reason
);
5237 killed
= memorystatus_do_kill(p
, cause
, jetsam_reason
);
5247 * Failure - first unwind the state,
5248 * then fall through to restart the search.
5251 proc_rele_locked(p
);
5252 p
->p_memstat_state
&= ~P_MEMSTAT_TERMINATED
;
5253 p
->p_memstat_state
|= P_MEMSTAT_ERROR
;
5258 * Failure - restart the search.
5260 * We might have raced with "p" exiting on another core, resulting in no
5261 * ref on "p". Or, we may have failed to kill "p".
5263 * Either way, we fall thru to here, leaving the proc in the
5264 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
5266 * And, we hold the the proc_list_lock at this point.
5269 next_p
= memorystatus_get_first_proc_locked(&i
, FALSE
);
5275 os_reason_free(jetsam_reason
);
5277 /* Clear snapshot if freshly captured and no target was found */
5278 if (new_snapshot
&& (kill_count
== 0)) {
5280 memorystatus_jetsam_snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
5284 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_JETSAM
) | DBG_FUNC_END
,
5285 memorystatus_available_pages
, killed
? aPid
: 0, kill_count
, 0, 0);
5291 memorystatus_kill_process_async(pid_t victim_pid
, uint32_t cause
) {
5293 * TODO: allow a general async path
5295 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
5296 * add the appropriate exit reason code mapping.
5298 if ((victim_pid
!= -1) || (cause
!= kMemorystatusKilledVMPageShortage
&& cause
!= kMemorystatusKilledVMThrashing
&&
5299 cause
!= kMemorystatusKilledFCThrashing
)) {
5303 kill_under_pressure_cause
= cause
;
5304 memorystatus_thread_wake();
5309 memorystatus_kill_on_VM_page_shortage(boolean_t async
) {
5311 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage
);
5313 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMPAGESHORTAGE
);
5314 if (jetsam_reason
== OS_REASON_NULL
) {
5315 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
5318 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage
, jetsam_reason
);
5323 memorystatus_kill_on_VM_thrashing(boolean_t async
) {
5325 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing
);
5327 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_VMTHRASHING
);
5328 if (jetsam_reason
== OS_REASON_NULL
) {
5329 printf("memorystatus_kill_on_VM_thrashing -- sync: failed to allocate jetsam reason\n");
5332 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing
, jetsam_reason
);
5337 memorystatus_kill_on_FC_thrashing(boolean_t async
) {
5341 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing
);
5343 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_MEMORY_FCTHRASHING
);
5344 if (jetsam_reason
== OS_REASON_NULL
) {
5345 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
5348 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing
, jetsam_reason
);
5353 memorystatus_kill_on_vnode_limit(void) {
5354 os_reason_t jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_VNODE
);
5355 if (jetsam_reason
== OS_REASON_NULL
) {
5356 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
5359 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes
, jetsam_reason
);
5362 #endif /* CONFIG_JETSAM */
5366 __private_extern__
void
5367 memorystatus_freeze_init(void)
5369 kern_return_t result
;
5372 freezer_lck_grp_attr
= lck_grp_attr_alloc_init();
5373 freezer_lck_grp
= lck_grp_alloc_init("freezer", freezer_lck_grp_attr
);
5375 lck_mtx_init(&freezer_mutex
, freezer_lck_grp
, NULL
);
5377 result
= kernel_thread_start(memorystatus_freeze_thread
, NULL
, &thread
);
5378 if (result
== KERN_SUCCESS
) {
5379 thread_deallocate(thread
);
5381 panic("Could not create memorystatus_freeze_thread");
5386 * Synchronously freeze the passed proc. Called with a reference to the proc held.
5388 * Returns EINVAL or the value returned by task_freeze().
5391 memorystatus_freeze_process_sync(proc_t p
)
5395 boolean_t memorystatus_freeze_swap_low
= FALSE
;
5397 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5398 memorystatus_available_pages
, 0, 0, 0, 0);
5400 lck_mtx_lock(&freezer_mutex
);
5406 if (memorystatus_freeze_enabled
== FALSE
) {
5410 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5414 if (memorystatus_freeze_update_throttle()) {
5415 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
5416 memorystatus_freeze_throttle_count
++;
5423 uint32_t purgeable
, wired
, clean
, dirty
, state
;
5424 uint32_t max_pages
, pages
, i
;
5428 state
= p
->p_memstat_state
;
5430 /* Ensure the process is eligible for freezing */
5431 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5436 /* Only freeze processes meeting our minimum resident page criteria */
5437 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5438 if (pages
< memorystatus_freeze_pages_min
) {
5443 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5445 unsigned int avail_swap_space
= 0; /* in pages. */
5448 * Freezer backed by the compressor and swap file(s)
5449 * while will hold compressed data.
5451 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5453 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5455 if (max_pages
< memorystatus_freeze_pages_min
) {
5461 * We only have the compressor without any swap.
5463 max_pages
= UINT32_MAX
- 1;
5466 /* Mark as locked temporarily to avoid kill */
5467 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5470 ret
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5472 DTRACE_MEMORYSTATUS6(memorystatus_freeze
, proc_t
, p
, unsigned int, memorystatus_available_pages
, boolean_t
, purgeable
, unsigned int, wired
, uint32_t, clean
, uint32_t, dirty
);
5474 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
5475 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5476 (ret
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5477 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5480 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5482 if (ret
== KERN_SUCCESS
) {
5483 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5485 memorystatus_frozen_count
++;
5487 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5489 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5491 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5492 throttle_intervals
[i
].pageouts
+= dirty
;
5496 memorystatus_freeze_pageouts
+= dirty
;
5497 memorystatus_freeze_count
++;
5501 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5508 lck_mtx_unlock(&freezer_mutex
);
5509 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5510 memorystatus_available_pages
, aPid
, 0, 0, 0);
5516 memorystatus_freeze_top_process(boolean_t
*memorystatus_freeze_swap_low
)
5520 proc_t p
= PROC_NULL
, next_p
= PROC_NULL
;
5523 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_START
,
5524 memorystatus_available_pages
, 0, 0, 0, 0);
5528 next_p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
5531 uint32_t purgeable
, wired
, clean
, dirty
;
5534 uint32_t max_pages
= 0;
5538 next_p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
5541 state
= p
->p_memstat_state
;
5543 /* Ensure the process is eligible for freezing */
5544 if ((state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_FROZEN
)) || !(state
& P_MEMSTAT_SUSPENDED
)) {
5545 continue; // with lock held
5548 /* Only freeze processes meeting our minimum resident page criteria */
5549 memorystatus_get_task_page_counts(p
->task
, &pages
, NULL
, NULL
, NULL
);
5550 if (pages
< memorystatus_freeze_pages_min
) {
5551 continue; // with lock held
5554 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5556 /* Ensure there's enough free space to freeze this process. */
5558 unsigned int avail_swap_space
= 0; /* in pages. */
5561 * Freezer backed by the compressor and swap file(s)
5562 * while will hold compressed data.
5564 avail_swap_space
= vm_swap_get_free_space() / PAGE_SIZE_64
;
5566 max_pages
= MIN(avail_swap_space
, memorystatus_freeze_pages_max
);
5568 if (max_pages
< memorystatus_freeze_pages_min
) {
5569 *memorystatus_freeze_swap_low
= TRUE
;
5575 * We only have the compressor pool.
5577 max_pages
= UINT32_MAX
- 1;
5580 /* Mark as locked temporarily to avoid kill */
5581 p
->p_memstat_state
|= P_MEMSTAT_LOCKED
;
5583 p
= proc_ref_locked(p
);
5589 kr
= task_freeze(p
->task
, &purgeable
, &wired
, &clean
, &dirty
, max_pages
, &shared
, FALSE
);
5591 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
5592 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5593 (kr
== KERN_SUCCESS
) ? "SUCCEEDED" : "FAILED", aPid
, (*p
->p_name
? p
->p_name
: "(unknown)"),
5594 memorystatus_available_pages
, purgeable
, wired
, clean
, dirty
, max_pages
, shared
);
5597 p
->p_memstat_state
&= ~P_MEMSTAT_LOCKED
;
5600 if (KERN_SUCCESS
== kr
) {
5601 memorystatus_freeze_entry_t data
= { aPid
, TRUE
, dirty
};
5603 memorystatus_frozen_count
++;
5605 p
->p_memstat_state
|= (P_MEMSTAT_FROZEN
| (shared
? 0: P_MEMSTAT_NORECLAIM
));
5607 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5609 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5610 throttle_intervals
[i
].pageouts
+= dirty
;
5614 memorystatus_freeze_pageouts
+= dirty
;
5615 memorystatus_freeze_count
++;
5619 memorystatus_send_note(kMemorystatusFreezeNote
, &data
, sizeof(data
));
5621 /* Return KERN_SUCESS */
5635 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_FREEZE
) | DBG_FUNC_END
,
5636 memorystatus_available_pages
, aPid
, 0, 0, 0);
5641 static inline boolean_t
5642 memorystatus_can_freeze_processes(void)
5648 if (memorystatus_suspended_count
) {
5649 uint32_t average_resident_pages
, estimated_processes
;
5651 /* Estimate the number of suspended processes we can fit */
5652 average_resident_pages
= memorystatus_suspended_footprint_total
/ memorystatus_suspended_count
;
5653 estimated_processes
= memorystatus_suspended_count
+
5654 ((memorystatus_available_pages
- memorystatus_available_pages_critical
) / average_resident_pages
);
5656 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
5657 if (estimated_processes
<= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
) {
5658 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_LOW
;
5660 memorystatus_freeze_suspended_threshold
= FREEZE_SUSPENDED_THRESHOLD_DEFAULT
;
5663 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
5664 memorystatus_suspended_count
, average_resident_pages
, estimated_processes
);
5666 if ((memorystatus_suspended_count
- memorystatus_frozen_count
) > memorystatus_freeze_suspended_threshold
) {
5681 memorystatus_can_freeze(boolean_t
*memorystatus_freeze_swap_low
)
5683 boolean_t can_freeze
= TRUE
;
5685 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
5686 after boot, and is generally is a no-op once we've reached steady state. */
5687 if (memorystatus_available_pages
> memorystatus_freeze_threshold
) {
5691 /* Check minimum suspended process threshold. */
5692 if (!memorystatus_can_freeze_processes()) {
5695 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT
);
5697 if ( !VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
5699 * In-core compressor used for freezing WITHOUT on-disk swap support.
5701 if (vm_compressor_low_on_space()) {
5702 if (*memorystatus_freeze_swap_low
) {
5703 *memorystatus_freeze_swap_low
= TRUE
;
5709 if (*memorystatus_freeze_swap_low
) {
5710 *memorystatus_freeze_swap_low
= FALSE
;
5717 * Freezing WITH on-disk swap support.
5719 * In-core compressor fronts the swap.
5721 if (vm_swap_low_on_space()) {
5722 if (*memorystatus_freeze_swap_low
) {
5723 *memorystatus_freeze_swap_low
= TRUE
;
5735 memorystatus_freeze_update_throttle_interval(mach_timespec_t
*ts
, struct throttle_interval_t
*interval
)
5737 unsigned int freeze_daily_pageouts_max
= memorystatus_freeze_daily_mb_max
* (1024 * 1024 / PAGE_SIZE
);
5738 if (CMP_MACH_TIMESPEC(ts
, &interval
->ts
) >= 0) {
5739 if (!interval
->max_pageouts
) {
5740 interval
->max_pageouts
= (interval
->burst_multiple
* (((uint64_t)interval
->mins
* freeze_daily_pageouts_max
) / (24 * 60)));
5742 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval
->mins
);
5744 interval
->ts
.tv_sec
= interval
->mins
* 60;
5745 interval
->ts
.tv_nsec
= 0;
5746 ADD_MACH_TIMESPEC(&interval
->ts
, ts
);
5747 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
5748 if (interval
->pageouts
> interval
->max_pageouts
) {
5749 interval
->pageouts
-= interval
->max_pageouts
;
5751 interval
->pageouts
= 0;
5753 interval
->throttle
= FALSE
;
5754 } else if (!interval
->throttle
&& interval
->pageouts
>= interval
->max_pageouts
) {
5755 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval
->mins
);
5756 interval
->throttle
= TRUE
;
5759 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
5760 interval
->pageouts
, interval
->max_pageouts
, interval
->mins
, (interval
->ts
.tv_sec
- ts
->tv_sec
) / 60,
5761 interval
->throttle
? "on" : "off");
5765 memorystatus_freeze_update_throttle(void)
5771 boolean_t throttled
= FALSE
;
5773 #if DEVELOPMENT || DEBUG
5774 if (!memorystatus_freeze_throttle_enabled
)
5778 clock_get_system_nanotime(&sec
, &nsec
);
5782 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
5784 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
5785 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
5786 * order to allow for bursts of activity.
5788 for (i
= 0; i
< sizeof(throttle_intervals
) / sizeof(struct throttle_interval_t
); i
++) {
5789 memorystatus_freeze_update_throttle_interval(&ts
, &throttle_intervals
[i
]);
5790 if (throttle_intervals
[i
].throttle
== TRUE
)
5798 memorystatus_freeze_thread(void *param __unused
, wait_result_t wr __unused
)
5800 static boolean_t memorystatus_freeze_swap_low
= FALSE
;
5802 lck_mtx_lock(&freezer_mutex
);
5803 if (memorystatus_freeze_enabled
) {
5804 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low
)) {
5805 /* Only freeze if we've not exceeded our pageout budgets.*/
5806 if (!memorystatus_freeze_update_throttle()) {
5807 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low
);
5809 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
5810 memorystatus_freeze_throttle_count
++; /* Throttled, update stats */
5814 lck_mtx_unlock(&freezer_mutex
);
5816 assert_wait((event_t
) &memorystatus_freeze_wakeup
, THREAD_UNINT
);
5817 thread_block((thread_continue_t
) memorystatus_freeze_thread
);
5820 #endif /* CONFIG_FREEZE */
5822 #if VM_PRESSURE_EVENTS
5824 #if CONFIG_MEMORYSTATUS
5827 memorystatus_send_note(int event_code
, void *data
, size_t data_length
) {
5829 struct kev_msg ev_msg
;
5831 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
5832 ev_msg
.kev_class
= KEV_SYSTEM_CLASS
;
5833 ev_msg
.kev_subclass
= KEV_MEMORYSTATUS_SUBCLASS
;
5835 ev_msg
.event_code
= event_code
;
5837 ev_msg
.dv
[0].data_length
= data_length
;
5838 ev_msg
.dv
[0].data_ptr
= data
;
5839 ev_msg
.dv
[1].data_length
= 0;
5841 ret
= kev_post_msg(&ev_msg
);
5843 printf("%s: kev_post_msg() failed, err %d\n", __func__
, ret
);
5850 memorystatus_warn_process(pid_t pid
, boolean_t limit_exceeded
) {
5852 boolean_t ret
= FALSE
;
5853 boolean_t found_knote
= FALSE
;
5854 struct knote
*kn
= NULL
;
5857 * See comment in sysctl_memorystatus_vm_pressure_send.
5860 memorystatus_klist_lock();
5862 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
5863 proc_t knote_proc
= knote_get_kq(kn
)->kq_p
;
5864 pid_t knote_pid
= knote_proc
->p_pid
;
5866 if (knote_pid
== pid
) {
5868 * By setting the "fflags" here, we are forcing
5869 * a process to deal with the case where it's
5870 * bumping up into its memory limits. If we don't
5871 * do this here, we will end up depending on the
5872 * system pressure snapshot evaluation in
5873 * filt_memorystatus().
5876 if (!limit_exceeded
) {
5879 * Processes on desktop are not expecting to handle a system-wide
5880 * critical or system-wide warning notification from this path.
5881 * Intentionally set only the unambiguous limit warning here.
5884 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
5885 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
5891 * Send this notification when a process has exceeded a soft limit.
5893 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
5894 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
5902 KNOTE(&memorystatus_klist
, 0);
5906 memorystatus_klist_unlock();
5912 * Can only be set by the current task on itself.
5915 memorystatus_low_mem_privileged_listener(uint32_t op_flags
)
5917 boolean_t set_privilege
= FALSE
;
5919 * Need an entitlement check here?
5921 if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
) {
5922 set_privilege
= TRUE
;
5923 } else if (op_flags
== MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
) {
5924 set_privilege
= FALSE
;
5929 return (task_low_mem_privileged_listener(current_task(), set_privilege
, NULL
));
5933 memorystatus_send_pressure_note(pid_t pid
) {
5934 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid
);
5935 return memorystatus_send_note(kMemorystatusPressureNote
, &pid
, sizeof(pid
));
5939 memorystatus_send_low_swap_note(void) {
5941 struct knote
*kn
= NULL
;
5943 memorystatus_klist_lock();
5944 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
5945 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
5946 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
5947 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
5948 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
5949 if (is_knote_registered_modify_task_pressure_bits(kn
, NOTE_MEMORYSTATUS_LOW_SWAP
, NULL
, 0, 0) == TRUE
) {
5950 KNOTE(&memorystatus_klist
, kMemorystatusLowSwap
);
5955 memorystatus_klist_unlock();
5959 memorystatus_bg_pressure_eligible(proc_t p
) {
5960 boolean_t eligible
= FALSE
;
5964 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p
->p_pid
, p
->p_memstat_state
);
5966 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
5967 if (!(p
->p_memstat_state
& (P_MEMSTAT_TERMINATED
| P_MEMSTAT_LOCKED
| P_MEMSTAT_SUSPENDED
| P_MEMSTAT_FROZEN
))) {
5977 memorystatus_is_foreground_locked(proc_t p
) {
5978 return ((p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND
) ||
5979 (p
->p_memstat_effectivepriority
== JETSAM_PRIORITY_FOREGROUND_SUPPORT
));
5983 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
5984 * to access the p_memstat_dirty field.
5987 memorystatus_proc_is_dirty_unsafe(void *v
)
5992 proc_t p
= (proc_t
)v
;
5993 return (p
->p_memstat_dirty
& P_DIRTY_IS_DIRTY
) != 0;
5996 #endif /* CONFIG_MEMORYSTATUS */
5999 * Trigger levels to test the mechanism.
6000 * Can be used via a sysctl.
6002 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
6003 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
6004 #define TEST_PURGEABLE_TRIGGER_ONE 3
6005 #define TEST_PURGEABLE_TRIGGER_ALL 4
6006 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
6007 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
6009 boolean_t memorystatus_manual_testing_on
= FALSE
;
6010 vm_pressure_level_t memorystatus_manual_testing_level
= kVMPressureNormal
;
6012 extern struct knote
*
6013 vm_pressure_select_optimal_candidate_to_notify(struct klist
*, int, boolean_t
);
6016 * This value is the threshold that a process must meet to be considered for scavenging.
6018 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
6020 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
6023 #define VM_PRESSURE_DEBUG(cond, format, ...) \
6025 if (cond) { printf(format, ##__VA_ARGS__); } \
6028 #define VM_PRESSURE_DEBUG(cond, format, ...)
6031 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
6033 void memorystatus_on_pageout_scan_end(void) {
6040 * knote_pressure_level - to check if the knote is registered for this notification level.
6042 * task - task whose bits we'll be modifying
6044 * 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.
6046 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
6051 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
)
6053 if (kn_max
->kn_sfflags
& knote_pressure_level
) {
6055 if (pressure_level_to_clear
&& task_has_been_notified(task
, pressure_level_to_clear
) == TRUE
) {
6057 task_clear_has_been_notified(task
, pressure_level_to_clear
);
6060 task_mark_has_been_notified(task
, pressure_level_to_set
);
6068 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear
)
6070 struct knote
*kn
= NULL
;
6072 memorystatus_klist_lock();
6073 SLIST_FOREACH(kn
, &memorystatus_klist
, kn_selnext
) {
6075 proc_t p
= PROC_NULL
;
6076 struct task
* t
= TASK_NULL
;
6078 p
= knote_get_kq(kn
)->kq_p
;
6080 if (p
!= proc_ref_locked(p
)) {
6087 t
= (struct task
*)(p
->task
);
6089 task_clear_has_been_notified(t
, pressure_level_to_clear
);
6094 memorystatus_klist_unlock();
6097 extern kern_return_t
vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process
);
6100 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
);
6103 * Used by the vm_pressure_thread which is
6104 * signalled from within vm_pageout_scan().
6106 static void vm_dispatch_memory_pressure(void);
6107 void consider_vm_pressure_events(void);
6109 void consider_vm_pressure_events(void)
6111 vm_dispatch_memory_pressure();
6113 static void vm_dispatch_memory_pressure(void)
6115 memorystatus_update_vm_pressure(FALSE
);
6118 extern vm_pressure_level_t
6119 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t
);
6122 vm_pressure_select_optimal_candidate_to_notify(struct klist
*candidate_list
, int level
, boolean_t target_foreground_process
)
6124 struct knote
*kn
= NULL
, *kn_max
= NULL
;
6125 uint64_t resident_max
= 0; /* MB */
6126 struct timeval curr_tstamp
= {0, 0};
6127 int elapsed_msecs
= 0;
6128 int selected_task_importance
= 0;
6129 static int pressure_snapshot
= -1;
6130 boolean_t pressure_increase
= FALSE
;
6132 if (pressure_snapshot
== -1) {
6136 pressure_snapshot
= level
;
6137 pressure_increase
= TRUE
;
6140 if (level
>= pressure_snapshot
) {
6141 pressure_increase
= TRUE
;
6143 pressure_increase
= FALSE
;
6146 pressure_snapshot
= level
;
6149 if (pressure_increase
== TRUE
) {
6151 * We'll start by considering the largest
6152 * unimportant task in our list.
6154 selected_task_importance
= INT_MAX
;
6157 * We'll start by considering the largest
6158 * important task in our list.
6160 selected_task_importance
= 0;
6163 microuptime(&curr_tstamp
);
6165 SLIST_FOREACH(kn
, candidate_list
, kn_selnext
) {
6167 uint64_t resident_size
= 0; /* MB */
6168 proc_t p
= PROC_NULL
;
6169 struct task
* t
= TASK_NULL
;
6170 int curr_task_importance
= 0;
6171 boolean_t consider_knote
= FALSE
;
6172 boolean_t privileged_listener
= FALSE
;
6174 p
= knote_get_kq(kn
)->kq_p
;
6176 if (p
!= proc_ref_locked(p
)) {
6183 #if CONFIG_MEMORYSTATUS
6184 if (target_foreground_process
== TRUE
&& !memorystatus_is_foreground_locked(p
)) {
6186 * Skip process not marked foreground.
6191 #endif /* CONFIG_MEMORYSTATUS */
6193 t
= (struct task
*)(p
->task
);
6195 timevalsub(&curr_tstamp
, &p
->vm_pressure_last_notify_tstamp
);
6196 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6198 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(level
);
6200 if ((kn
->kn_sfflags
& dispatch_level
) == 0) {
6205 #if CONFIG_MEMORYSTATUS
6206 if (target_foreground_process
== FALSE
&& !memorystatus_bg_pressure_eligible(p
)) {
6207 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p
->p_pid
);
6211 #endif /* CONFIG_MEMORYSTATUS */
6213 curr_task_importance
= task_importance_estimate(t
);
6216 * Privileged listeners are only considered in the multi-level pressure scheme
6217 * AND only if the pressure is increasing.
6221 if (task_has_been_notified(t
, level
) == FALSE
) {
6224 * Is this a privileged listener?
6226 if (task_low_mem_privileged_listener(t
, FALSE
, &privileged_listener
) == 0) {
6228 if (privileged_listener
) {
6238 } else if (level
== 0) {
6241 * Task wasn't notified when the pressure was increasing and so
6242 * no need to notify it that the pressure is decreasing.
6244 if ((task_has_been_notified(t
, kVMPressureWarning
) == FALSE
) && (task_has_been_notified(t
, kVMPressureCritical
) == FALSE
)) {
6251 * We don't want a small process to block large processes from
6252 * being notified again. <rdar://problem/7955532>
6254 resident_size
= (get_task_phys_footprint(t
))/(1024*1024ULL); /* MB */
6256 if (resident_size
>= VM_PRESSURE_MINIMUM_RSIZE
) {
6260 * Warning or Critical Pressure.
6262 if (pressure_increase
) {
6263 if ((curr_task_importance
< selected_task_importance
) ||
6264 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6267 * We have found a candidate process which is:
6268 * a) at a lower importance than the current selected process
6270 * b) has importance equal to that of the current selected process but is larger
6273 consider_knote
= TRUE
;
6276 if ((curr_task_importance
> selected_task_importance
) ||
6277 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6280 * We have found a candidate process which is:
6281 * a) at a higher importance than the current selected process
6283 * b) has importance equal to that of the current selected process but is larger
6286 consider_knote
= TRUE
;
6289 } else if (level
== 0) {
6291 * Pressure back to normal.
6293 if ((curr_task_importance
> selected_task_importance
) ||
6294 ((curr_task_importance
== selected_task_importance
) && (resident_size
> resident_max
))) {
6296 consider_knote
= TRUE
;
6300 if (consider_knote
) {
6301 resident_max
= resident_size
;
6303 selected_task_importance
= curr_task_importance
;
6304 consider_knote
= FALSE
; /* reset for the next candidate */
6307 /* There was no candidate with enough resident memory to scavenge */
6308 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p
->p_pid
, resident_size
);
6315 VM_DEBUG_CONSTANT_EVENT(vm_pressure_event
, VM_PRESSURE_EVENT
, DBG_FUNC_NONE
, knote_get_kq(kn_max
)->kq_p
->p_pid
, resident_max
, 0, 0);
6316 VM_PRESSURE_DEBUG(1, "[vm_pressure] sending event to pid %d with %llu resident\n", knote_get_kq(kn_max
)->kq_p
->p_pid
, resident_max
);
6322 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
6323 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6324 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6326 uint64_t next_warning_notification_sent_at_ts
= 0;
6327 uint64_t next_critical_notification_sent_at_ts
= 0;
6330 memorystatus_update_vm_pressure(boolean_t target_foreground_process
)
6332 struct knote
*kn_max
= NULL
;
6333 struct knote
*kn_cur
= NULL
, *kn_temp
= NULL
; /* for safe list traversal */
6334 pid_t target_pid
= -1;
6335 struct klist dispatch_klist
= { NULL
};
6336 proc_t target_proc
= PROC_NULL
;
6337 struct task
*task
= NULL
;
6338 boolean_t found_candidate
= FALSE
;
6340 static vm_pressure_level_t level_snapshot
= kVMPressureNormal
;
6341 static vm_pressure_level_t prev_level_snapshot
= kVMPressureNormal
;
6342 boolean_t smoothing_window_started
= FALSE
;
6343 struct timeval smoothing_window_start_tstamp
= {0, 0};
6344 struct timeval curr_tstamp
= {0, 0};
6345 int elapsed_msecs
= 0;
6346 uint64_t curr_ts
= mach_absolute_time();
6349 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
6351 int idle_kill_counter
= 0;
6354 * On desktop we take this opportunity to free up memory pressure
6355 * by immediately killing idle exitable processes. We use a delay
6356 * to avoid overkill. And we impose a max counter as a fail safe
6357 * in case daemons re-launch too fast.
6359 while ((memorystatus_vm_pressure_level
!= kVMPressureNormal
) && (idle_kill_counter
< MAX_IDLE_KILLS
)) {
6360 if (memorystatus_idle_exit_from_VM() == FALSE
) {
6361 /* No idle exitable processes left to kill */
6364 idle_kill_counter
++;
6366 if (memorystatus_manual_testing_on
== TRUE
) {
6368 * Skip the delay when testing
6369 * the pressure notification scheme.
6372 delay(1000000); /* 1 second */
6375 #endif /* !CONFIG_JETSAM */
6377 if (level_snapshot
!= kVMPressureNormal
) {
6380 * Check to see if we are still in the 'resting' period
6381 * after having notified all clients interested in
6382 * a particular pressure level.
6385 level_snapshot
= memorystatus_vm_pressure_level
;
6387 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6389 if (curr_ts
< next_warning_notification_sent_at_ts
) {
6390 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6391 return KERN_SUCCESS
;
6393 } else if (level_snapshot
== kVMPressureCritical
) {
6395 if (curr_ts
< next_critical_notification_sent_at_ts
) {
6396 delay(INTER_NOTIFICATION_DELAY
* 4 /* 1 sec */);
6397 return KERN_SUCCESS
;
6405 * There is a race window here. But it's not clear
6406 * how much we benefit from having extra synchronization.
6408 level_snapshot
= memorystatus_vm_pressure_level
;
6410 if (prev_level_snapshot
> level_snapshot
) {
6412 * Pressure decreased? Let's take a little breather
6413 * and see if this condition stays.
6415 if (smoothing_window_started
== FALSE
) {
6417 smoothing_window_started
= TRUE
;
6418 microuptime(&smoothing_window_start_tstamp
);
6421 microuptime(&curr_tstamp
);
6422 timevalsub(&curr_tstamp
, &smoothing_window_start_tstamp
);
6423 elapsed_msecs
= curr_tstamp
.tv_sec
* 1000 + curr_tstamp
.tv_usec
/ 1000;
6425 if (elapsed_msecs
< VM_PRESSURE_DECREASED_SMOOTHING_PERIOD
) {
6427 delay(INTER_NOTIFICATION_DELAY
);
6432 prev_level_snapshot
= level_snapshot
;
6433 smoothing_window_started
= FALSE
;
6435 memorystatus_klist_lock();
6436 kn_max
= vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist
, level_snapshot
, target_foreground_process
);
6438 if (kn_max
== NULL
) {
6439 memorystatus_klist_unlock();
6442 * No more level-based clients to notify.
6444 * Start the 'resting' window within which clients will not be re-notified.
6447 if (level_snapshot
!= kVMPressureNormal
) {
6448 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6449 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6450 next_warning_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6452 memorystatus_klist_reset_all_for_level(kVMPressureWarning
);
6455 if (level_snapshot
== kVMPressureCritical
) {
6456 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD
* NSEC_PER_SEC
, &curr_ts
);
6457 next_critical_notification_sent_at_ts
= mach_absolute_time() + curr_ts
;
6459 memorystatus_klist_reset_all_for_level(kVMPressureCritical
);
6462 return KERN_FAILURE
;
6465 target_proc
= knote_get_kq(kn_max
)->kq_p
;
6468 if (target_proc
!= proc_ref_locked(target_proc
)) {
6469 target_proc
= PROC_NULL
;
6471 memorystatus_klist_unlock();
6476 target_pid
= target_proc
->p_pid
;
6478 task
= (struct task
*)(target_proc
->task
);
6480 if (level_snapshot
!= kVMPressureNormal
) {
6482 if (level_snapshot
== kVMPressureWarning
|| level_snapshot
== kVMPressureUrgent
) {
6484 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_WARN
, task
, 0, kVMPressureWarning
) == TRUE
) {
6485 found_candidate
= TRUE
;
6488 if (level_snapshot
== kVMPressureCritical
) {
6490 if (is_knote_registered_modify_task_pressure_bits(kn_max
, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
, task
, 0, kVMPressureCritical
) == TRUE
) {
6491 found_candidate
= TRUE
;
6496 if (kn_max
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6498 task_clear_has_been_notified(task
, kVMPressureWarning
);
6499 task_clear_has_been_notified(task
, kVMPressureCritical
);
6501 found_candidate
= TRUE
;
6505 if (found_candidate
== FALSE
) {
6506 proc_rele(target_proc
);
6507 memorystatus_klist_unlock();
6511 SLIST_FOREACH_SAFE(kn_cur
, &memorystatus_klist
, kn_selnext
, kn_temp
) {
6513 int knote_pressure_level
= convert_internal_pressure_level_to_dispatch_level(level_snapshot
);
6515 if (is_knote_registered_modify_task_pressure_bits(kn_cur
, knote_pressure_level
, task
, 0, level_snapshot
) == TRUE
) {
6516 proc_t knote_proc
= knote_get_kq(kn_cur
)->kq_p
;
6517 pid_t knote_pid
= knote_proc
->p_pid
;
6518 if (knote_pid
== target_pid
) {
6519 KNOTE_DETACH(&memorystatus_klist
, kn_cur
);
6520 KNOTE_ATTACH(&dispatch_klist
, kn_cur
);
6525 KNOTE(&dispatch_klist
, (level_snapshot
!= kVMPressureNormal
) ? kMemorystatusPressure
: kMemorystatusNoPressure
);
6527 SLIST_FOREACH_SAFE(kn_cur
, &dispatch_klist
, kn_selnext
, kn_temp
) {
6528 KNOTE_DETACH(&dispatch_klist
, kn_cur
);
6529 KNOTE_ATTACH(&memorystatus_klist
, kn_cur
);
6532 memorystatus_klist_unlock();
6534 microuptime(&target_proc
->vm_pressure_last_notify_tstamp
);
6535 proc_rele(target_proc
);
6537 if (memorystatus_manual_testing_on
== TRUE
&& target_foreground_process
== TRUE
) {
6541 if (memorystatus_manual_testing_on
== TRUE
) {
6543 * Testing out the pressure notification scheme.
6544 * No need for delays etc.
6548 uint32_t sleep_interval
= INTER_NOTIFICATION_DELAY
;
6550 unsigned int page_delta
= 0;
6551 unsigned int skip_delay_page_threshold
= 0;
6553 assert(memorystatus_available_pages_pressure
>= memorystatus_available_pages_critical_base
);
6555 page_delta
= (memorystatus_available_pages_pressure
- memorystatus_available_pages_critical_base
) / 2;
6556 skip_delay_page_threshold
= memorystatus_available_pages_pressure
- page_delta
;
6558 if (memorystatus_available_pages
<= skip_delay_page_threshold
) {
6560 * We are nearing the critcal mark fast and can't afford to wait between
6565 #endif /* CONFIG_JETSAM */
6567 if (sleep_interval
) {
6568 delay(sleep_interval
);
6573 return KERN_SUCCESS
;
6577 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level
)
6579 vm_pressure_level_t dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6581 switch (internal_pressure_level
) {
6583 case kVMPressureNormal
:
6585 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
6589 case kVMPressureWarning
:
6590 case kVMPressureUrgent
:
6592 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
6596 case kVMPressureCritical
:
6598 dispatch_level
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
6606 return dispatch_level
;
6610 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
6612 #pragma unused(arg1, arg2, oidp)
6613 vm_pressure_level_t dispatch_level
= convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level
);
6615 return SYSCTL_OUT(req
, &dispatch_level
, sizeof(dispatch_level
));
6618 #if DEBUG || DEVELOPMENT
6620 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
,
6621 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6623 #else /* DEBUG || DEVELOPMENT */
6625 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_vm_pressure_level
, CTLTYPE_INT
|CTLFLAG_RD
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6626 0, 0, &sysctl_memorystatus_vm_pressure_level
, "I", "");
6628 #endif /* DEBUG || DEVELOPMENT */
6630 extern int memorystatus_purge_on_warning
;
6631 extern int memorystatus_purge_on_critical
;
6634 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
6636 #pragma unused(arg1, arg2)
6640 int pressure_level
= 0;
6641 int trigger_request
= 0;
6644 error
= sysctl_handle_int(oidp
, &level
, 0, req
);
6645 if (error
|| !req
->newptr
) {
6649 memorystatus_manual_testing_on
= TRUE
;
6651 trigger_request
= (level
>> 16) & 0xFFFF;
6652 pressure_level
= (level
& 0xFFFF);
6654 if (trigger_request
< TEST_LOW_MEMORY_TRIGGER_ONE
||
6655 trigger_request
> TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
) {
6658 switch (pressure_level
) {
6659 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL
:
6660 case NOTE_MEMORYSTATUS_PRESSURE_WARN
:
6661 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
:
6668 * The pressure level is being set from user-space.
6669 * And user-space uses the constants in sys/event.h
6670 * So we translate those events to our internal levels here.
6672 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6674 memorystatus_manual_testing_level
= kVMPressureNormal
;
6677 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
6679 memorystatus_manual_testing_level
= kVMPressureWarning
;
6680 force_purge
= memorystatus_purge_on_warning
;
6682 } else if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
6684 memorystatus_manual_testing_level
= kVMPressureCritical
;
6685 force_purge
= memorystatus_purge_on_critical
;
6688 memorystatus_vm_pressure_level
= memorystatus_manual_testing_level
;
6690 /* purge according to the new pressure level */
6691 switch (trigger_request
) {
6692 case TEST_PURGEABLE_TRIGGER_ONE
:
6693 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
:
6694 if (force_purge
== 0) {
6695 /* no purging requested */
6698 vm_purgeable_object_purge_one_unlocked(force_purge
);
6700 case TEST_PURGEABLE_TRIGGER_ALL
:
6701 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
:
6702 if (force_purge
== 0) {
6703 /* no purging requested */
6706 while (vm_purgeable_object_purge_one_unlocked(force_purge
));
6710 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ONE
) ||
6711 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE
)) {
6713 memorystatus_update_vm_pressure(TRUE
);
6716 if ((trigger_request
== TEST_LOW_MEMORY_TRIGGER_ALL
) ||
6717 (trigger_request
== TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL
)) {
6719 while (memorystatus_update_vm_pressure(FALSE
) == KERN_SUCCESS
) {
6724 if (pressure_level
== NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
6725 memorystatus_manual_testing_on
= FALSE
;
6731 SYSCTL_PROC(_kern
, OID_AUTO
, memorypressure_manual_trigger
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6732 0, 0, &sysctl_memorypressure_manual_trigger
, "I", "");
6735 extern int memorystatus_purge_on_warning
;
6736 extern int memorystatus_purge_on_urgent
;
6737 extern int memorystatus_purge_on_critical
;
6739 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_warning
, CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_warning
, 0, "");
6740 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_urgent
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_urgent
, 0, "");
6741 SYSCTL_INT(_kern
, OID_AUTO
, memorystatus_purge_on_critical
, CTLTYPE_INT
|CTLFLAG_RW
|CTLFLAG_LOCKED
, &memorystatus_purge_on_critical
, 0, "");
6744 #endif /* VM_PRESSURE_EVENTS */
6746 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
6748 memorystatus_get_priority_list(memorystatus_priority_entry_t
**list_ptr
, size_t *buffer_size
, size_t *list_size
, boolean_t size_only
)
6750 uint32_t list_count
, i
= 0;
6751 memorystatus_priority_entry_t
*list_entry
;
6754 list_count
= memorystatus_list_count
;
6755 *list_size
= sizeof(memorystatus_priority_entry_t
) * list_count
;
6757 /* Just a size check? */
6762 /* Otherwise, validate the size of the buffer */
6763 if (*buffer_size
< *list_size
) {
6767 *list_ptr
= (memorystatus_priority_entry_t
*)kalloc(*list_size
);
6772 memset(*list_ptr
, 0, *list_size
);
6774 *buffer_size
= *list_size
;
6777 list_entry
= *list_ptr
;
6781 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6782 while (p
&& (*list_size
< *buffer_size
)) {
6783 list_entry
->pid
= p
->p_pid
;
6784 list_entry
->priority
= p
->p_memstat_effectivepriority
;
6785 list_entry
->user_data
= p
->p_memstat_userdata
;
6788 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
6789 * Background limits are described via the inactive limit slots.
6790 * So, here, the cached limit should always be valid.
6793 if (p
->p_memstat_memlimit
<= 0) {
6794 task_get_phys_footprint_limit(p
->task
, &list_entry
->limit
);
6796 list_entry
->limit
= p
->p_memstat_memlimit
;
6799 list_entry
->state
= memorystatus_build_state(p
);
6802 *list_size
+= sizeof(memorystatus_priority_entry_t
);
6804 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6809 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size
);
6815 memorystatus_cmd_get_priority_list(user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
6817 boolean_t size_only
;
6818 memorystatus_priority_entry_t
*list
= NULL
;
6821 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
6823 error
= memorystatus_get_priority_list(&list
, &buffer_size
, &list_size
, size_only
);
6829 error
= copyout(list
, buffer
, list_size
);
6833 *retval
= list_size
;
6838 kfree(list
, buffer_size
);
6847 memorystatus_clear_errors(void)
6852 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
6856 p
= memorystatus_get_first_proc_locked(&i
, TRUE
);
6858 if (p
->p_memstat_state
& P_MEMSTAT_ERROR
) {
6859 p
->p_memstat_state
&= ~P_MEMSTAT_ERROR
;
6861 p
= memorystatus_get_next_proc_locked(&i
, p
, TRUE
);
6866 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_CLEAR_ERRORS
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
6870 memorystatus_update_levels_locked(boolean_t critical_only
) {
6872 memorystatus_available_pages_critical
= memorystatus_available_pages_critical_base
;
6875 * If there's an entry in the first bucket, we have idle processes.
6878 memstat_bucket_t
*first_bucket
= &memstat_bucket
[JETSAM_PRIORITY_IDLE
];
6879 if (first_bucket
->count
) {
6880 memorystatus_available_pages_critical
+= memorystatus_available_pages_critical_idle_offset
;
6882 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6884 * The critical threshold must never exceed the pressure threshold
6886 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6890 #if DEBUG || DEVELOPMENT
6891 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6892 memorystatus_available_pages_critical
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6894 if (memorystatus_available_pages_critical
> memorystatus_available_pages_pressure
) {
6896 * The critical threshold must never exceed the pressure threshold
6898 memorystatus_available_pages_critical
= memorystatus_available_pages_pressure
;
6903 if (memorystatus_jetsam_policy
& kPolicyMoreFree
) {
6904 memorystatus_available_pages_critical
+= memorystatus_policy_more_free_offset_pages
;
6907 if (critical_only
) {
6911 #if VM_PRESSURE_EVENTS
6912 memorystatus_available_pages_pressure
= (pressure_threshold_percentage
/ delta_percentage
) * memorystatus_delta
;
6913 #if DEBUG || DEVELOPMENT
6914 if (memorystatus_jetsam_policy
& kPolicyDiagnoseActive
) {
6915 memorystatus_available_pages_pressure
+= memorystatus_jetsam_policy_offset_pages_diagnostic
;
6922 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
6924 #pragma unused(arg1, arg2, oidp)
6925 int error
= 0, more_free
= 0;
6928 * TODO: Enable this privilege check?
6930 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
6935 error
= sysctl_handle_int(oidp
, &more_free
, 0, req
);
6936 if (error
|| !req
->newptr
)
6939 if ((more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == kPolicyMoreFree
)) ||
6940 (!more_free
&& ((memorystatus_jetsam_policy
& kPolicyMoreFree
) == 0))) {
6943 * No change in state.
6951 memorystatus_jetsam_policy
|= kPolicyMoreFree
;
6953 memorystatus_jetsam_policy
&= ~kPolicyMoreFree
;
6956 memorystatus_update_levels_locked(TRUE
);
6962 SYSCTL_PROC(_kern
, OID_AUTO
, memorystatus_policy_more_free
, CTLTYPE_INT
|CTLFLAG_WR
|CTLFLAG_LOCKED
|CTLFLAG_MASKED
,
6963 0, 0, &sysctl_kern_memorystatus_policy_more_free
, "I", "");
6966 * Get the at_boot snapshot
6969 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
6970 size_t input_size
= *snapshot_size
;
6973 * The at_boot snapshot has no entry list.
6975 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
);
6982 * Validate the size of the snapshot buffer
6984 if (input_size
< *snapshot_size
) {
6989 * Update the notification_time only
6991 memorystatus_at_boot_snapshot
.notification_time
= mach_absolute_time();
6992 *snapshot
= &memorystatus_at_boot_snapshot
;
6994 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
6995 (long)input_size
, (long)*snapshot_size
, 0);
7000 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7001 size_t input_size
= *snapshot_size
;
7002 uint32_t ods_list_count
= memorystatus_list_count
;
7003 memorystatus_jetsam_snapshot_t
*ods
= NULL
; /* The on_demand snapshot buffer */
7005 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (ods_list_count
));
7012 * Validate the size of the snapshot buffer.
7013 * This is inherently racey. May want to revisit
7014 * this error condition and trim the output when
7017 if (input_size
< *snapshot_size
) {
7022 * Allocate and initialize a snapshot buffer.
7024 ods
= (memorystatus_jetsam_snapshot_t
*)kalloc(*snapshot_size
);
7029 memset(ods
, 0, *snapshot_size
);
7032 memorystatus_init_jetsam_snapshot_locked(ods
, ods_list_count
);
7036 * Return the kernel allocated, on_demand buffer.
7037 * The caller of this routine will copy the data out
7038 * to user space and then free the kernel allocated
7043 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7044 (long)input_size
, (long)*snapshot_size
, (long)ods_list_count
);
7050 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t
**snapshot
, size_t *snapshot_size
, boolean_t size_only
) {
7051 size_t input_size
= *snapshot_size
;
7053 if (memorystatus_jetsam_snapshot_count
> 0) {
7054 *snapshot_size
= sizeof(memorystatus_jetsam_snapshot_t
) + (sizeof(memorystatus_jetsam_snapshot_entry_t
) * (memorystatus_jetsam_snapshot_count
));
7063 if (input_size
< *snapshot_size
) {
7067 *snapshot
= memorystatus_jetsam_snapshot
;
7069 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7070 (long)input_size
, (long)*snapshot_size
, (long)memorystatus_jetsam_snapshot_count
);
7077 memorystatus_cmd_get_jetsam_snapshot(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, int32_t *retval
) {
7079 boolean_t size_only
;
7080 boolean_t is_default_snapshot
= FALSE
;
7081 boolean_t is_on_demand_snapshot
= FALSE
;
7082 boolean_t is_at_boot_snapshot
= FALSE
;
7083 memorystatus_jetsam_snapshot_t
*snapshot
;
7085 size_only
= ((buffer
== USER_ADDR_NULL
) ? TRUE
: FALSE
);
7089 is_default_snapshot
= TRUE
;
7090 error
= memorystatus_get_jetsam_snapshot(&snapshot
, &buffer_size
, size_only
);
7092 if (flags
& ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7094 * Unsupported bit set in flag.
7099 if ((flags
& (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) ==
7100 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND
| MEMORYSTATUS_SNAPSHOT_AT_BOOT
)) {
7102 * Can't have both set at the same time.
7107 if (flags
& MEMORYSTATUS_SNAPSHOT_ON_DEMAND
) {
7108 is_on_demand_snapshot
= TRUE
;
7110 * When not requesting the size only, the following call will allocate
7111 * an on_demand snapshot buffer, which is freed below.
7113 error
= memorystatus_get_on_demand_snapshot(&snapshot
, &buffer_size
, size_only
);
7115 } else if (flags
& MEMORYSTATUS_SNAPSHOT_AT_BOOT
) {
7116 is_at_boot_snapshot
= TRUE
;
7117 error
= memorystatus_get_at_boot_snapshot(&snapshot
, &buffer_size
, size_only
);
7120 * Invalid flag setting.
7131 * Copy the data out to user space and clear the snapshot buffer.
7132 * If working with the jetsam snapshot,
7133 * clearing the buffer means, reset the count.
7134 * If working with an on_demand snapshot
7135 * clearing the buffer means, free it.
7136 * If working with the at_boot snapshot
7137 * there is nothing to clear or update.
7140 if ((error
= copyout(snapshot
, buffer
, buffer_size
)) == 0) {
7141 if (is_default_snapshot
) {
7143 * The jetsam snapshot is never freed, its count is simply reset.
7146 snapshot
->entry_count
= memorystatus_jetsam_snapshot_count
= 0;
7147 memorystatus_jetsam_snapshot_last_timestamp
= 0;
7152 if (is_on_demand_snapshot
) {
7154 * The on_demand snapshot is always freed,
7155 * even if the copyout failed.
7158 kfree(snapshot
, buffer_size
);
7164 *retval
= buffer_size
;
7171 * Routine: memorystatus_cmd_grp_set_properties
7172 * Purpose: Update properties for a group of processes.
7174 * Supported Properties:
7176 * Move each process out of its effective priority
7177 * band and into a new priority band.
7178 * Maintains relative order from lowest to highest priority.
7179 * In single band, maintains relative order from head to tail.
7181 * eg: before [effectivepriority | pid]
7183 * [17 | p55, p67, p19 ]
7188 * after [ new band | pid]
7189 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7191 * Returns: 0 on success, else non-zero.
7193 * Caveat: We know there is a race window regarding recycled pids.
7194 * A process could be killed before the kernel can act on it here.
7195 * If a pid cannot be found in any of the jetsam priority bands,
7196 * then we simply ignore it. No harm.
7197 * But, if the pid has been recycled then it could be an issue.
7198 * In that scenario, we might move an unsuspecting process to the new
7199 * priority band. It's not clear how the kernel can safeguard
7200 * against this, but it would be an extremely rare case anyway.
7201 * The caller of this api might avoid such race conditions by
7202 * ensuring that the processes passed in the pid list are suspended.
7206 /* This internal structure can expand when we add support for more properties */
7207 typedef struct memorystatus_internal_properties
7210 int32_t priority
; /* see memorytstatus_priority_entry_t : priority */
7211 } memorystatus_internal_properties_t
;
7215 memorystatus_cmd_grp_set_properties(int32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7217 #pragma unused (flags)
7220 * We only handle setting priority
7225 memorystatus_priority_entry_t
*entries
= NULL
;
7226 uint32_t entry_count
= 0;
7228 /* This will be the ordered proc list */
7229 memorystatus_internal_properties_t
*table
= NULL
;
7230 size_t table_size
= 0;
7231 uint32_t table_count
= 0;
7234 uint32_t bucket_index
= 0;
7235 boolean_t head_insert
;
7236 int32_t new_priority
;
7241 if ((buffer
== USER_ADDR_NULL
) || (buffer_size
== 0) || ((buffer_size
% sizeof(memorystatus_priority_entry_t
)) != 0)) {
7246 entry_count
= (buffer_size
/ sizeof(memorystatus_priority_entry_t
));
7247 if ((entries
= (memorystatus_priority_entry_t
*)kalloc(buffer_size
)) == NULL
) {
7252 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_START
, entry_count
, 0, 0, 0, 0);
7254 if ((error
= copyin(buffer
, entries
, buffer_size
)) != 0) {
7258 /* Verify sanity of input priorities */
7259 for (i
=0; i
< entry_count
; i
++) {
7260 if (entries
[i
].priority
== -1) {
7261 /* Use as shorthand for default priority */
7262 entries
[i
].priority
= JETSAM_PRIORITY_DEFAULT
;
7263 } else if ((entries
[i
].priority
== system_procs_aging_band
) || (entries
[i
].priority
== applications_aging_band
)) {
7264 /* Both the aging bands are reserved for internal use;
7265 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
7266 entries
[i
].priority
= JETSAM_PRIORITY_IDLE
;
7267 } else if (entries
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7268 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7270 /* Deal with this later */
7271 } else if ((entries
[i
].priority
< 0) || (entries
[i
].priority
>= MEMSTAT_BUCKET_COUNT
)) {
7278 table_size
= sizeof(memorystatus_internal_properties_t
) * entry_count
;
7279 if ( (table
= (memorystatus_internal_properties_t
*)kalloc(table_size
)) == NULL
) {
7283 memset(table
, 0, table_size
);
7287 * For each jetsam bucket entry, spin through the input property list.
7288 * When a matching pid is found, populate an adjacent table with the
7289 * appropriate proc pointer and new property values.
7290 * This traversal automatically preserves order from lowest
7291 * to highest priority.
7298 /* Create the ordered table */
7299 p
= memorystatus_get_first_proc_locked(&bucket_index
, TRUE
);
7300 while (p
&& (table_count
< entry_count
)) {
7301 for (i
=0; i
< entry_count
; i
++ ) {
7302 if (p
->p_pid
== entries
[i
].pid
) {
7303 /* Build the table data */
7304 table
[table_count
].proc
= p
;
7305 table
[table_count
].priority
= entries
[i
].priority
;
7310 p
= memorystatus_get_next_proc_locked(&bucket_index
, p
, TRUE
);
7313 /* We now have ordered list of procs ready to move */
7314 for (i
=0; i
< table_count
; i
++) {
7318 /* Allow head inserts -- but relative order is now */
7319 if (table
[i
].priority
== JETSAM_PRIORITY_IDLE_HEAD
) {
7320 new_priority
= JETSAM_PRIORITY_IDLE
;
7323 new_priority
= table
[i
].priority
;
7324 head_insert
= false;
7328 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7333 * Take appropriate steps if moving proc out of
7334 * either of the aging bands.
7336 if ((p
->p_memstat_effectivepriority
== system_procs_aging_band
) || (p
->p_memstat_effectivepriority
== applications_aging_band
)) {
7337 memorystatus_invalidate_idle_demotion_locked(p
, TRUE
);
7340 memorystatus_update_priority_locked(p
, new_priority
, head_insert
, false);
7346 * if (table_count != entry_count)
7347 * then some pids were not found in a jetsam band.
7348 * harmless but interesting...
7350 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT
, BSD_MEMSTAT_GRP_SET_PROP
) | DBG_FUNC_END
, entry_count
, table_count
, 0, 0, 0);
7354 kfree(entries
, buffer_size
);
7356 kfree(table
, table_size
);
7363 * This routine is used to update a process's jetsam priority position and stored user_data.
7364 * It is not used for the setting of memory limits, which is why the last 6 args to the
7365 * memorystatus_update() call are 0 or FALSE.
7369 memorystatus_cmd_set_priority_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7371 memorystatus_priority_properties_t mpp_entry
;
7373 /* Validate inputs */
7374 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_priority_properties_t
))) {
7378 error
= copyin(buffer
, &mpp_entry
, buffer_size
);
7388 if (p
->p_memstat_state
& P_MEMSTAT_INTERNAL
) {
7393 error
= memorystatus_update(p
, mpp_entry
.priority
, mpp_entry
.user_data
, FALSE
, FALSE
, 0, 0, FALSE
, FALSE
, FALSE
);
7401 memorystatus_cmd_set_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7403 memorystatus_memlimit_properties_t mmp_entry
;
7405 /* Validate inputs */
7406 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7410 error
= copyin(buffer
, &mmp_entry
, buffer_size
);
7413 error
= memorystatus_set_memlimit_properties(pid
, &mmp_entry
);
7420 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7421 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7422 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
7423 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7424 * to the task's ledgers via task_set_phys_footprint_limit().
7427 memorystatus_cmd_get_memlimit_properties(pid_t pid
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7429 memorystatus_memlimit_properties_t mmp_entry
;
7431 /* Validate inputs */
7432 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(memorystatus_memlimit_properties_t
))) {
7436 memset (&mmp_entry
, 0, sizeof(memorystatus_memlimit_properties_t
));
7438 proc_t p
= proc_find(pid
);
7444 * Get the active limit and attributes.
7445 * No locks taken since we hold a reference to the proc.
7448 if (p
->p_memstat_memlimit_active
> 0 ) {
7449 mmp_entry
.memlimit_active
= p
->p_memstat_memlimit_active
;
7451 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_active
);
7454 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL
) {
7455 mmp_entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7459 * Get the inactive limit and attributes
7461 if (p
->p_memstat_memlimit_inactive
<= 0) {
7462 task_convert_phys_footprint_limit(-1, &mmp_entry
.memlimit_inactive
);
7464 mmp_entry
.memlimit_inactive
= p
->p_memstat_memlimit_inactive
;
7466 if (p
->p_memstat_state
& P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL
) {
7467 mmp_entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7471 error
= copyout(&mmp_entry
, buffer
, buffer_size
);
7478 * SPI for kbd - pr24956468
7479 * This is a very simple snapshot that calculates how much a
7480 * process's phys_footprint exceeds a specific memory limit.
7481 * Only the inactive memory limit is supported for now.
7482 * The delta is returned as bytes in excess or zero.
7485 memorystatus_cmd_get_memlimit_excess_np(pid_t pid
, uint32_t flags
, user_addr_t buffer
, size_t buffer_size
, __unused
int32_t *retval
) {
7487 uint64_t footprint_in_bytes
= 0;
7488 uint64_t delta_in_bytes
= 0;
7489 int32_t memlimit_mb
= 0;
7490 uint64_t memlimit_bytes
= 0;
7492 /* Validate inputs */
7493 if ((pid
== 0) || (buffer
== USER_ADDR_NULL
) || (buffer_size
!= sizeof(uint64_t)) || (flags
!= 0)) {
7497 proc_t p
= proc_find(pid
);
7503 * Get the inactive limit.
7504 * No locks taken since we hold a reference to the proc.
7507 if (p
->p_memstat_memlimit_inactive
<= 0) {
7508 task_convert_phys_footprint_limit(-1, &memlimit_mb
);
7510 memlimit_mb
= p
->p_memstat_memlimit_inactive
;
7513 footprint_in_bytes
= get_task_phys_footprint(p
->task
);
7517 memlimit_bytes
= memlimit_mb
* 1024 * 1024; /* MB to bytes */
7520 * Computed delta always returns >= 0 bytes
7522 if (footprint_in_bytes
> memlimit_bytes
) {
7523 delta_in_bytes
= footprint_in_bytes
- memlimit_bytes
;
7526 error
= copyout(&delta_in_bytes
, buffer
, sizeof(delta_in_bytes
));
7533 memorystatus_cmd_get_pressure_status(int32_t *retval
) {
7536 /* Need privilege for check */
7537 error
= priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE
, 0);
7542 /* Inherently racy, so it's not worth taking a lock here */
7543 *retval
= (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7549 memorystatus_get_pressure_status_kdp() {
7550 return (kVMPressureNormal
!= memorystatus_vm_pressure_level
) ? 1 : 0;
7554 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
7556 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
7557 * So, with 2-level HWM preserving previous behavior will map as follows.
7558 * - treat the limit passed in as both an active and inactive limit.
7559 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
7561 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
7562 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
7563 * - so mapping is (active/non-fatal, inactive/non-fatal)
7565 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
7566 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
7567 * - so mapping is (active/fatal, inactive/fatal)
7571 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid
, int32_t high_water_mark
, __unused
int32_t *retval
, boolean_t is_fatal_limit
) {
7573 memorystatus_memlimit_properties_t entry
;
7575 entry
.memlimit_active
= high_water_mark
;
7576 entry
.memlimit_active_attr
= 0;
7577 entry
.memlimit_inactive
= high_water_mark
;
7578 entry
.memlimit_inactive_attr
= 0;
7580 if (is_fatal_limit
== TRUE
) {
7581 entry
.memlimit_active_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7582 entry
.memlimit_inactive_attr
|= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
;
7585 error
= memorystatus_set_memlimit_properties(pid
, &entry
);
7590 memorystatus_set_memlimit_properties(pid_t pid
, memorystatus_memlimit_properties_t
*entry
) {
7592 int32_t memlimit_active
;
7593 boolean_t memlimit_active_is_fatal
;
7594 int32_t memlimit_inactive
;
7595 boolean_t memlimit_inactive_is_fatal
;
7596 uint32_t valid_attrs
= 0;
7599 proc_t p
= proc_find(pid
);
7605 * Check for valid attribute flags.
7607 valid_attrs
|= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
);
7608 if ((entry
->memlimit_active_attr
& (~valid_attrs
)) != 0) {
7612 if ((entry
->memlimit_inactive_attr
& (~valid_attrs
)) != 0) {
7618 * Setup the active memlimit properties
7620 memlimit_active
= entry
->memlimit_active
;
7621 if (entry
->memlimit_active_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7622 memlimit_active_is_fatal
= TRUE
;
7624 memlimit_active_is_fatal
= FALSE
;
7628 * Setup the inactive memlimit properties
7630 memlimit_inactive
= entry
->memlimit_inactive
;
7631 if (entry
->memlimit_inactive_attr
& MEMORYSTATUS_MEMLIMIT_ATTR_FATAL
) {
7632 memlimit_inactive_is_fatal
= TRUE
;
7634 memlimit_inactive_is_fatal
= FALSE
;
7638 * Setting a limit of <= 0 implies that the process has no
7639 * high-water-mark and has no per-task-limit. That means
7640 * the system_wide task limit is in place, which by the way,
7644 if (memlimit_active
<= 0) {
7646 * Enforce the fatal system_wide task limit while process is active.
7648 memlimit_active
= -1;
7649 memlimit_active_is_fatal
= TRUE
;
7652 if (memlimit_inactive
<= 0) {
7654 * Enforce the fatal system_wide task limit while process is inactive.
7656 memlimit_inactive
= -1;
7657 memlimit_inactive_is_fatal
= TRUE
;
7663 * Store the active limit variants in the proc.
7665 SET_ACTIVE_LIMITS_LOCKED(p
, memlimit_active
, memlimit_active_is_fatal
);
7668 * Store the inactive limit variants in the proc.
7670 SET_INACTIVE_LIMITS_LOCKED(p
, memlimit_inactive
, memlimit_inactive_is_fatal
);
7673 * Enforce appropriate limit variant by updating the cached values
7674 * and writing the ledger.
7675 * Limit choice is based on process active/inactive state.
7678 if (memorystatus_highwater_enabled
) {
7679 boolean_t trigger_exception
;
7681 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
7682 * Background limits are described via the inactive limit slots.
7685 if (proc_jetsam_state_is_active_locked(p
) == TRUE
) {
7686 CACHE_ACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
7688 CACHE_INACTIVE_LIMITS_LOCKED(p
, trigger_exception
);
7691 /* Enforce the limit by writing to the ledgers */
7692 assert(trigger_exception
== TRUE
);
7693 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
;
7695 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
7696 p
->p_pid
, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1),
7697 (p
->p_memstat_state
& P_MEMSTAT_FATAL_MEMLIMIT
? "F " : "NF"), p
->p_memstat_effectivepriority
, p
->p_memstat_dirty
,
7698 (p
->p_memstat_dirty
? ((p
->p_memstat_dirty
& P_DIRTY
) ? "isdirty" : "isclean") : ""));
7699 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit
, proc_t
, p
, int32_t, (p
->p_memstat_memlimit
> 0 ? p
->p_memstat_memlimit
: -1));
7709 * Returns the jetsam priority (effective or requested) of the process
7710 * associated with this task.
7713 proc_get_memstat_priority(proc_t p
, boolean_t effective_priority
)
7716 if (effective_priority
) {
7717 return p
->p_memstat_effectivepriority
;
7719 return p
->p_memstat_requestedpriority
;
7725 #endif /* CONFIG_JETSAM */
7728 memorystatus_control(struct proc
*p __unused
, struct memorystatus_control_args
*args
, int *ret
) {
7730 os_reason_t jetsam_reason
= OS_REASON_NULL
;
7734 #pragma unused(jetsam_reason)
7737 /* Need to be root or have entitlement */
7738 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT
)) {
7745 * Do not enforce it for snapshots.
7747 if (args
->command
!= MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
) {
7748 if (args
->buffersize
> MEMORYSTATUS_BUFFERSIZE_MAX
) {
7754 switch (args
->command
) {
7755 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST
:
7756 error
= memorystatus_cmd_get_priority_list(args
->buffer
, args
->buffersize
, ret
);
7759 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
:
7760 error
= memorystatus_cmd_set_priority_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7762 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
:
7763 error
= memorystatus_cmd_set_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7765 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
:
7766 error
= memorystatus_cmd_get_memlimit_properties(args
->pid
, args
->buffer
, args
->buffersize
, ret
);
7768 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS
:
7769 error
= memorystatus_cmd_get_memlimit_excess_np(args
->pid
, args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7771 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES
:
7772 error
= memorystatus_cmd_grp_set_properties((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7774 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
:
7775 error
= memorystatus_cmd_get_jetsam_snapshot((int32_t)args
->flags
, args
->buffer
, args
->buffersize
, ret
);
7777 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS
:
7778 error
= memorystatus_cmd_get_pressure_status(ret
);
7780 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
:
7782 * This call does not distinguish between active and inactive limits.
7783 * Default behavior in 2-level HWM world is to set both.
7784 * Non-fatal limit is also assumed for both.
7786 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, FALSE
);
7788 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
:
7790 * This call does not distinguish between active and inactive limits.
7791 * Default behavior in 2-level HWM world is to set both.
7792 * Fatal limit is also assumed for both.
7794 error
= memorystatus_cmd_set_jetsam_memory_limit(args
->pid
, (int32_t)args
->flags
, ret
, TRUE
);
7797 #if DEVELOPMENT || DEBUG
7798 case MEMORYSTATUS_CMD_TEST_JETSAM
:
7799 jetsam_reason
= os_reason_create(OS_REASON_JETSAM
, JETSAM_REASON_GENERIC
);
7800 if (jetsam_reason
== OS_REASON_NULL
) {
7801 printf("memorystatus_control: failed to allocate jetsam reason\n");
7804 error
= memorystatus_kill_process_sync(args
->pid
, kMemorystatusKilled
, jetsam_reason
) ? 0 : EINVAL
;
7806 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT
:
7807 error
= memorystatus_cmd_test_jetsam_sort(args
->pid
, (int32_t)args
->flags
);
7809 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS
:
7810 error
= memorystatus_cmd_set_panic_bits(args
->buffer
, args
->buffersize
);
7812 #else /* DEVELOPMENT || DEBUG */
7813 #pragma unused(jetsam_reason)
7814 #endif /* DEVELOPMENT || DEBUG */
7815 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE
:
7816 if (memorystatus_aggressive_jetsam_lenient_allowed
== FALSE
) {
7817 #if DEVELOPMENT || DEBUG
7818 printf("Enabling Lenient Mode\n");
7819 #endif /* DEVELOPMENT || DEBUG */
7821 memorystatus_aggressive_jetsam_lenient_allowed
= TRUE
;
7822 memorystatus_aggressive_jetsam_lenient
= TRUE
;
7826 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE
:
7827 #if DEVELOPMENT || DEBUG
7828 printf("Disabling Lenient mode\n");
7829 #endif /* DEVELOPMENT || DEBUG */
7830 memorystatus_aggressive_jetsam_lenient_allowed
= FALSE
;
7831 memorystatus_aggressive_jetsam_lenient
= FALSE
;
7834 #endif /* CONFIG_JETSAM */
7835 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE
:
7836 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE
:
7837 error
= memorystatus_low_mem_privileged_listener(args
->command
);
7841 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE
:
7842 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE
:
7843 error
= memorystatus_update_inactive_jetsam_priority_band(args
->pid
, args
->command
, args
->flags
? TRUE
: FALSE
);
7845 #endif /* CONFIG_JETSAM */
7857 filt_memorystatusattach(struct knote
*kn
)
7861 kn
->kn_flags
|= EV_CLEAR
;
7862 error
= memorystatus_knote_register(kn
);
7864 kn
->kn_flags
= EV_ERROR
;
7865 kn
->kn_data
= error
;
7871 filt_memorystatusdetach(struct knote
*kn
)
7873 memorystatus_knote_unregister(kn
);
7877 filt_memorystatus(struct knote
*kn __unused
, long hint
)
7881 case kMemorystatusNoPressure
:
7882 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_NORMAL
) {
7883 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
;
7886 case kMemorystatusPressure
:
7887 if (memorystatus_vm_pressure_level
== kVMPressureWarning
|| memorystatus_vm_pressure_level
== kVMPressureUrgent
) {
7888 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_WARN
) {
7889 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_WARN
;
7891 } else if (memorystatus_vm_pressure_level
== kVMPressureCritical
) {
7893 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
) {
7894 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
;
7898 case kMemorystatusLowSwap
:
7899 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_LOW_SWAP
) {
7900 kn
->kn_fflags
= NOTE_MEMORYSTATUS_LOW_SWAP
;
7904 case kMemorystatusProcLimitWarn
:
7905 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
) {
7906 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
;
7910 case kMemorystatusProcLimitCritical
:
7911 if (kn
->kn_sfflags
& NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
) {
7912 kn
->kn_fflags
= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
;
7921 return (kn
->kn_fflags
!= 0);
7925 filt_memorystatustouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
7929 memorystatus_klist_lock();
7932 * copy in new kevent settings
7933 * (saving the "desired" data and fflags).
7935 kn
->kn_sfflags
= kev
->fflags
;
7937 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
7938 kn
->kn_udata
= kev
->udata
;
7941 * reset the output flags based on a
7942 * combination of the old events and
7943 * the new desired event list.
7945 //kn->kn_fflags &= kn->kn_sfflags;
7947 res
= (kn
->kn_fflags
!= 0);
7949 memorystatus_klist_unlock();
7955 filt_memorystatusprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
7957 #pragma unused(data)
7960 memorystatus_klist_lock();
7961 res
= (kn
->kn_fflags
!= 0);
7963 *kev
= kn
->kn_kevent
;
7964 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
7968 memorystatus_klist_unlock();
7974 memorystatus_klist_lock(void) {
7975 lck_mtx_lock(&memorystatus_klist_mutex
);
7979 memorystatus_klist_unlock(void) {
7980 lck_mtx_unlock(&memorystatus_klist_mutex
);
7984 memorystatus_kevent_init(lck_grp_t
*grp
, lck_attr_t
*attr
) {
7985 lck_mtx_init(&memorystatus_klist_mutex
, grp
, attr
);
7986 klist_init(&memorystatus_klist
);
7990 memorystatus_knote_register(struct knote
*kn
) {
7993 memorystatus_klist_lock();
7995 if (kn
->kn_sfflags
& (NOTE_MEMORYSTATUS_PRESSURE_NORMAL
| NOTE_MEMORYSTATUS_PRESSURE_WARN
|
7996 NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
| NOTE_MEMORYSTATUS_LOW_SWAP
|
7997 NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
| NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
)) {
7999 KNOTE_ATTACH(&memorystatus_klist
, kn
);
8005 memorystatus_klist_unlock();
8011 memorystatus_knote_unregister(struct knote
*kn __unused
) {
8012 memorystatus_klist_lock();
8013 KNOTE_DETACH(&memorystatus_klist
, kn
);
8014 memorystatus_klist_unlock();
8019 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
8021 memorystatus_issue_pressure_kevent(boolean_t pressured
) {
8022 memorystatus_klist_lock();
8023 KNOTE(&memorystatus_klist
, pressured
? kMemorystatusPressure
: kMemorystatusNoPressure
);
8024 memorystatus_klist_unlock();
8027 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
8031 /* Coalition support */
8033 /* sorting info for a particular priority bucket */
8034 typedef struct memstat_sort_info
{
8035 coalition_t msi_coal
;
8036 uint64_t msi_page_count
;
8039 } memstat_sort_info_t
;
8042 * qsort from smallest page count to largest page count
8044 * return < 0 for a < b
8048 static int memstat_asc_cmp(const void *a
, const void *b
)
8050 const memstat_sort_info_t
*msA
= (const memstat_sort_info_t
*)a
;
8051 const memstat_sort_info_t
*msB
= (const memstat_sort_info_t
*)b
;
8053 return (int)((uint64_t)msA
->msi_page_count
- (uint64_t)msB
->msi_page_count
);
8057 * Return the number of pids rearranged during this sort.
8060 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index
, int coal_sort_order
)
8062 #define MAX_SORT_PIDS 80
8063 #define MAX_COAL_LEADERS 10
8065 unsigned int b
= bucket_index
;
8069 coalition_t coal
= COALITION_NULL
;
8071 int total_pids_moved
= 0;
8075 * The system is typically under memory pressure when in this
8076 * path, hence, we want to avoid dynamic memory allocation.
8078 memstat_sort_info_t leaders
[MAX_COAL_LEADERS
];
8079 pid_t pid_list
[MAX_SORT_PIDS
];
8081 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8086 * Clear the array that holds coalition leader information
8088 for (i
=0; i
< MAX_COAL_LEADERS
; i
++) {
8089 leaders
[i
].msi_coal
= COALITION_NULL
;
8090 leaders
[i
].msi_page_count
= 0; /* will hold total coalition page count */
8091 leaders
[i
].msi_pid
= 0; /* will hold coalition leader pid */
8092 leaders
[i
].msi_ntasks
= 0; /* will hold the number of tasks in a coalition */
8095 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8097 if (coalition_is_leader(p
->task
, COALITION_TYPE_JETSAM
, &coal
)) {
8098 if (nleaders
< MAX_COAL_LEADERS
) {
8099 int coal_ntasks
= 0;
8100 uint64_t coal_page_count
= coalition_get_page_count(coal
, &coal_ntasks
);
8101 leaders
[nleaders
].msi_coal
= coal
;
8102 leaders
[nleaders
].msi_page_count
= coal_page_count
;
8103 leaders
[nleaders
].msi_pid
= p
->p_pid
; /* the coalition leader */
8104 leaders
[nleaders
].msi_ntasks
= coal_ntasks
;
8108 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8109 * Abandoned coalitions will linger at the tail of the priority band
8110 * when this sort session ends.
8111 * TODO: should this be an assert?
8113 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
8114 __FUNCTION__
, MAX_COAL_LEADERS
, bucket_index
);
8118 p
=memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8121 if (nleaders
== 0) {
8122 /* Nothing to sort */
8127 * Sort the coalition leader array, from smallest coalition page count
8128 * to largest coalition page count. When inserted in the priority bucket,
8129 * smallest coalition is handled first, resulting in the last to be jetsammed.
8132 qsort(leaders
, nleaders
, sizeof(memstat_sort_info_t
), memstat_asc_cmp
);
8136 for (i
= 0; i
< nleaders
; i
++) {
8137 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8138 __FUNCTION__
, i
, nleaders
, leaders
[i
].msi_pid
, leaders
[i
].msi_page_count
,
8139 leaders
[i
].msi_ntasks
);
8144 * During coalition sorting, processes in a priority band are rearranged
8145 * by being re-inserted at the head of the queue. So, when handling a
8146 * list, the first process that gets moved to the head of the queue,
8147 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8149 * So, for example, the coalition leader is expected to jetsam last,
8150 * after its coalition members. Therefore, the coalition leader is
8151 * inserted at the head of the queue first.
8153 * After processing a coalition, the jetsam order is as follows:
8154 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8158 * Coalition members are rearranged in the priority bucket here,
8159 * based on their coalition role.
8161 total_pids_moved
= 0;
8162 for (i
=0; i
< nleaders
; i
++) {
8164 /* a bit of bookkeeping */
8167 /* Coalition leaders are jetsammed last, so move into place first */
8168 pid_list
[0] = leaders
[i
].msi_pid
;
8169 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
, 1);
8171 /* xpc services should jetsam after extensions */
8172 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_XPC
,
8173 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8176 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8177 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8180 /* extensions should jetsam after unmarked processes */
8181 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_EXT
,
8182 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8185 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8186 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8189 /* undefined coalition members should be the first to jetsam */
8190 ntasks
= coalition_get_pid_list (leaders
[i
].msi_coal
, COALITION_ROLEMASK_UNDEF
,
8191 coal_sort_order
, pid_list
, MAX_SORT_PIDS
);
8194 pids_moved
+= memorystatus_move_list_locked(bucket_index
, pid_list
,
8195 (ntasks
<= MAX_SORT_PIDS
? ntasks
: MAX_SORT_PIDS
));
8199 if (pids_moved
== leaders
[i
].msi_ntasks
) {
8201 * All the pids in the coalition were found in this band.
8203 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__
,
8204 pids_moved
, leaders
[i
].msi_ntasks
);
8205 } else if (pids_moved
> leaders
[i
].msi_ntasks
) {
8207 * Apparently new coalition members showed up during the sort?
8209 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__
,
8210 pids_moved
, leaders
[i
].msi_ntasks
);
8213 * Apparently not all the pids in the coalition were found in this band?
8215 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__
,
8216 pids_moved
, leaders
[i
].msi_ntasks
);
8220 total_pids_moved
+= pids_moved
;
8224 return(total_pids_moved
);
8229 * Traverse a list of pids, searching for each within the priority band provided.
8230 * If pid is found, move it to the front of the priority band.
8231 * Never searches outside the priority band provided.
8234 * bucket_index - jetsam priority band.
8235 * pid_list - pointer to a list of pids.
8236 * list_sz - number of pids in the list.
8238 * Pid list ordering is important in that,
8239 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8240 * The sort_order is set by the coalition default.
8243 * the number of pids found and hence moved within the priority band.
8246 memorystatus_move_list_locked(unsigned int bucket_index
, pid_t
*pid_list
, int list_sz
)
8248 memstat_bucket_t
*current_bucket
;
8252 if ((pid_list
== NULL
) || (list_sz
<= 0)) {
8256 if (bucket_index
>= MEMSTAT_BUCKET_COUNT
) {
8260 current_bucket
= &memstat_bucket
[bucket_index
];
8261 for (i
=0; i
< list_sz
; i
++) {
8262 unsigned int b
= bucket_index
;
8264 proc_t aProc
= NULL
;
8268 list_index
= ((list_sz
- 1) - i
);
8269 aPid
= pid_list
[list_index
];
8271 /* never search beyond bucket_index provided */
8272 p
= memorystatus_get_first_proc_locked(&b
, FALSE
);
8274 if (p
->p_pid
== aPid
) {
8278 p
= memorystatus_get_next_proc_locked(&b
, p
, FALSE
);
8281 if (aProc
== NULL
) {
8282 /* pid not found in this band, just skip it */
8285 TAILQ_REMOVE(¤t_bucket
->list
, aProc
, p_memstat_list
);
8286 TAILQ_INSERT_HEAD(¤t_bucket
->list
, aProc
, p_memstat_list
);
8292 #endif /* CONFIG_JETSAM */