]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_memorystatus.c
xnu-3789.70.16.tar.gz
[apple/xnu.git] / bsd / kern / kern_memorystatus.c
1 /*
2 * Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 *
28 */
29
30 #include <kern/sched_prim.h>
31 #include <kern/kalloc.h>
32 #include <kern/assert.h>
33 #include <kern/debug.h>
34 #include <kern/locks.h>
35 #include <kern/task.h>
36 #include <kern/thread.h>
37 #include <kern/host.h>
38 #include <kern/policy_internal.h>
39
40 #include <IOKit/IOBSD.h>
41
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>
51 #include <sys/proc.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>
58 #include <sys/wait.h>
59 #include <sys/tree.h>
60 #include <sys/priv.h>
61 #include <vm/vm_pageout.h>
62 #include <vm/vm_protos.h>
63
64 #if CONFIG_FREEZE
65 #include <vm/vm_map.h>
66 #endif /* CONFIG_FREEZE */
67
68 #include <sys/kern_memorystatus.h>
69
70 #include <mach/machine/sdt.h>
71
72 /* For logging clarity */
73 static const char *jetsam_kill_cause_name[] = {
74 "" ,
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 */
84 };
85
86 #if CONFIG_JETSAM
87 /* Does cause indicate vm or fc thrashing? */
88 static boolean_t
89 is_thrashing(unsigned cause)
90 {
91 switch (cause) {
92 case kMemorystatusKilledVMThrashing:
93 case kMemorystatusKilledFCThrashing:
94 return TRUE;
95 default:
96 return FALSE;
97 }
98 }
99
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 */
103
104 /* These are very verbose printfs(), enable with
105 * MEMORYSTATUS_DEBUG_LOG
106 */
107 #if MEMORYSTATUS_DEBUG_LOG
108 #define MEMORYSTATUS_DEBUG(cond, format, ...) \
109 do { \
110 if (cond) { printf(format, ##__VA_ARGS__); } \
111 } while(0)
112 #else
113 #define MEMORYSTATUS_DEBUG(cond, format, ...)
114 #endif
115
116 /*
117 * Active / Inactive limit support
118 * proc list must be locked
119 *
120 * The SET_*** macros are used to initialize a limit
121 * for the first time.
122 *
123 * The CACHE_*** macros are use to cache the limit that will
124 * soon be in effect down in the ledgers.
125 */
126
127 #define SET_ACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
128 MACRO_BEGIN \
129 (p)->p_memstat_memlimit_active = (limit); \
130 if (is_fatal) { \
131 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
132 } else { \
133 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL; \
134 } \
135 MACRO_END
136
137 #define SET_INACTIVE_LIMITS_LOCKED(p, limit, is_fatal) \
138 MACRO_BEGIN \
139 (p)->p_memstat_memlimit_inactive = (limit); \
140 if (is_fatal) { \
141 (p)->p_memstat_state |= P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
142 } else { \
143 (p)->p_memstat_state &= ~P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL; \
144 } \
145 MACRO_END
146
147 #define CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal) \
148 MACRO_BEGIN \
149 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_active; \
150 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) { \
151 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
152 is_fatal = TRUE; \
153 } else { \
154 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
155 is_fatal = FALSE; \
156 } \
157 MACRO_END
158
159 #define CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal) \
160 MACRO_BEGIN \
161 (p)->p_memstat_memlimit = (p)->p_memstat_memlimit_inactive; \
162 if ((p)->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) { \
163 (p)->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT; \
164 is_fatal = TRUE; \
165 } else { \
166 (p)->p_memstat_state &= ~P_MEMSTAT_FATAL_MEMLIMIT; \
167 is_fatal = FALSE; \
168 } \
169 MACRO_END
170
171
172 /* General tunables */
173
174 unsigned long delta_percentage = 5;
175 unsigned long critical_threshold_percentage = 5;
176 unsigned long idle_offset_percentage = 5;
177 unsigned long pressure_threshold_percentage = 15;
178 unsigned long freeze_threshold_percentage = 50;
179 unsigned long policy_more_free_offset_percentage = 5;
180
181 /* General memorystatus stuff */
182
183 struct klist memorystatus_klist;
184 static lck_mtx_t memorystatus_klist_mutex;
185
186 static void memorystatus_klist_lock(void);
187 static void memorystatus_klist_unlock(void);
188
189 static uint64_t memorystatus_sysprocs_idle_delay_time = 0;
190 static uint64_t memorystatus_apps_idle_delay_time = 0;
191
192 /*
193 * Memorystatus kevents
194 */
195
196 static int filt_memorystatusattach(struct knote *kn);
197 static void filt_memorystatusdetach(struct knote *kn);
198 static int filt_memorystatus(struct knote *kn, long hint);
199 static int filt_memorystatustouch(struct knote *kn, struct kevent_internal_s *kev);
200 static int filt_memorystatusprocess(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev);
201
202 struct filterops memorystatus_filtops = {
203 .f_attach = filt_memorystatusattach,
204 .f_detach = filt_memorystatusdetach,
205 .f_event = filt_memorystatus,
206 .f_touch = filt_memorystatustouch,
207 .f_process = filt_memorystatusprocess,
208 };
209
210 enum {
211 kMemorystatusNoPressure = 0x1,
212 kMemorystatusPressure = 0x2,
213 kMemorystatusLowSwap = 0x4,
214 kMemorystatusProcLimitWarn = 0x8,
215 kMemorystatusProcLimitCritical = 0x10
216 };
217
218 /* Idle guard handling */
219
220 static int32_t memorystatus_scheduled_idle_demotions_sysprocs = 0;
221 static int32_t memorystatus_scheduled_idle_demotions_apps = 0;
222
223 static thread_call_t memorystatus_idle_demotion_call;
224
225 static void memorystatus_perform_idle_demotion(__unused void *spare1, __unused void *spare2);
226 static void memorystatus_schedule_idle_demotion_locked(proc_t p, boolean_t set_state);
227 static void memorystatus_invalidate_idle_demotion_locked(proc_t p, boolean_t clean_state);
228 static void memorystatus_reschedule_idle_demotion_locked(void);
229
230 static void memorystatus_update_priority_locked(proc_t p, int priority, boolean_t head_insert, boolean_t skip_demotion_check);
231
232 vm_pressure_level_t convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t);
233
234 boolean_t is_knote_registered_modify_task_pressure_bits(struct knote*, int, task_t, vm_pressure_level_t, vm_pressure_level_t);
235 void memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear);
236 void memorystatus_send_low_swap_note(void);
237
238 int memorystatus_wakeup = 0;
239
240 unsigned int memorystatus_level = 0;
241
242 static int memorystatus_list_count = 0;
243
244 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
245
246 typedef struct memstat_bucket {
247 TAILQ_HEAD(, proc) list;
248 int count;
249 } memstat_bucket_t;
250
251 memstat_bucket_t memstat_bucket[MEMSTAT_BUCKET_COUNT];
252
253 uint64_t memstat_idle_demotion_deadline = 0;
254
255 int system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
256 int applications_aging_band = JETSAM_PRIORITY_IDLE;
257
258 #define isProcessInAgingBands(p) ((isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) || (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)))
259 #define isApp(p) (! (p->p_memstat_dirty & P_DIRTY_TRACK))
260 #define isSysProc(p) ((p->p_memstat_dirty & P_DIRTY_TRACK))
261
262 #define kJetsamAgingPolicyNone (0)
263 #define kJetsamAgingPolicyLegacy (1)
264 #define kJetsamAgingPolicySysProcsReclaimedFirst (2)
265 #define kJetsamAgingPolicyAppsReclaimedFirst (3)
266 #define kJetsamAgingPolicyMax kJetsamAgingPolicyAppsReclaimedFirst
267
268 unsigned int jetsam_aging_policy = kJetsamAgingPolicyLegacy;
269
270 extern int corpse_for_fatal_memkill;
271 extern unsigned long total_corpses_count;
272 extern void task_purge_all_corpses(void);
273
274 #if 0
275
276 /* Keeping around for future use if we need a utility that can do this OR an app that needs a dynamic adjustment. */
277
278 static int
279 sysctl_set_jetsam_aging_policy SYSCTL_HANDLER_ARGS
280 {
281 #pragma unused(oidp, arg1, arg2)
282
283 int error = 0, val = 0;
284 memstat_bucket_t *old_bucket = 0;
285 int old_system_procs_aging_band = 0, new_system_procs_aging_band = 0;
286 int old_applications_aging_band = 0, new_applications_aging_band = 0;
287 proc_t p = NULL, next_proc = NULL;
288
289
290 error = sysctl_io_number(req, jetsam_aging_policy, sizeof(int), &val, NULL);
291 if (error || !req->newptr) {
292 return (error);
293 }
294
295 if ((val < 0) || (val > kJetsamAgingPolicyMax)) {
296 printf("jetsam: ordering policy sysctl has invalid value - %d\n", val);
297 return EINVAL;
298 }
299
300 /*
301 * We need to synchronize with any potential adding/removal from aging bands
302 * that might be in progress currently. We use the proc_list_lock() just for
303 * consistency with all the routines dealing with 'aging' processes. We need
304 * a lighterweight lock.
305 */
306 proc_list_lock();
307
308 old_system_procs_aging_band = system_procs_aging_band;
309 old_applications_aging_band = applications_aging_band;
310
311 switch (val) {
312
313 case kJetsamAgingPolicyNone:
314 new_system_procs_aging_band = JETSAM_PRIORITY_IDLE;
315 new_applications_aging_band = JETSAM_PRIORITY_IDLE;
316 break;
317
318 case kJetsamAgingPolicyLegacy:
319 /*
320 * Legacy behavior where some daemons get a 10s protection once and only before the first clean->dirty->clean transition before going into IDLE band.
321 */
322 new_system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
323 new_applications_aging_band = JETSAM_PRIORITY_IDLE;
324 break;
325
326 case kJetsamAgingPolicySysProcsReclaimedFirst:
327 new_system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
328 new_applications_aging_band = JETSAM_PRIORITY_AGING_BAND2;
329 break;
330
331 case kJetsamAgingPolicyAppsReclaimedFirst:
332 new_system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND2;
333 new_applications_aging_band = JETSAM_PRIORITY_AGING_BAND1;
334 break;
335
336 default:
337 break;
338 }
339
340 if (old_system_procs_aging_band && (old_system_procs_aging_band != new_system_procs_aging_band)) {
341
342 old_bucket = &memstat_bucket[old_system_procs_aging_band];
343 p = TAILQ_FIRST(&old_bucket->list);
344
345 while (p) {
346
347 next_proc = TAILQ_NEXT(p, p_memstat_list);
348
349 if (isSysProc(p)) {
350 if (new_system_procs_aging_band == JETSAM_PRIORITY_IDLE) {
351 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
352 }
353
354 memorystatus_update_priority_locked(p, new_system_procs_aging_band, false, true);
355 }
356
357 p = next_proc;
358 continue;
359 }
360 }
361
362 if (old_applications_aging_band && (old_applications_aging_band != new_applications_aging_band)) {
363
364 old_bucket = &memstat_bucket[old_applications_aging_band];
365 p = TAILQ_FIRST(&old_bucket->list);
366
367 while (p) {
368
369 next_proc = TAILQ_NEXT(p, p_memstat_list);
370
371 if (isApp(p)) {
372 if (new_applications_aging_band == JETSAM_PRIORITY_IDLE) {
373 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
374 }
375
376 memorystatus_update_priority_locked(p, new_applications_aging_band, false, true);
377 }
378
379 p = next_proc;
380 continue;
381 }
382 }
383
384 jetsam_aging_policy = val;
385 system_procs_aging_band = new_system_procs_aging_band;
386 applications_aging_band = new_applications_aging_band;
387
388 proc_list_unlock();
389
390 return (0);
391 }
392
393 SYSCTL_PROC(_kern, OID_AUTO, set_jetsam_aging_policy, CTLTYPE_INT|CTLFLAG_RW,
394 0, 0, sysctl_set_jetsam_aging_policy, "I", "Jetsam Aging Policy");
395 #endif /*0*/
396
397 static int
398 sysctl_jetsam_set_sysprocs_idle_delay_time SYSCTL_HANDLER_ARGS
399 {
400 #pragma unused(oidp, arg1, arg2)
401
402 int error = 0, val = 0, old_time_in_secs = 0;
403 uint64_t old_time_in_ns = 0;
404
405 absolutetime_to_nanoseconds(memorystatus_sysprocs_idle_delay_time, &old_time_in_ns);
406 old_time_in_secs = old_time_in_ns / NSEC_PER_SEC;
407
408 error = sysctl_io_number(req, old_time_in_secs, sizeof(int), &val, NULL);
409 if (error || !req->newptr) {
410 return (error);
411 }
412
413 if ((val < 0) || (val > INT32_MAX)) {
414 printf("jetsam: new idle delay interval has invalid value.\n");
415 return EINVAL;
416 }
417
418 nanoseconds_to_absolutetime((uint64_t)val * NSEC_PER_SEC, &memorystatus_sysprocs_idle_delay_time);
419
420 return(0);
421 }
422
423 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_sysprocs_idle_delay_time, CTLTYPE_INT|CTLFLAG_RW,
424 0, 0, sysctl_jetsam_set_sysprocs_idle_delay_time, "I", "Aging window for system processes");
425
426
427 static int
428 sysctl_jetsam_set_apps_idle_delay_time SYSCTL_HANDLER_ARGS
429 {
430 #pragma unused(oidp, arg1, arg2)
431
432 int error = 0, val = 0, old_time_in_secs = 0;
433 uint64_t old_time_in_ns = 0;
434
435 absolutetime_to_nanoseconds(memorystatus_apps_idle_delay_time, &old_time_in_ns);
436 old_time_in_secs = old_time_in_ns / NSEC_PER_SEC;
437
438 error = sysctl_io_number(req, old_time_in_secs, sizeof(int), &val, NULL);
439 if (error || !req->newptr) {
440 return (error);
441 }
442
443 if ((val < 0) || (val > INT32_MAX)) {
444 printf("jetsam: new idle delay interval has invalid value.\n");
445 return EINVAL;
446 }
447
448 nanoseconds_to_absolutetime((uint64_t)val * NSEC_PER_SEC, &memorystatus_apps_idle_delay_time);
449
450 return(0);
451 }
452
453 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_apps_idle_delay_time, CTLTYPE_INT|CTLFLAG_RW,
454 0, 0, sysctl_jetsam_set_apps_idle_delay_time, "I", "Aging window for applications");
455
456 SYSCTL_INT(_kern, OID_AUTO, jetsam_aging_policy, CTLTYPE_INT|CTLFLAG_RD, &jetsam_aging_policy, 0, "");
457
458 static unsigned int memorystatus_dirty_count = 0;
459
460 SYSCTL_INT(_kern, OID_AUTO, max_task_pmem, CTLFLAG_RD|CTLFLAG_LOCKED|CTLFLAG_MASKED, &max_task_footprint_mb, 0, "");
461
462
463 int
464 memorystatus_get_level(__unused struct proc *p, struct memorystatus_get_level_args *args, __unused int *ret)
465 {
466 user_addr_t level = 0;
467
468 level = args->level;
469
470 if (copyout(&memorystatus_level, level, sizeof(memorystatus_level)) != 0) {
471 return EFAULT;
472 }
473
474 return 0;
475 }
476
477 static proc_t memorystatus_get_first_proc_locked(unsigned int *bucket_index, boolean_t search);
478 static proc_t memorystatus_get_next_proc_locked(unsigned int *bucket_index, proc_t p, boolean_t search);
479
480 static void memorystatus_thread(void *param __unused, wait_result_t wr __unused);
481
482 /* Memory Limits */
483
484 static int memorystatus_highwater_enabled = 1; /* Update the cached memlimit data. */
485
486 static boolean_t proc_jetsam_state_is_active_locked(proc_t);
487 static boolean_t memorystatus_kill_specific_process(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason);
488 static boolean_t memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason);
489
490
491 /* Jetsam */
492
493 #if CONFIG_JETSAM
494
495 static int memorystatus_cmd_set_jetsam_memory_limit(pid_t pid, int32_t high_water_mark, __unused int32_t *retval, boolean_t is_fatal_limit);
496
497 static int memorystatus_cmd_set_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
498
499 static int memorystatus_set_memlimit_properties(pid_t pid, memorystatus_memlimit_properties_t *entry);
500
501 static int memorystatus_cmd_get_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
502
503 static int memorystatus_cmd_get_memlimit_excess_np(pid_t pid, uint32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval);
504
505 int proc_get_memstat_priority(proc_t, boolean_t);
506
507 static boolean_t memorystatus_idle_snapshot = 0;
508
509 unsigned int memorystatus_delta = 0;
510
511 static unsigned int memorystatus_available_pages_critical_base = 0;
512 //static unsigned int memorystatus_last_foreground_pressure_pages = (unsigned int)-1;
513 static unsigned int memorystatus_available_pages_critical_idle_offset = 0;
514
515 /* Jetsam Loop Detection */
516 static boolean_t memorystatus_jld_enabled = TRUE; /* Enables jetsam loop detection on all devices */
517 static uint32_t memorystatus_jld_eval_period_msecs = 0; /* Init pass sets this based on device memory size */
518 static int memorystatus_jld_eval_aggressive_count = 3; /* Raise the priority max after 'n' aggressive loops */
519 static int memorystatus_jld_eval_aggressive_priority_band_max = 15; /* Kill aggressively up through this band */
520
521 /*
522 * A FG app can request that the aggressive jetsam mechanism display some leniency in the FG band. This 'lenient' mode is described as:
523 * --- if aggressive jetsam kills an app in the FG band and gets back >=AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD memory, it will stop the aggressive march further into and up the jetsam bands.
524 *
525 * RESTRICTIONS:
526 * - Such a request is respected/acknowledged only once while that 'requesting' app is in the FG band i.e. if aggressive jetsam was
527 * needed and the 'lenient' mode was deployed then that's it for this special mode while the app is in the FG band.
528 *
529 * - If the app is still in the FG band and aggressive jetsam is needed again, there will be no stop-and-check the next time around.
530 *
531 * - Also, the transition of the 'requesting' app away from the FG band will void this special behavior.
532 */
533
534 #define AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD 25
535 boolean_t memorystatus_aggressive_jetsam_lenient_allowed = FALSE;
536 boolean_t memorystatus_aggressive_jetsam_lenient = FALSE;
537
538 #if DEVELOPMENT || DEBUG
539 /*
540 * Jetsam Loop Detection tunables.
541 */
542
543 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_period_msecs, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_jld_eval_period_msecs, 0, "");
544 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_aggressive_count, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_jld_eval_aggressive_count, 0, "");
545 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jld_eval_aggressive_priority_band_max, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_jld_eval_aggressive_priority_band_max, 0, "");
546 #endif /* DEVELOPMENT || DEBUG */
547
548 #if DEVELOPMENT || DEBUG
549 static unsigned int memorystatus_jetsam_panic_debug = 0;
550 static unsigned int memorystatus_jetsam_policy_offset_pages_diagnostic = 0;
551 #endif
552
553 static unsigned int memorystatus_jetsam_policy = kPolicyDefault;
554 static unsigned int memorystatus_thread_wasted_wakeup = 0;
555
556 static uint32_t kill_under_pressure_cause = 0;
557
558 /*
559 * default jetsam snapshot support
560 */
561 static memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot;
562 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
563 static unsigned int memorystatus_jetsam_snapshot_count = 0;
564 static unsigned int memorystatus_jetsam_snapshot_max = 0;
565 static uint64_t memorystatus_jetsam_snapshot_last_timestamp = 0;
566 static uint64_t memorystatus_jetsam_snapshot_timeout = 0;
567 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
568
569 /*
570 * snapshot support for memstats collected at boot.
571 */
572 static memorystatus_jetsam_snapshot_t memorystatus_at_boot_snapshot;
573
574 static void memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t *od_snapshot, uint32_t ods_list_count);
575 static boolean_t memorystatus_init_jetsam_snapshot_entry_locked(proc_t p, memorystatus_jetsam_snapshot_entry_t *entry, uint64_t gencount);
576 static void memorystatus_update_jetsam_snapshot_entry_locked(proc_t p, uint32_t kill_cause, uint64_t killtime);
577
578 static void memorystatus_clear_errors(void);
579 static void memorystatus_get_task_page_counts(task_t task, uint32_t *footprint, uint32_t *max_footprint, uint32_t *max_footprint_lifetime, uint32_t *purgeable_pages);
580 static void memorystatus_get_task_phys_footprint_page_counts(task_t task,
581 uint64_t *internal_pages, uint64_t *internal_compressed_pages,
582 uint64_t *purgeable_nonvolatile_pages, uint64_t *purgeable_nonvolatile_compressed_pages,
583 uint64_t *alternate_accounting_pages, uint64_t *alternate_accounting_compressed_pages,
584 uint64_t *iokit_mapped_pages, uint64_t *page_table_pages);
585
586 static void memorystatus_get_task_memory_region_count(task_t task, uint64_t *count);
587
588 static uint32_t memorystatus_build_state(proc_t p);
589 static void memorystatus_update_levels_locked(boolean_t critical_only);
590 //static boolean_t memorystatus_issue_pressure_kevent(boolean_t pressured);
591
592 static boolean_t memorystatus_kill_top_process(boolean_t any, boolean_t sort_flag, uint32_t cause, os_reason_t jetsam_reason, int32_t *priority, uint32_t *errors);
593 static boolean_t memorystatus_kill_top_process_aggressive(boolean_t any, uint32_t cause, os_reason_t jetsam_reason, int aggr_count, int32_t priority_max, uint32_t *errors);
594 static boolean_t memorystatus_kill_elevated_process(uint32_t cause, os_reason_t jetsam_reason, int aggr_count, uint32_t *errors);
595 static boolean_t memorystatus_kill_hiwat_proc(uint32_t *errors);
596
597 static boolean_t memorystatus_kill_process_async(pid_t victim_pid, uint32_t cause);
598
599 /* Priority Band Sorting Routines */
600 static int memorystatus_sort_bucket(unsigned int bucket_index, int sort_order);
601 static int memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index, int coal_sort_order);
602 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index);
603 static int memorystatus_move_list_locked(unsigned int bucket_index, pid_t *pid_list, int list_sz);
604
605 /* qsort routines */
606 typedef int (*cmpfunc_t)(const void *a, const void *b);
607 extern void qsort(void *a, size_t n, size_t es, cmpfunc_t cmp);
608 static int memstat_asc_cmp(const void *a, const void *b);
609
610 #endif /* CONFIG_JETSAM */
611
612 /* VM pressure */
613
614 extern unsigned int vm_page_free_count;
615 extern unsigned int vm_page_active_count;
616 extern unsigned int vm_page_inactive_count;
617 extern unsigned int vm_page_throttled_count;
618 extern unsigned int vm_page_purgeable_count;
619 extern unsigned int vm_page_wire_count;
620 #if CONFIG_SECLUDED_MEMORY
621 extern unsigned int vm_page_secluded_count;
622 #endif /* CONFIG_SECLUDED_MEMORY */
623
624 #if VM_PRESSURE_EVENTS
625
626 boolean_t memorystatus_warn_process(pid_t pid, __unused boolean_t is_active, __unused boolean_t is_fatal, boolean_t exceeded);
627
628 vm_pressure_level_t memorystatus_vm_pressure_level = kVMPressureNormal;
629
630 #if CONFIG_MEMORYSTATUS
631 unsigned int memorystatus_available_pages = (unsigned int)-1;
632 unsigned int memorystatus_available_pages_pressure = 0;
633 unsigned int memorystatus_available_pages_critical = 0;
634 unsigned int memorystatus_frozen_count = 0;
635 unsigned int memorystatus_suspended_count = 0;
636 unsigned int memorystatus_policy_more_free_offset_pages = 0;
637
638 #if CONFIG_JETSAM
639 #if DEVELOPMENT || DEBUG
640 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages, CTLFLAG_RD | CTLFLAG_LOCKED, &memorystatus_available_pages, 0, "");
641 #else
642 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages, CTLFLAG_RD| CTLFLAG_MASKED | CTLFLAG_LOCKED, &memorystatus_available_pages, 0, "");
643 #endif /* DEVELOPMENT || DEBUG */
644 #endif /* CONFIG_JETSAM */
645
646 /*
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.
651 *
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.
657 */
658 boolean_t memorystatus_hwm_candidates = 0;
659
660 static int memorystatus_send_note(int event_code, void *data, size_t data_length);
661 #endif /* CONFIG_MEMORYSTATUS */
662
663 #endif /* VM_PRESSURE_EVENTS */
664
665
666 #if DEVELOPMENT || DEBUG
667
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;
671
672 #endif
673
674
675 /* Freeze */
676
677 #if CONFIG_FREEZE
678
679 boolean_t memorystatus_freeze_enabled = FALSE;
680 int memorystatus_freeze_wakeup = 0;
681
682 lck_grp_attr_t *freezer_lck_grp_attr;
683 lck_grp_t *freezer_lck_grp;
684 static lck_mtx_t freezer_mutex;
685
686 static inline boolean_t memorystatus_can_freeze_processes(void);
687 static boolean_t memorystatus_can_freeze(boolean_t *memorystatus_freeze_swap_low);
688
689 static void memorystatus_freeze_thread(void *param __unused, wait_result_t wr __unused);
690
691 /* Thresholds */
692 static unsigned int memorystatus_freeze_threshold = 0;
693
694 static unsigned int memorystatus_freeze_pages_min = 0;
695 static unsigned int memorystatus_freeze_pages_max = 0;
696
697 static unsigned int memorystatus_freeze_suspended_threshold = FREEZE_SUSPENDED_THRESHOLD_DEFAULT;
698
699 static unsigned int memorystatus_freeze_daily_mb_max = FREEZE_DAILY_MB_MAX_DEFAULT;
700
701 /* Stats */
702 static uint64_t memorystatus_freeze_count = 0;
703 static uint64_t memorystatus_freeze_pageouts = 0;
704
705 /* Throttling */
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 */
709 };
710
711 static uint64_t memorystatus_freeze_throttle_count = 0;
712
713 static unsigned int memorystatus_suspended_footprint_total = 0; /* pages */
714
715 extern uint64_t vm_swap_get_free_space(void);
716
717 static boolean_t memorystatus_freeze_update_throttle();
718
719 #endif /* CONFIG_FREEZE */
720
721 /* Debug */
722
723 extern struct knote *vm_find_knote_from_pid(pid_t, struct klist *);
724
725 #if DEVELOPMENT || DEBUG
726
727 static unsigned int memorystatus_debug_dump_this_bucket = 0;
728
729 static void
730 memorystatus_debug_dump_bucket_locked (unsigned int bucket_index)
731 {
732 proc_t p = NULL;
733 uint64_t bytes = 0;
734 int ledger_limit = 0;
735 unsigned int b = bucket_index;
736 boolean_t traverse_all_buckets = FALSE;
737
738 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
739 traverse_all_buckets = TRUE;
740 b = 0;
741 } else {
742 traverse_all_buckets = FALSE;
743 b = bucket_index;
744 }
745
746 /*
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
754 */
755
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);
759 while (p) {
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",
763 b, p->p_pid,
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,
767 ledger_limit,
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);
776 }
777 printf("memorystatus_debug_dump ***END***\n");
778 }
779
780 static int
781 sysctl_memorystatus_debug_dump_bucket SYSCTL_HANDLER_ARGS
782 {
783 #pragma unused(oidp, arg2)
784 int bucket_index = 0;
785 int error;
786 error = SYSCTL_OUT(req, arg1, sizeof(int));
787 if (error || !req->newptr) {
788 return (error);
789 }
790 error = SYSCTL_IN(req, &bucket_index, sizeof(int));
791 if (error || !req->newptr) {
792 return (error);
793 }
794 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
795 /*
796 * All jetsam buckets will be dumped.
797 */
798 } else {
799 /*
800 * Only a single bucket will be dumped.
801 */
802 }
803
804 proc_list_lock();
805 memorystatus_debug_dump_bucket_locked(bucket_index);
806 proc_list_unlock();
807 memorystatus_debug_dump_this_bucket = bucket_index;
808 return (error);
809 }
810
811 /*
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>
816 */
817
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", "");
819
820
821 /* Debug aid to aid determination of limit */
822
823 static int
824 sysctl_memorystatus_highwater_enable SYSCTL_HANDLER_ARGS
825 {
826 #pragma unused(oidp, arg2)
827 proc_t p;
828 unsigned int b = 0;
829 int error, enable = 0;
830 boolean_t use_active; /* use the active limit and active limit attributes */
831 boolean_t is_fatal;
832
833 error = SYSCTL_OUT(req, arg1, sizeof(int));
834 if (error || !req->newptr) {
835 return (error);
836 }
837
838 error = SYSCTL_IN(req, &enable, sizeof(int));
839 if (error || !req->newptr) {
840 return (error);
841 }
842
843 if (!(enable == 0 || enable == 1)) {
844 return EINVAL;
845 }
846
847 proc_list_lock();
848
849 p = memorystatus_get_first_proc_locked(&b, TRUE);
850 while (p) {
851 use_active = proc_jetsam_state_is_active_locked(p);
852
853 if (enable) {
854 /*
855 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
856 * Background limits are described via the inactive limit slots.
857 */
858
859 if (use_active == TRUE) {
860 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
861 } else {
862 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
863 }
864
865 } else {
866 /*
867 * Disabling limits does not touch the stored variants.
868 * Set the cached limit fields to system_wide defaults.
869 */
870 p->p_memstat_memlimit = -1;
871 p->p_memstat_state |= P_MEMSTAT_FATAL_MEMLIMIT;
872 is_fatal = TRUE;
873 }
874
875 /*
876 * Enforce the cached limit by writing to the ledger.
877 */
878 task_set_phys_footprint_limit_internal(p->task, (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit: -1, NULL, use_active, is_fatal);
879
880 p = memorystatus_get_next_proc_locked(&b, p, TRUE);
881 }
882
883 memorystatus_highwater_enabled = enable;
884
885 proc_list_unlock();
886
887 return 0;
888
889 }
890
891 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_highwater_enabled, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_highwater_enabled, 0, sysctl_memorystatus_highwater_enable, "I", "");
892
893 #if VM_PRESSURE_EVENTS
894
895 /*
896 * This routine is used for targeted notifications regardless of system memory pressure
897 * and regardless of whether or not the process has already been notified.
898 * It bypasses and has no effect on the only-one-notification per soft-limit policy.
899 *
900 * "memnote" is the current user.
901 */
902
903 static int
904 sysctl_memorystatus_vm_pressure_send SYSCTL_HANDLER_ARGS
905 {
906 #pragma unused(arg1, arg2)
907
908 int error = 0, pid = 0;
909 struct knote *kn = NULL;
910 boolean_t found_knote = FALSE;
911 int fflags = 0; /* filter flags for EVFILT_MEMORYSTATUS */
912 uint64_t value = 0;
913
914 error = sysctl_handle_quad(oidp, &value, 0, req);
915 if (error || !req->newptr)
916 return (error);
917
918 /*
919 * Find the pid in the low 32 bits of value passed in.
920 */
921 pid = (int)(value & 0xFFFFFFFF);
922
923 /*
924 * Find notification in the high 32 bits of the value passed in.
925 */
926 fflags = (int)((value >> 32) & 0xFFFFFFFF);
927
928 /*
929 * For backwards compatibility, when no notification is
930 * passed in, default to the NOTE_MEMORYSTATUS_PRESSURE_WARN
931 */
932 if (fflags == 0) {
933 fflags = NOTE_MEMORYSTATUS_PRESSURE_WARN;
934 // printf("memorystatus_vm_pressure_send: using default notification [0x%x]\n", fflags);
935 }
936
937 /*
938 * See event.h ... fflags for EVFILT_MEMORYSTATUS
939 */
940 if (!((fflags == NOTE_MEMORYSTATUS_PRESSURE_NORMAL)||
941 (fflags == NOTE_MEMORYSTATUS_PRESSURE_WARN) ||
942 (fflags == NOTE_MEMORYSTATUS_PRESSURE_CRITICAL) ||
943 (fflags == NOTE_MEMORYSTATUS_LOW_SWAP) ||
944 (fflags == NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) ||
945 (fflags == NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL))) {
946
947 printf("memorystatus_vm_pressure_send: notification [0x%x] not supported \n", fflags);
948 error = 1;
949 return (error);
950 }
951
952 /*
953 * Forcibly send pid a memorystatus notification.
954 */
955
956 memorystatus_klist_lock();
957
958 SLIST_FOREACH(kn, &memorystatus_klist, kn_selnext) {
959 proc_t knote_proc = knote_get_kq(kn)->kq_p;
960 pid_t knote_pid = knote_proc->p_pid;
961
962 if (knote_pid == pid) {
963 /*
964 * Forcibly send this pid a memorystatus notification.
965 */
966 kn->kn_fflags = fflags;
967 found_knote = TRUE;
968 }
969 }
970
971 if (found_knote) {
972 KNOTE(&memorystatus_klist, 0);
973 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] sent to process [%d] \n", value, fflags, pid);
974 error = 0;
975 } else {
976 printf("memorystatus_vm_pressure_send: (value 0x%llx) notification [0x%x] not sent to process [%d] (none registered?)\n", value, fflags, pid);
977 error = 1;
978 }
979
980 memorystatus_klist_unlock();
981
982 return (error);
983 }
984
985 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_vm_pressure_send, CTLTYPE_QUAD|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
986 0, 0, &sysctl_memorystatus_vm_pressure_send, "Q", "");
987
988 #endif /* VM_PRESSURE_EVENTS */
989
990 #if CONFIG_JETSAM
991
992 SYSCTL_INT(_kern, OID_AUTO, memorystatus_idle_snapshot, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_idle_snapshot, 0, "");
993
994 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical, CTLFLAG_RD|CTLFLAG_LOCKED, &memorystatus_available_pages_critical, 0, "");
995 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical_base, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_available_pages_critical_base, 0, "");
996 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_critical_idle_offset, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_available_pages_critical_idle_offset, 0, "");
997 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_policy_more_free_offset_pages, CTLFLAG_RW, &memorystatus_policy_more_free_offset_pages, 0, "");
998
999 /* Diagnostic code */
1000
1001 enum {
1002 kJetsamDiagnosticModeNone = 0,
1003 kJetsamDiagnosticModeAll = 1,
1004 kJetsamDiagnosticModeStopAtFirstActive = 2,
1005 kJetsamDiagnosticModeCount
1006 } jetsam_diagnostic_mode = kJetsamDiagnosticModeNone;
1007
1008 static int jetsam_diagnostic_suspended_one_active_proc = 0;
1009
1010 static int
1011 sysctl_jetsam_diagnostic_mode SYSCTL_HANDLER_ARGS
1012 {
1013 #pragma unused(arg1, arg2)
1014
1015 const char *diagnosticStrings[] = {
1016 "jetsam: diagnostic mode: resetting critical level.",
1017 "jetsam: diagnostic mode: will examine all processes",
1018 "jetsam: diagnostic mode: will stop at first active process"
1019 };
1020
1021 int error, val = jetsam_diagnostic_mode;
1022 boolean_t changed = FALSE;
1023
1024 error = sysctl_handle_int(oidp, &val, 0, req);
1025 if (error || !req->newptr)
1026 return (error);
1027 if ((val < 0) || (val >= kJetsamDiagnosticModeCount)) {
1028 printf("jetsam: diagnostic mode: invalid value - %d\n", val);
1029 return EINVAL;
1030 }
1031
1032 proc_list_lock();
1033
1034 if ((unsigned int) val != jetsam_diagnostic_mode) {
1035 jetsam_diagnostic_mode = val;
1036
1037 memorystatus_jetsam_policy &= ~kPolicyDiagnoseActive;
1038
1039 switch (jetsam_diagnostic_mode) {
1040 case kJetsamDiagnosticModeNone:
1041 /* Already cleared */
1042 break;
1043 case kJetsamDiagnosticModeAll:
1044 memorystatus_jetsam_policy |= kPolicyDiagnoseAll;
1045 break;
1046 case kJetsamDiagnosticModeStopAtFirstActive:
1047 memorystatus_jetsam_policy |= kPolicyDiagnoseFirst;
1048 break;
1049 default:
1050 /* Already validated */
1051 break;
1052 }
1053
1054 memorystatus_update_levels_locked(FALSE);
1055 changed = TRUE;
1056 }
1057
1058 proc_list_unlock();
1059
1060 if (changed) {
1061 printf("%s\n", diagnosticStrings[val]);
1062 }
1063
1064 return (0);
1065 }
1066
1067 SYSCTL_PROC(_debug, OID_AUTO, jetsam_diagnostic_mode, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_LOCKED|CTLFLAG_ANYBODY,
1068 &jetsam_diagnostic_mode, 0, sysctl_jetsam_diagnostic_mode, "I", "Jetsam Diagnostic Mode");
1069
1070 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_jetsam_policy_offset_pages_diagnostic, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_jetsam_policy_offset_pages_diagnostic, 0, "");
1071
1072 #if VM_PRESSURE_EVENTS
1073
1074 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_available_pages_pressure, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_available_pages_pressure, 0, "");
1075
1076 #endif /* VM_PRESSURE_EVENTS */
1077
1078 #endif /* CONFIG_JETSAM */
1079
1080 #if CONFIG_FREEZE
1081
1082 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_daily_mb_max, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_daily_mb_max, 0, "");
1083
1084 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_threshold, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_threshold, 0, "");
1085
1086 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_pages_min, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_pages_min, 0, "");
1087 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_pages_max, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_pages_max, 0, "");
1088
1089 SYSCTL_QUAD(_kern, OID_AUTO, memorystatus_freeze_count, CTLFLAG_RD|CTLFLAG_LOCKED, &memorystatus_freeze_count, "");
1090 SYSCTL_QUAD(_kern, OID_AUTO, memorystatus_freeze_pageouts, CTLFLAG_RD|CTLFLAG_LOCKED, &memorystatus_freeze_pageouts, "");
1091 SYSCTL_QUAD(_kern, OID_AUTO, memorystatus_freeze_throttle_count, CTLFLAG_RD|CTLFLAG_LOCKED, &memorystatus_freeze_throttle_count, "");
1092 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_min_processes, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_suspended_threshold, 0, "");
1093
1094 boolean_t memorystatus_freeze_throttle_enabled = TRUE;
1095 SYSCTL_UINT(_kern, OID_AUTO, memorystatus_freeze_throttle_enabled, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_freeze_throttle_enabled, 0, "");
1096
1097 #define VM_PAGES_FOR_ALL_PROCS (2)
1098 /*
1099 * Manual trigger of freeze and thaw for dev / debug kernels only.
1100 */
1101 static int
1102 sysctl_memorystatus_freeze SYSCTL_HANDLER_ARGS
1103 {
1104 #pragma unused(arg1, arg2)
1105 int error, pid = 0;
1106 proc_t p;
1107
1108 if (memorystatus_freeze_enabled == FALSE) {
1109 return ENOTSUP;
1110 }
1111
1112 error = sysctl_handle_int(oidp, &pid, 0, req);
1113 if (error || !req->newptr)
1114 return (error);
1115
1116 if (pid == VM_PAGES_FOR_ALL_PROCS) {
1117 vm_pageout_anonymous_pages();
1118
1119 return 0;
1120 }
1121
1122 lck_mtx_lock(&freezer_mutex);
1123
1124 p = proc_find(pid);
1125 if (p != NULL) {
1126 uint32_t purgeable, wired, clean, dirty;
1127 boolean_t shared;
1128 uint32_t max_pages = 0;
1129
1130 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
1131
1132 unsigned int avail_swap_space = 0; /* in pages. */
1133
1134 /*
1135 * Freezer backed by the compressor and swap file(s)
1136 * while will hold compressed data.
1137 */
1138 avail_swap_space = vm_swap_get_free_space() / PAGE_SIZE_64;
1139
1140 max_pages = MIN(avail_swap_space, memorystatus_freeze_pages_max);
1141
1142 } else {
1143 /*
1144 * We only have the compressor without any swap.
1145 */
1146 max_pages = UINT32_MAX - 1;
1147 }
1148
1149 error = task_freeze(p->task, &purgeable, &wired, &clean, &dirty, max_pages, &shared, FALSE);
1150 proc_rele(p);
1151
1152 if (error)
1153 error = EIO;
1154
1155 lck_mtx_unlock(&freezer_mutex);
1156 return error;
1157 }
1158
1159 lck_mtx_unlock(&freezer_mutex);
1160 return EINVAL;
1161 }
1162
1163 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_freeze, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
1164 0, 0, &sysctl_memorystatus_freeze, "I", "");
1165
1166 static int
1167 sysctl_memorystatus_available_pages_thaw SYSCTL_HANDLER_ARGS
1168 {
1169 #pragma unused(arg1, arg2)
1170
1171 int error, pid = 0;
1172 proc_t p;
1173
1174 if (memorystatus_freeze_enabled == FALSE) {
1175 return ENOTSUP;
1176 }
1177
1178 error = sysctl_handle_int(oidp, &pid, 0, req);
1179 if (error || !req->newptr)
1180 return (error);
1181
1182 if (pid == VM_PAGES_FOR_ALL_PROCS) {
1183 do_fastwake_warmup_all();
1184 return 0;
1185 } else {
1186 p = proc_find(pid);
1187 if (p != NULL) {
1188 error = task_thaw(p->task);
1189 proc_rele(p);
1190
1191 if (error)
1192 error = EIO;
1193 return error;
1194 }
1195 }
1196
1197 return EINVAL;
1198 }
1199
1200 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_thaw, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
1201 0, 0, &sysctl_memorystatus_available_pages_thaw, "I", "");
1202
1203 #endif /* CONFIG_FREEZE */
1204
1205 #endif /* DEVELOPMENT || DEBUG */
1206
1207 extern kern_return_t kernel_thread_start_priority(thread_continue_t continuation,
1208 void *parameter,
1209 integer_t priority,
1210 thread_t *new_thread);
1211
1212 #if DEVELOPMENT || DEBUG
1213
1214 static int
1215 sysctl_memorystatus_disconnect_page_mappings SYSCTL_HANDLER_ARGS
1216 {
1217 #pragma unused(arg1, arg2)
1218 int error = 0, pid = 0;
1219 proc_t p;
1220
1221 error = sysctl_handle_int(oidp, &pid, 0, req);
1222 if (error || !req->newptr)
1223 return (error);
1224
1225 lck_mtx_lock(&disconnect_page_mappings_mutex);
1226
1227 if (pid == -1) {
1228 vm_pageout_disconnect_all_pages();
1229 } else {
1230 p = proc_find(pid);
1231
1232 if (p != NULL) {
1233 error = task_disconnect_page_mappings(p->task);
1234
1235 proc_rele(p);
1236
1237 if (error)
1238 error = EIO;
1239 } else
1240 error = EINVAL;
1241 }
1242 lck_mtx_unlock(&disconnect_page_mappings_mutex);
1243
1244 return error;
1245 }
1246
1247 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_disconnect_page_mappings, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
1248 0, 0, &sysctl_memorystatus_disconnect_page_mappings, "I", "");
1249
1250 #endif /* DEVELOPMENT || DEBUG */
1251
1252
1253
1254 #if CONFIG_JETSAM
1255 /*
1256 * Picks the sorting routine for a given jetsam priority band.
1257 *
1258 * Input:
1259 * bucket_index - jetsam priority band to be sorted.
1260 * sort_order - JETSAM_SORT_xxx from kern_memorystatus.h
1261 * Currently sort_order is only meaningful when handling
1262 * coalitions.
1263 *
1264 * Return:
1265 * 0 on success
1266 * non-0 on failure
1267 */
1268 static int memorystatus_sort_bucket(unsigned int bucket_index, int sort_order)
1269 {
1270 int coal_sort_order;
1271
1272 /*
1273 * Verify the jetsam priority
1274 */
1275 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
1276 return(EINVAL);
1277 }
1278
1279 #if DEVELOPMENT || DEBUG
1280 if (sort_order == JETSAM_SORT_DEFAULT) {
1281 coal_sort_order = COALITION_SORT_DEFAULT;
1282 } else {
1283 coal_sort_order = sort_order; /* only used for testing scenarios */
1284 }
1285 #else
1286 /* Verify default */
1287 if (sort_order == JETSAM_SORT_DEFAULT) {
1288 coal_sort_order = COALITION_SORT_DEFAULT;
1289 } else {
1290 return(EINVAL);
1291 }
1292 #endif
1293
1294 proc_list_lock();
1295 switch (bucket_index) {
1296 case JETSAM_PRIORITY_FOREGROUND:
1297 if (memorystatus_sort_by_largest_coalition_locked(bucket_index, coal_sort_order) == 0) {
1298 /*
1299 * Fall back to per process sorting when zero coalitions are found.
1300 */
1301 memorystatus_sort_by_largest_process_locked(bucket_index);
1302 }
1303 break;
1304 default:
1305 memorystatus_sort_by_largest_process_locked(bucket_index);
1306 break;
1307 }
1308 proc_list_unlock();
1309
1310 return(0);
1311 }
1312
1313 /*
1314 * Sort processes by size for a single jetsam bucket.
1315 */
1316
1317 static void memorystatus_sort_by_largest_process_locked(unsigned int bucket_index)
1318 {
1319 proc_t p = NULL, insert_after_proc = NULL, max_proc = NULL;
1320 proc_t next_p = NULL, prev_max_proc = NULL;
1321 uint32_t pages = 0, max_pages = 0;
1322 memstat_bucket_t *current_bucket;
1323
1324 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
1325 return;
1326 }
1327
1328 current_bucket = &memstat_bucket[bucket_index];
1329
1330 p = TAILQ_FIRST(&current_bucket->list);
1331
1332 while (p) {
1333 memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL, NULL);
1334 max_pages = pages;
1335 max_proc = p;
1336 prev_max_proc = p;
1337
1338 while ((next_p = TAILQ_NEXT(p, p_memstat_list)) != NULL) {
1339 /* traversing list until we find next largest process */
1340 p=next_p;
1341 memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL, NULL);
1342 if (pages > max_pages) {
1343 max_pages = pages;
1344 max_proc = p;
1345 }
1346 }
1347
1348 if (prev_max_proc != max_proc) {
1349 /* found a larger process, place it in the list */
1350 TAILQ_REMOVE(&current_bucket->list, max_proc, p_memstat_list);
1351 if (insert_after_proc == NULL) {
1352 TAILQ_INSERT_HEAD(&current_bucket->list, max_proc, p_memstat_list);
1353 } else {
1354 TAILQ_INSERT_AFTER(&current_bucket->list, insert_after_proc, max_proc, p_memstat_list);
1355 }
1356 prev_max_proc = max_proc;
1357 }
1358
1359 insert_after_proc = max_proc;
1360
1361 p = TAILQ_NEXT(max_proc, p_memstat_list);
1362 }
1363 }
1364
1365 #endif /* CONFIG_JETSAM */
1366
1367 static proc_t memorystatus_get_first_proc_locked(unsigned int *bucket_index, boolean_t search) {
1368 memstat_bucket_t *current_bucket;
1369 proc_t next_p;
1370
1371 if ((*bucket_index) >= MEMSTAT_BUCKET_COUNT) {
1372 return NULL;
1373 }
1374
1375 current_bucket = &memstat_bucket[*bucket_index];
1376 next_p = TAILQ_FIRST(&current_bucket->list);
1377 if (!next_p && search) {
1378 while (!next_p && (++(*bucket_index) < MEMSTAT_BUCKET_COUNT)) {
1379 current_bucket = &memstat_bucket[*bucket_index];
1380 next_p = TAILQ_FIRST(&current_bucket->list);
1381 }
1382 }
1383
1384 return next_p;
1385 }
1386
1387 static proc_t memorystatus_get_next_proc_locked(unsigned int *bucket_index, proc_t p, boolean_t search) {
1388 memstat_bucket_t *current_bucket;
1389 proc_t next_p;
1390
1391 if (!p || ((*bucket_index) >= MEMSTAT_BUCKET_COUNT)) {
1392 return NULL;
1393 }
1394
1395 next_p = TAILQ_NEXT(p, p_memstat_list);
1396 while (!next_p && search && (++(*bucket_index) < MEMSTAT_BUCKET_COUNT)) {
1397 current_bucket = &memstat_bucket[*bucket_index];
1398 next_p = TAILQ_FIRST(&current_bucket->list);
1399 }
1400
1401 return next_p;
1402 }
1403
1404 __private_extern__ void
1405 memorystatus_init(void)
1406 {
1407 thread_t thread = THREAD_NULL;
1408 kern_return_t result;
1409 int i;
1410
1411 #if CONFIG_FREEZE
1412 memorystatus_freeze_pages_min = FREEZE_PAGES_MIN;
1413 memorystatus_freeze_pages_max = FREEZE_PAGES_MAX;
1414 #endif
1415
1416 #if DEVELOPMENT || DEBUG
1417 disconnect_page_mappings_lck_grp_attr = lck_grp_attr_alloc_init();
1418 disconnect_page_mappings_lck_grp = lck_grp_alloc_init("disconnect_page_mappings", disconnect_page_mappings_lck_grp_attr);
1419
1420 lck_mtx_init(&disconnect_page_mappings_mutex, disconnect_page_mappings_lck_grp, NULL);
1421 #endif
1422
1423 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS * NSEC_PER_SEC, &memorystatus_sysprocs_idle_delay_time);
1424 nanoseconds_to_absolutetime((uint64_t)DEFERRED_IDLE_EXIT_TIME_SECS * NSEC_PER_SEC, &memorystatus_apps_idle_delay_time);
1425
1426 /* Init buckets */
1427 for (i = 0; i < MEMSTAT_BUCKET_COUNT; i++) {
1428 TAILQ_INIT(&memstat_bucket[i].list);
1429 memstat_bucket[i].count = 0;
1430 }
1431
1432 memorystatus_idle_demotion_call = thread_call_allocate((thread_call_func_t)memorystatus_perform_idle_demotion, NULL);
1433
1434 /* Apply overrides */
1435 PE_get_default("kern.jetsam_delta", &delta_percentage, sizeof(delta_percentage));
1436 if (delta_percentage == 0) {
1437 delta_percentage = 5;
1438 }
1439 assert(delta_percentage < 100);
1440 PE_get_default("kern.jetsam_critical_threshold", &critical_threshold_percentage, sizeof(critical_threshold_percentage));
1441 assert(critical_threshold_percentage < 100);
1442 PE_get_default("kern.jetsam_idle_offset", &idle_offset_percentage, sizeof(idle_offset_percentage));
1443 assert(idle_offset_percentage < 100);
1444 PE_get_default("kern.jetsam_pressure_threshold", &pressure_threshold_percentage, sizeof(pressure_threshold_percentage));
1445 assert(pressure_threshold_percentage < 100);
1446 PE_get_default("kern.jetsam_freeze_threshold", &freeze_threshold_percentage, sizeof(freeze_threshold_percentage));
1447 assert(freeze_threshold_percentage < 100);
1448
1449 if (!PE_parse_boot_argn("jetsam_aging_policy", &jetsam_aging_policy,
1450 sizeof (jetsam_aging_policy))) {
1451
1452 if (!PE_get_default("kern.jetsam_aging_policy", &jetsam_aging_policy,
1453 sizeof(jetsam_aging_policy))) {
1454
1455 jetsam_aging_policy = kJetsamAgingPolicyLegacy;
1456 }
1457 }
1458
1459 if (jetsam_aging_policy > kJetsamAgingPolicyMax) {
1460 jetsam_aging_policy = kJetsamAgingPolicyLegacy;
1461 }
1462
1463 switch (jetsam_aging_policy) {
1464
1465 case kJetsamAgingPolicyNone:
1466 system_procs_aging_band = JETSAM_PRIORITY_IDLE;
1467 applications_aging_band = JETSAM_PRIORITY_IDLE;
1468 break;
1469
1470 case kJetsamAgingPolicyLegacy:
1471 /*
1472 * Legacy behavior where some daemons get a 10s protection once
1473 * AND only before the first clean->dirty->clean transition before
1474 * going into IDLE band.
1475 */
1476 system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
1477 applications_aging_band = JETSAM_PRIORITY_IDLE;
1478 break;
1479
1480 case kJetsamAgingPolicySysProcsReclaimedFirst:
1481 system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND1;
1482 applications_aging_band = JETSAM_PRIORITY_AGING_BAND2;
1483 break;
1484
1485 case kJetsamAgingPolicyAppsReclaimedFirst:
1486 system_procs_aging_band = JETSAM_PRIORITY_AGING_BAND2;
1487 applications_aging_band = JETSAM_PRIORITY_AGING_BAND1;
1488 break;
1489
1490 default:
1491 break;
1492 }
1493
1494 /*
1495 * The aging bands cannot overlap with the JETSAM_PRIORITY_ELEVATED_INACTIVE
1496 * band and must be below it in priority. This is so that we don't have to make
1497 * our 'aging' code worry about a mix of processes, some of which need to age
1498 * and some others that need to stay elevated in the jetsam bands.
1499 */
1500 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE > system_procs_aging_band);
1501 assert(JETSAM_PRIORITY_ELEVATED_INACTIVE > applications_aging_band);
1502
1503 #if CONFIG_JETSAM
1504 /* Take snapshots for idle-exit kills by default? First check the boot-arg... */
1505 if (!PE_parse_boot_argn("jetsam_idle_snapshot", &memorystatus_idle_snapshot, sizeof (memorystatus_idle_snapshot))) {
1506 /* ...no boot-arg, so check the device tree */
1507 PE_get_default("kern.jetsam_idle_snapshot", &memorystatus_idle_snapshot, sizeof(memorystatus_idle_snapshot));
1508 }
1509
1510 memorystatus_delta = delta_percentage * atop_64(max_mem) / 100;
1511 memorystatus_available_pages_critical_idle_offset = idle_offset_percentage * atop_64(max_mem) / 100;
1512 memorystatus_available_pages_critical_base = (critical_threshold_percentage / delta_percentage) * memorystatus_delta;
1513 memorystatus_policy_more_free_offset_pages = (policy_more_free_offset_percentage / delta_percentage) * memorystatus_delta;
1514
1515 memorystatus_jetsam_snapshot_max = maxproc;
1516 memorystatus_jetsam_snapshot =
1517 (memorystatus_jetsam_snapshot_t*)kalloc(sizeof(memorystatus_jetsam_snapshot_t) +
1518 sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_max);
1519 if (!memorystatus_jetsam_snapshot) {
1520 panic("Could not allocate memorystatus_jetsam_snapshot");
1521 }
1522
1523 nanoseconds_to_absolutetime((uint64_t)JETSAM_SNAPSHOT_TIMEOUT_SECS * NSEC_PER_SEC, &memorystatus_jetsam_snapshot_timeout);
1524
1525 memset(&memorystatus_at_boot_snapshot, 0, sizeof(memorystatus_jetsam_snapshot_t));
1526
1527 /* No contention at this point */
1528 memorystatus_update_levels_locked(FALSE);
1529
1530 /* Jetsam Loop Detection */
1531 if (max_mem <= (512 * 1024 * 1024)) {
1532 /* 512 MB devices */
1533 memorystatus_jld_eval_period_msecs = 8000; /* 8000 msecs == 8 second window */
1534 } else {
1535 /* 1GB and larger devices */
1536 memorystatus_jld_eval_period_msecs = 6000; /* 6000 msecs == 6 second window */
1537 }
1538 #endif
1539
1540 #if CONFIG_FREEZE
1541 memorystatus_freeze_threshold = (freeze_threshold_percentage / delta_percentage) * memorystatus_delta;
1542 #endif
1543
1544 result = kernel_thread_start_priority(memorystatus_thread, NULL, 95 /* MAXPRI_KERNEL */, &thread);
1545 if (result == KERN_SUCCESS) {
1546 thread_deallocate(thread);
1547 } else {
1548 panic("Could not create memorystatus_thread");
1549 }
1550 }
1551
1552 /* Centralised for the purposes of allowing panic-on-jetsam */
1553 extern void
1554 vm_run_compactor(void);
1555
1556 /*
1557 * The jetsam no frills kill call
1558 * Return: 0 on success
1559 * error code on failure (EINVAL...)
1560 */
1561 static int
1562 jetsam_do_kill(proc_t p, int jetsam_flags, os_reason_t jetsam_reason) {
1563 int error = 0;
1564 error = exit_with_reason(p, W_EXITCODE(0, SIGKILL), (int *)NULL, FALSE, FALSE, jetsam_flags, jetsam_reason);
1565 return(error);
1566 }
1567
1568 /*
1569 * Wrapper for processes exiting with memorystatus details
1570 */
1571 static boolean_t
1572 memorystatus_do_kill(proc_t p, uint32_t cause, os_reason_t jetsam_reason) {
1573
1574 int error = 0;
1575 __unused pid_t victim_pid = p->p_pid;
1576
1577 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DO_KILL)) | DBG_FUNC_START,
1578 victim_pid, cause, vm_page_free_count, 0, 0);
1579
1580 DTRACE_MEMORYSTATUS3(memorystatus_do_kill, proc_t, p, os_reason_t, jetsam_reason, uint32_t, cause);
1581 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
1582 if (memorystatus_jetsam_panic_debug & (1 << cause)) {
1583 panic("memorystatus_do_kill(): jetsam debug panic (cause: %d)", cause);
1584 }
1585 #else
1586 #pragma unused(cause)
1587 #endif
1588 int jetsam_flags = P_LTERM_JETSAM;
1589 switch (cause) {
1590 case kMemorystatusKilledHiwat: jetsam_flags |= P_JETSAM_HIWAT; break;
1591 case kMemorystatusKilledVnodes: jetsam_flags |= P_JETSAM_VNODE; break;
1592 case kMemorystatusKilledVMPageShortage: jetsam_flags |= P_JETSAM_VMPAGESHORTAGE; break;
1593 case kMemorystatusKilledVMThrashing: jetsam_flags |= P_JETSAM_VMTHRASHING; break;
1594 case kMemorystatusKilledFCThrashing: jetsam_flags |= P_JETSAM_FCTHRASHING; break;
1595 case kMemorystatusKilledPerProcessLimit: jetsam_flags |= P_JETSAM_PID; break;
1596 case kMemorystatusKilledIdleExit: jetsam_flags |= P_JETSAM_IDLEEXIT; break;
1597 }
1598 error = jetsam_do_kill(p, jetsam_flags, jetsam_reason);
1599
1600 KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DO_KILL)) | DBG_FUNC_END,
1601 victim_pid, cause, vm_page_free_count, error, 0);
1602
1603 vm_run_compactor();
1604
1605 return (error == 0);
1606 }
1607
1608 /*
1609 * Node manipulation
1610 */
1611
1612 static void
1613 memorystatus_check_levels_locked(void) {
1614 #if CONFIG_JETSAM
1615 /* Update levels */
1616 memorystatus_update_levels_locked(TRUE);
1617 #endif
1618 }
1619
1620 /*
1621 * Pin a process to a particular jetsam band when it is in the background i.e. not doing active work.
1622 * For an application: that means no longer in the FG band
1623 * For a daemon: that means no longer in its 'requested' jetsam priority band
1624 */
1625
1626 int
1627 memorystatus_update_inactive_jetsam_priority_band(pid_t pid, uint32_t op_flags, boolean_t effective_now)
1628 {
1629 int error = 0;
1630 boolean_t enable = FALSE;
1631 proc_t p = NULL;
1632
1633 if (op_flags == MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE) {
1634 enable = TRUE;
1635 } else if (op_flags == MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE) {
1636 enable = FALSE;
1637 } else {
1638 return EINVAL;
1639 }
1640
1641 p = proc_find(pid);
1642 if (p != NULL) {
1643
1644 if ((enable && ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) == P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) ||
1645 (!enable && ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) == 0))) {
1646 /*
1647 * No change in state.
1648 */
1649
1650 } else {
1651
1652 proc_list_lock();
1653
1654 if (enable) {
1655 p->p_memstat_state |= P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND;
1656 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1657
1658 if (effective_now) {
1659 if (p->p_memstat_effectivepriority < JETSAM_PRIORITY_ELEVATED_INACTIVE) {
1660 if(memorystatus_highwater_enabled) {
1661 /*
1662 * Process is about to transition from
1663 * inactive --> active
1664 * assign active state
1665 */
1666 boolean_t is_fatal;
1667 boolean_t use_active = TRUE;
1668 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
1669 task_set_phys_footprint_limit_internal(p->task, (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1, NULL, use_active, is_fatal);
1670 }
1671 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_ELEVATED_INACTIVE, FALSE, FALSE);
1672 }
1673 } else {
1674 if (isProcessInAgingBands(p)) {
1675 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1676 }
1677 }
1678 } else {
1679
1680 p->p_memstat_state &= ~P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND;
1681 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1682
1683 if (effective_now) {
1684 if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_ELEVATED_INACTIVE) {
1685 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1686 }
1687 } else {
1688 if (isProcessInAgingBands(p)) {
1689 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
1690 }
1691 }
1692 }
1693
1694 proc_list_unlock();
1695 }
1696 proc_rele(p);
1697 error = 0;
1698
1699 } else {
1700 error = ESRCH;
1701 }
1702
1703 return error;
1704 }
1705
1706 static void
1707 memorystatus_perform_idle_demotion(__unused void *spare1, __unused void *spare2)
1708 {
1709 proc_t p;
1710 uint64_t current_time = 0, idle_delay_time = 0;
1711 int demote_prio_band = 0;
1712 memstat_bucket_t *demotion_bucket;
1713
1714 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion()\n");
1715
1716 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_IDLE_DEMOTE) | DBG_FUNC_START, 0, 0, 0, 0, 0);
1717
1718 current_time = mach_absolute_time();
1719
1720 proc_list_lock();
1721
1722 demote_prio_band = JETSAM_PRIORITY_IDLE + 1;
1723
1724 for (; demote_prio_band < JETSAM_PRIORITY_MAX; demote_prio_band++) {
1725
1726 if (demote_prio_band != system_procs_aging_band && demote_prio_band != applications_aging_band)
1727 continue;
1728
1729 demotion_bucket = &memstat_bucket[demote_prio_band];
1730 p = TAILQ_FIRST(&demotion_bucket->list);
1731
1732 while (p) {
1733 MEMORYSTATUS_DEBUG(1, "memorystatus_perform_idle_demotion() found %d\n", p->p_pid);
1734
1735 assert(p->p_memstat_idledeadline);
1736
1737 assert(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS);
1738
1739 if (current_time >= p->p_memstat_idledeadline) {
1740
1741 if ((isSysProc(p) &&
1742 ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED|P_DIRTY_IS_DIRTY)) != P_DIRTY_IDLE_EXIT_ENABLED)) || /* system proc marked dirty*/
1743 task_has_assertions((struct task *)(p->task))) { /* has outstanding assertions which might indicate outstanding work too */
1744 idle_delay_time = (isSysProc(p)) ? memorystatus_sysprocs_idle_delay_time : memorystatus_apps_idle_delay_time;
1745
1746 p->p_memstat_idledeadline += idle_delay_time;
1747 p = TAILQ_NEXT(p, p_memstat_list);
1748
1749 } else {
1750
1751 proc_t next_proc = NULL;
1752
1753 next_proc = TAILQ_NEXT(p, p_memstat_list);
1754 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
1755
1756 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, false, true);
1757
1758 p = next_proc;
1759 continue;
1760
1761 }
1762 } else {
1763 // No further candidates
1764 break;
1765 }
1766 }
1767
1768 }
1769
1770 memorystatus_reschedule_idle_demotion_locked();
1771
1772 proc_list_unlock();
1773
1774 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_IDLE_DEMOTE) | DBG_FUNC_END, 0, 0, 0, 0, 0);
1775 }
1776
1777 static void
1778 memorystatus_schedule_idle_demotion_locked(proc_t p, boolean_t set_state)
1779 {
1780 boolean_t present_in_sysprocs_aging_bucket = FALSE;
1781 boolean_t present_in_apps_aging_bucket = FALSE;
1782 uint64_t idle_delay_time = 0;
1783
1784 if (jetsam_aging_policy == kJetsamAgingPolicyNone) {
1785 return;
1786 }
1787
1788 if (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) {
1789 /*
1790 * This process isn't going to be making the trip to the lower bands.
1791 */
1792 return;
1793 }
1794
1795 if (isProcessInAgingBands(p)){
1796
1797 if (jetsam_aging_policy != kJetsamAgingPolicyLegacy) {
1798 assert((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) != P_DIRTY_AGING_IN_PROGRESS);
1799 }
1800
1801 if (isSysProc(p) && system_procs_aging_band) {
1802 present_in_sysprocs_aging_bucket = TRUE;
1803
1804 } else if (isApp(p) && applications_aging_band) {
1805 present_in_apps_aging_bucket = TRUE;
1806 }
1807 }
1808
1809 assert(!present_in_sysprocs_aging_bucket);
1810 assert(!present_in_apps_aging_bucket);
1811
1812 MEMORYSTATUS_DEBUG(1, "memorystatus_schedule_idle_demotion_locked: scheduling demotion to idle band for pid %d (dirty:0x%x, set_state %d, demotions %d).\n",
1813 p->p_pid, p->p_memstat_dirty, set_state, (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps));
1814
1815 if(isSysProc(p)) {
1816 assert((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED);
1817 }
1818
1819 idle_delay_time = (isSysProc(p)) ? memorystatus_sysprocs_idle_delay_time : memorystatus_apps_idle_delay_time;
1820
1821 if (set_state) {
1822 p->p_memstat_dirty |= P_DIRTY_AGING_IN_PROGRESS;
1823 p->p_memstat_idledeadline = mach_absolute_time() + idle_delay_time;
1824 }
1825
1826 assert(p->p_memstat_idledeadline);
1827
1828 if (isSysProc(p) && present_in_sysprocs_aging_bucket == FALSE) {
1829 memorystatus_scheduled_idle_demotions_sysprocs++;
1830
1831 } else if (isApp(p) && present_in_apps_aging_bucket == FALSE) {
1832 memorystatus_scheduled_idle_demotions_apps++;
1833 }
1834 }
1835
1836 static void
1837 memorystatus_invalidate_idle_demotion_locked(proc_t p, boolean_t clear_state)
1838 {
1839 boolean_t present_in_sysprocs_aging_bucket = FALSE;
1840 boolean_t present_in_apps_aging_bucket = FALSE;
1841
1842 if (!system_procs_aging_band && !applications_aging_band) {
1843 return;
1844 }
1845
1846 if ((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) == 0) {
1847 return;
1848 }
1849
1850 if (isProcessInAgingBands(p)) {
1851
1852 if (jetsam_aging_policy != kJetsamAgingPolicyLegacy) {
1853 assert((p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) == P_DIRTY_AGING_IN_PROGRESS);
1854 }
1855
1856 if (isSysProc(p) && system_procs_aging_band) {
1857 assert(p->p_memstat_effectivepriority == system_procs_aging_band);
1858 assert(p->p_memstat_idledeadline);
1859 present_in_sysprocs_aging_bucket = TRUE;
1860
1861 } else if (isApp(p) && applications_aging_band) {
1862 assert(p->p_memstat_effectivepriority == applications_aging_band);
1863 assert(p->p_memstat_idledeadline);
1864 present_in_apps_aging_bucket = TRUE;
1865 }
1866 }
1867
1868 MEMORYSTATUS_DEBUG(1, "memorystatus_invalidate_idle_demotion(): invalidating demotion to idle band for pid %d (clear_state %d, demotions %d).\n",
1869 p->p_pid, clear_state, (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps));
1870
1871
1872 if (clear_state) {
1873 p->p_memstat_idledeadline = 0;
1874 p->p_memstat_dirty &= ~P_DIRTY_AGING_IN_PROGRESS;
1875 }
1876
1877 if (isSysProc(p) &&present_in_sysprocs_aging_bucket == TRUE) {
1878 memorystatus_scheduled_idle_demotions_sysprocs--;
1879 assert(memorystatus_scheduled_idle_demotions_sysprocs >= 0);
1880
1881 } else if (isApp(p) && present_in_apps_aging_bucket == TRUE) {
1882 memorystatus_scheduled_idle_demotions_apps--;
1883 assert(memorystatus_scheduled_idle_demotions_apps >= 0);
1884 }
1885
1886 assert((memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps) >= 0);
1887 }
1888
1889 static void
1890 memorystatus_reschedule_idle_demotion_locked(void) {
1891 if (0 == (memorystatus_scheduled_idle_demotions_sysprocs + memorystatus_scheduled_idle_demotions_apps)) {
1892 if (memstat_idle_demotion_deadline) {
1893 /* Transitioned 1->0, so cancel next call */
1894 thread_call_cancel(memorystatus_idle_demotion_call);
1895 memstat_idle_demotion_deadline = 0;
1896 }
1897 } else {
1898 memstat_bucket_t *demotion_bucket;
1899 proc_t p = NULL, p1 = NULL, p2 = NULL;
1900
1901 if (system_procs_aging_band) {
1902
1903 demotion_bucket = &memstat_bucket[system_procs_aging_band];
1904 p1 = TAILQ_FIRST(&demotion_bucket->list);
1905
1906 p = p1;
1907 }
1908
1909 if (applications_aging_band) {
1910
1911 demotion_bucket = &memstat_bucket[applications_aging_band];
1912 p2 = TAILQ_FIRST(&demotion_bucket->list);
1913
1914 if (p1 && p2) {
1915 p = (p1->p_memstat_idledeadline > p2->p_memstat_idledeadline) ? p2 : p1;
1916 } else {
1917 p = (p1 == NULL) ? p2 : p1;
1918 }
1919
1920 }
1921
1922 assert(p);
1923
1924 if (p != NULL) {
1925 assert(p && p->p_memstat_idledeadline);
1926 if (memstat_idle_demotion_deadline != p->p_memstat_idledeadline){
1927 thread_call_enter_delayed(memorystatus_idle_demotion_call, p->p_memstat_idledeadline);
1928 memstat_idle_demotion_deadline = p->p_memstat_idledeadline;
1929 }
1930 }
1931 }
1932 }
1933
1934 /*
1935 * List manipulation
1936 */
1937
1938 int
1939 memorystatus_add(proc_t p, boolean_t locked)
1940 {
1941 memstat_bucket_t *bucket;
1942
1943 MEMORYSTATUS_DEBUG(1, "memorystatus_list_add(): adding pid %d with priority %d.\n", p->p_pid, p->p_memstat_effectivepriority);
1944
1945 if (!locked) {
1946 proc_list_lock();
1947 }
1948
1949 DTRACE_MEMORYSTATUS2(memorystatus_add, proc_t, p, int32_t, p->p_memstat_effectivepriority);
1950
1951 /* Processes marked internal do not have priority tracked */
1952 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
1953 goto exit;
1954 }
1955
1956 bucket = &memstat_bucket[p->p_memstat_effectivepriority];
1957
1958 if (isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) {
1959 assert(bucket->count == memorystatus_scheduled_idle_demotions_sysprocs - 1);
1960
1961 } else if (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)) {
1962 assert(bucket->count == memorystatus_scheduled_idle_demotions_apps - 1);
1963
1964 } else if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
1965 /*
1966 * Entering the idle band.
1967 * Record idle start time.
1968 */
1969 p->p_memstat_idle_start = mach_absolute_time();
1970 }
1971
1972 TAILQ_INSERT_TAIL(&bucket->list, p, p_memstat_list);
1973 bucket->count++;
1974
1975 memorystatus_list_count++;
1976
1977 memorystatus_check_levels_locked();
1978
1979 exit:
1980 if (!locked) {
1981 proc_list_unlock();
1982 }
1983
1984 return 0;
1985 }
1986
1987 /*
1988 * Description:
1989 * Moves a process from one jetsam bucket to another.
1990 * which changes the LRU position of the process.
1991 *
1992 * Monitors transition between buckets and if necessary
1993 * will update cached memory limits accordingly.
1994 *
1995 * skip_demotion_check:
1996 * - if the 'jetsam aging policy' is NOT 'legacy':
1997 * When this flag is TRUE, it means we are going
1998 * to age the ripe processes out of the aging bands and into the
1999 * IDLE band and apply their inactive memory limits.
2000 *
2001 * - if the 'jetsam aging policy' is 'legacy':
2002 * When this flag is TRUE, it might mean the above aging mechanism
2003 * OR
2004 * It might be that we have a process that has used up its 'idle deferral'
2005 * stay that is given to it once per lifetime. And in this case, the process
2006 * won't be going through any aging codepaths. But we still need to apply
2007 * the right inactive limits and so we explicitly set this to TRUE if the
2008 * new priority for the process is the IDLE band.
2009 */
2010 void
2011 memorystatus_update_priority_locked(proc_t p, int priority, boolean_t head_insert, boolean_t skip_demotion_check)
2012 {
2013 memstat_bucket_t *old_bucket, *new_bucket;
2014
2015 assert(priority < MEMSTAT_BUCKET_COUNT);
2016
2017 /* Ensure that exit isn't underway, leaving the proc retained but removed from its bucket */
2018 if ((p->p_listflag & P_LIST_EXITED) != 0) {
2019 return;
2020 }
2021
2022 MEMORYSTATUS_DEBUG(1, "memorystatus_update_priority_locked(): setting %s(%d) to priority %d, inserting at %s\n",
2023 (*p->p_name ? p->p_name : "unknown"), p->p_pid, priority, head_insert ? "head" : "tail");
2024
2025 DTRACE_MEMORYSTATUS3(memorystatus_update_priority, proc_t, p, int32_t, p->p_memstat_effectivepriority, int, priority);
2026
2027 #if DEVELOPMENT || DEBUG
2028 if (priority == JETSAM_PRIORITY_IDLE && /* if the process is on its way into the IDLE band */
2029 skip_demotion_check == FALSE && /* and it isn't via the path that will set the INACTIVE memlimits */
2030 (p->p_memstat_dirty & P_DIRTY_TRACK) && /* and it has 'DIRTY' tracking enabled */
2031 ((p->p_memstat_memlimit != p->p_memstat_memlimit_inactive) || /* and we notice that the current limit isn't the right value (inactive) */
2032 ((p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) ? ( ! (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT)) : (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT)))) /* OR type (fatal vs non-fatal) */
2033 panic("memorystatus_update_priority_locked: on %s with 0x%x, prio: %d and %d\n", p->p_name, p->p_memstat_state, priority, p->p_memstat_memlimit); /* then we must catch this */
2034 #endif /* DEVELOPMENT || DEBUG */
2035
2036 old_bucket = &memstat_bucket[p->p_memstat_effectivepriority];
2037
2038 if (skip_demotion_check == FALSE) {
2039
2040 if (isSysProc(p)) {
2041 /*
2042 * For system processes, the memorystatus_dirty_* routines take care of adding/removing
2043 * the processes from the aging bands and balancing the demotion counts.
2044 * We can, however, override that if the process has an 'elevated inactive jetsam band' attribute.
2045 */
2046
2047 if (priority <= JETSAM_PRIORITY_ELEVATED_INACTIVE && (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) {
2048 priority = JETSAM_PRIORITY_ELEVATED_INACTIVE;
2049
2050 assert(! (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS));
2051 }
2052 } else if (isApp(p)) {
2053
2054 /*
2055 * Check to see if the application is being lowered in jetsam priority. If so, and:
2056 * - it has an 'elevated inactive jetsam band' attribute, then put it in the JETSAM_PRIORITY_ELEVATED_INACTIVE band.
2057 * - it is a normal application, then let it age in the aging band if that policy is in effect.
2058 */
2059
2060 if (priority <= JETSAM_PRIORITY_ELEVATED_INACTIVE && (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) {
2061 priority = JETSAM_PRIORITY_ELEVATED_INACTIVE;
2062 } else {
2063
2064 if (applications_aging_band) {
2065 if (p->p_memstat_effectivepriority == applications_aging_band) {
2066 assert(old_bucket->count == (memorystatus_scheduled_idle_demotions_apps + 1));
2067 }
2068
2069 if ((jetsam_aging_policy != kJetsamAgingPolicyLegacy) && (priority <= applications_aging_band)) {
2070 assert(! (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS));
2071 priority = applications_aging_band;
2072 memorystatus_schedule_idle_demotion_locked(p, TRUE);
2073 }
2074 }
2075 }
2076 }
2077 }
2078
2079 if ((system_procs_aging_band && (priority == system_procs_aging_band)) || (applications_aging_band && (priority == applications_aging_band))) {
2080 assert(p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS);
2081 }
2082
2083 TAILQ_REMOVE(&old_bucket->list, p, p_memstat_list);
2084 old_bucket->count--;
2085
2086 new_bucket = &memstat_bucket[priority];
2087 if (head_insert)
2088 TAILQ_INSERT_HEAD(&new_bucket->list, p, p_memstat_list);
2089 else
2090 TAILQ_INSERT_TAIL(&new_bucket->list, p, p_memstat_list);
2091 new_bucket->count++;
2092
2093 if (memorystatus_highwater_enabled) {
2094 boolean_t is_fatal;
2095 boolean_t use_active;
2096
2097 /*
2098 * If cached limit data is updated, then the limits
2099 * will be enforced by writing to the ledgers.
2100 */
2101 boolean_t ledger_update_needed = TRUE;
2102
2103 /*
2104 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
2105 * Background limits are described via the inactive limit slots.
2106 *
2107 * Here, we must update the cached memory limit if the task
2108 * is transitioning between:
2109 * active <--> inactive
2110 * FG <--> BG
2111 * but:
2112 * dirty <--> clean is ignored
2113 *
2114 * We bypass non-idle processes that have opted into dirty tracking because
2115 * a move between buckets does not imply a transition between the
2116 * dirty <--> clean state.
2117 */
2118
2119 if (p->p_memstat_dirty & P_DIRTY_TRACK) {
2120
2121 if (skip_demotion_check == TRUE && priority == JETSAM_PRIORITY_IDLE) {
2122 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2123 use_active = FALSE;
2124 } else {
2125 ledger_update_needed = FALSE;
2126 }
2127
2128 } else if ((priority >= JETSAM_PRIORITY_FOREGROUND) && (p->p_memstat_effectivepriority < JETSAM_PRIORITY_FOREGROUND)) {
2129 /*
2130 * inactive --> active
2131 * BG --> FG
2132 * assign active state
2133 */
2134 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
2135 use_active = TRUE;
2136
2137 } else if ((priority < JETSAM_PRIORITY_FOREGROUND) && (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND)) {
2138 /*
2139 * active --> inactive
2140 * FG --> BG
2141 * assign inactive state
2142 */
2143 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2144 use_active = FALSE;
2145 } else {
2146 /*
2147 * The transition between jetsam priority buckets apparently did
2148 * not affect active/inactive state.
2149 * This is not unusual... especially during startup when
2150 * processes are getting established in their respective bands.
2151 */
2152 ledger_update_needed = FALSE;
2153 }
2154
2155 /*
2156 * Enforce the new limits by writing to the ledger
2157 */
2158 if (ledger_update_needed) {
2159 task_set_phys_footprint_limit_internal(p->task, (p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1, NULL, use_active, is_fatal);
2160
2161 MEMORYSTATUS_DEBUG(3, "memorystatus_update_priority_locked: new limit on pid %d (%dMB %s) priority old --> new (%d --> %d) dirty?=0x%x %s\n",
2162 p->p_pid, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
2163 (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, priority, p->p_memstat_dirty,
2164 (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
2165 }
2166 }
2167
2168 /*
2169 * Record idle start or idle delta.
2170 */
2171 if (p->p_memstat_effectivepriority == priority) {
2172 /*
2173 * This process is not transitioning between
2174 * jetsam priority buckets. Do nothing.
2175 */
2176 } else if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
2177 uint64_t now;
2178 /*
2179 * Transitioning out of the idle priority bucket.
2180 * Record idle delta.
2181 */
2182 assert(p->p_memstat_idle_start != 0);
2183 now = mach_absolute_time();
2184 if (now > p->p_memstat_idle_start) {
2185 p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
2186 }
2187 } else if (priority == JETSAM_PRIORITY_IDLE) {
2188 /*
2189 * Transitioning into the idle priority bucket.
2190 * Record idle start.
2191 */
2192 p->p_memstat_idle_start = mach_absolute_time();
2193 }
2194
2195 p->p_memstat_effectivepriority = priority;
2196
2197 #if CONFIG_SECLUDED_MEMORY
2198 if (secluded_for_apps &&
2199 task_could_use_secluded_mem(p->task)) {
2200 task_set_can_use_secluded_mem(
2201 p->task,
2202 (priority >= JETSAM_PRIORITY_FOREGROUND));
2203 }
2204 #endif /* CONFIG_SECLUDED_MEMORY */
2205
2206 memorystatus_check_levels_locked();
2207 }
2208
2209 /*
2210 *
2211 * Description: Update the jetsam priority and memory limit attributes for a given process.
2212 *
2213 * Parameters:
2214 * p init this process's jetsam information.
2215 * priority The jetsam priority band
2216 * user_data user specific data, unused by the kernel
2217 * effective guards against race if process's update already occurred
2218 * update_memlimit When true we know this is the init step via the posix_spawn path.
2219 *
2220 * memlimit_active Value in megabytes; The monitored footprint level while the
2221 * process is active. Exceeding it may result in termination
2222 * based on it's associated fatal flag.
2223 *
2224 * memlimit_active_is_fatal When a process is active and exceeds its memory footprint,
2225 * this describes whether or not it should be immediately fatal.
2226 *
2227 * memlimit_inactive Value in megabytes; The monitored footprint level while the
2228 * process is inactive. Exceeding it may result in termination
2229 * based on it's associated fatal flag.
2230 *
2231 * memlimit_inactive_is_fatal When a process is inactive and exceeds its memory footprint,
2232 * this describes whether or not it should be immediatly fatal.
2233 *
2234 * memlimit_background This process has a high-water-mark while in the background.
2235 * No longer meaningful. Background limits are described via
2236 * the inactive slots. Flag is ignored.
2237 *
2238 *
2239 * Returns: 0 Success
2240 * non-0 Failure
2241 */
2242
2243 int
2244 memorystatus_update(proc_t p, int priority, uint64_t user_data, boolean_t effective, boolean_t update_memlimit,
2245 int32_t memlimit_active, boolean_t memlimit_active_is_fatal,
2246 int32_t memlimit_inactive, boolean_t memlimit_inactive_is_fatal,
2247 __unused boolean_t memlimit_background)
2248 {
2249 int ret;
2250 boolean_t head_insert = false;
2251
2252 MEMORYSTATUS_DEBUG(1, "memorystatus_update: changing (%s) pid %d: priority %d, user_data 0x%llx\n", (*p->p_name ? p->p_name : "unknown"), p->p_pid, priority, user_data);
2253
2254 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_UPDATE) | DBG_FUNC_START, p->p_pid, priority, user_data, effective, 0);
2255
2256 if (priority == -1) {
2257 /* Use as shorthand for default priority */
2258 priority = JETSAM_PRIORITY_DEFAULT;
2259 } else if ((priority == system_procs_aging_band) || (priority == applications_aging_band)) {
2260 /* Both the aging bands are reserved for internal use; if requested, adjust to JETSAM_PRIORITY_IDLE. */
2261 priority = JETSAM_PRIORITY_IDLE;
2262 } else if (priority == JETSAM_PRIORITY_IDLE_HEAD) {
2263 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle queue */
2264 priority = JETSAM_PRIORITY_IDLE;
2265 head_insert = TRUE;
2266 } else if ((priority < 0) || (priority >= MEMSTAT_BUCKET_COUNT)) {
2267 /* Sanity check */
2268 ret = EINVAL;
2269 goto out;
2270 }
2271
2272 proc_list_lock();
2273
2274 assert(!(p->p_memstat_state & P_MEMSTAT_INTERNAL));
2275
2276 if (effective && (p->p_memstat_state & P_MEMSTAT_PRIORITYUPDATED)) {
2277 ret = EALREADY;
2278 proc_list_unlock();
2279 MEMORYSTATUS_DEBUG(1, "memorystatus_update: effective change specified for pid %d, but change already occurred.\n", p->p_pid);
2280 goto out;
2281 }
2282
2283 if ((p->p_memstat_state & P_MEMSTAT_TERMINATED) || ((p->p_listflag & P_LIST_EXITED) != 0)) {
2284 /*
2285 * This could happen when a process calling posix_spawn() is exiting on the jetsam thread.
2286 */
2287 ret = EBUSY;
2288 proc_list_unlock();
2289 goto out;
2290 }
2291
2292 p->p_memstat_state |= P_MEMSTAT_PRIORITYUPDATED;
2293 p->p_memstat_userdata = user_data;
2294 p->p_memstat_requestedpriority = priority;
2295
2296 if (update_memlimit) {
2297 boolean_t is_fatal;
2298 boolean_t use_active;
2299
2300 /*
2301 * Posix_spawn'd processes come through this path to instantiate ledger limits.
2302 * Forked processes do not come through this path, so no ledger limits exist.
2303 * (That's why forked processes can consume unlimited memory.)
2304 */
2305
2306 MEMORYSTATUS_DEBUG(3, "memorystatus_update(enter): pid %d, priority %d, dirty=0x%x, Active(%dMB %s), Inactive(%dMB, %s)\n",
2307 p->p_pid, priority, p->p_memstat_dirty,
2308 memlimit_active, (memlimit_active_is_fatal ? "F " : "NF"),
2309 memlimit_inactive, (memlimit_inactive_is_fatal ? "F " : "NF"));
2310
2311 if (memlimit_background) {
2312
2313 /*
2314 * With 2-level HWM support, we no longer honor P_MEMSTAT_MEMLIMIT_BACKGROUND.
2315 * Background limits are described via the inactive limit slots.
2316 */
2317
2318 // p->p_memstat_state |= P_MEMSTAT_MEMLIMIT_BACKGROUND;
2319
2320 #if DEVELOPMENT || DEBUG
2321 printf("memorystatus_update: WARNING %s[%d] set unused flag P_MEMSTAT_MEMLIMIT_BACKGROUND [A==%dMB %s] [IA==%dMB %s]\n",
2322 (*p->p_name ? p->p_name : "unknown"), p->p_pid,
2323 memlimit_active, (memlimit_active_is_fatal ? "F " : "NF"),
2324 memlimit_inactive, (memlimit_inactive_is_fatal ? "F " : "NF"));
2325 #endif /* DEVELOPMENT || DEBUG */
2326 }
2327
2328 if (memlimit_active <= 0) {
2329 /*
2330 * This process will have a system_wide task limit when active.
2331 * System_wide task limit is always fatal.
2332 * It's quite common to see non-fatal flag passed in here.
2333 * It's not an error, we just ignore it.
2334 */
2335
2336 /*
2337 * For backward compatibility with some unexplained launchd behavior,
2338 * we allow a zero sized limit. But we still enforce system_wide limit
2339 * when written to the ledgers.
2340 */
2341
2342 if (memlimit_active < 0) {
2343 memlimit_active = -1; /* enforces system_wide task limit */
2344 }
2345 memlimit_active_is_fatal = TRUE;
2346 }
2347
2348 if (memlimit_inactive <= 0) {
2349 /*
2350 * This process will have a system_wide task limit when inactive.
2351 * System_wide task limit is always fatal.
2352 */
2353
2354 memlimit_inactive = -1;
2355 memlimit_inactive_is_fatal = TRUE;
2356 }
2357
2358 /*
2359 * Initialize the active limit variants for this process.
2360 */
2361 SET_ACTIVE_LIMITS_LOCKED(p, memlimit_active, memlimit_active_is_fatal);
2362
2363 /*
2364 * Initialize the inactive limit variants for this process.
2365 */
2366 SET_INACTIVE_LIMITS_LOCKED(p, memlimit_inactive, memlimit_inactive_is_fatal);
2367
2368 /*
2369 * Initialize the cached limits for target process.
2370 * When the target process is dirty tracked, it's typically
2371 * in a clean state. Non dirty tracked processes are
2372 * typically active (Foreground or above).
2373 * But just in case, we don't make assumptions...
2374 */
2375
2376 if (proc_jetsam_state_is_active_locked(p) == TRUE) {
2377 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
2378 use_active = TRUE;
2379 } else {
2380 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2381 use_active = FALSE;
2382 }
2383
2384 /*
2385 * Enforce the cached limit by writing to the ledger.
2386 */
2387 if (memorystatus_highwater_enabled) {
2388 /* apply now */
2389 task_set_phys_footprint_limit_internal(p->task, ((p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1), NULL, use_active, is_fatal);
2390
2391 MEMORYSTATUS_DEBUG(3, "memorystatus_update: init: limit on pid %d (%dMB %s) targeting priority(%d) dirty?=0x%x %s\n",
2392 p->p_pid, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
2393 (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), priority, p->p_memstat_dirty,
2394 (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
2395 }
2396 }
2397
2398 /*
2399 * We can't add to the aging bands buckets here.
2400 * But, we could be removing it from those buckets.
2401 * Check and take appropriate steps if so.
2402 */
2403
2404 if (isProcessInAgingBands(p)) {
2405
2406 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2407 memorystatus_update_priority_locked(p, JETSAM_PRIORITY_IDLE, FALSE, TRUE);
2408 } else {
2409 if (jetsam_aging_policy == kJetsamAgingPolicyLegacy && priority == JETSAM_PRIORITY_IDLE) {
2410 /*
2411 * Daemons with 'inactive' limits will go through the dirty tracking codepath.
2412 * This path deals with apps that may have 'inactive' limits e.g. WebContent processes.
2413 * If this is the legacy aging policy we explicitly need to apply those limits. If it
2414 * is any other aging policy, then we don't need to worry because all processes
2415 * will go through the aging bands and then the demotion thread will take care to
2416 * move them into the IDLE band and apply the required limits.
2417 */
2418 memorystatus_update_priority_locked(p, priority, head_insert, TRUE);
2419 }
2420 }
2421
2422 memorystatus_update_priority_locked(p, priority, head_insert, FALSE);
2423
2424 proc_list_unlock();
2425 ret = 0;
2426
2427 out:
2428 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_UPDATE) | DBG_FUNC_END, ret, 0, 0, 0, 0);
2429
2430 return ret;
2431 }
2432
2433 int
2434 memorystatus_remove(proc_t p, boolean_t locked)
2435 {
2436 int ret;
2437 memstat_bucket_t *bucket;
2438 boolean_t reschedule = FALSE;
2439
2440 MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p->p_pid);
2441
2442 if (!locked) {
2443 proc_list_lock();
2444 }
2445
2446 assert(!(p->p_memstat_state & P_MEMSTAT_INTERNAL));
2447
2448 bucket = &memstat_bucket[p->p_memstat_effectivepriority];
2449
2450 if (isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) {
2451
2452 assert(bucket->count == memorystatus_scheduled_idle_demotions_sysprocs);
2453 reschedule = TRUE;
2454
2455 } else if (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)) {
2456
2457 assert(bucket->count == memorystatus_scheduled_idle_demotions_apps);
2458 reschedule = TRUE;
2459 }
2460
2461 /*
2462 * Record idle delta
2463 */
2464
2465 if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
2466 uint64_t now = mach_absolute_time();
2467 if (now > p->p_memstat_idle_start) {
2468 p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
2469 }
2470 }
2471
2472 TAILQ_REMOVE(&bucket->list, p, p_memstat_list);
2473 bucket->count--;
2474
2475 memorystatus_list_count--;
2476
2477 /* If awaiting demotion to the idle band, clean up */
2478 if (reschedule) {
2479 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2480 memorystatus_reschedule_idle_demotion_locked();
2481 }
2482
2483 memorystatus_check_levels_locked();
2484
2485 #if CONFIG_FREEZE
2486 if (p->p_memstat_state & (P_MEMSTAT_FROZEN)) {
2487 memorystatus_frozen_count--;
2488 }
2489
2490 if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
2491 memorystatus_suspended_footprint_total -= p->p_memstat_suspendedfootprint;
2492 memorystatus_suspended_count--;
2493 }
2494 #endif
2495
2496 if (!locked) {
2497 proc_list_unlock();
2498 }
2499
2500 if (p) {
2501 ret = 0;
2502 } else {
2503 ret = ESRCH;
2504 }
2505
2506 return ret;
2507 }
2508
2509 /*
2510 * Validate dirty tracking flags with process state.
2511 *
2512 * Return:
2513 * 0 on success
2514 * non-0 on failure
2515 *
2516 * The proc_list_lock is held by the caller.
2517 */
2518
2519 static int
2520 memorystatus_validate_track_flags(struct proc *target_p, uint32_t pcontrol) {
2521 /* See that the process isn't marked for termination */
2522 if (target_p->p_memstat_dirty & P_DIRTY_TERMINATED) {
2523 return EBUSY;
2524 }
2525
2526 /* Idle exit requires that process be tracked */
2527 if ((pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) &&
2528 !(pcontrol & PROC_DIRTY_TRACK)) {
2529 return EINVAL;
2530 }
2531
2532 /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
2533 if ((pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) &&
2534 !(pcontrol & PROC_DIRTY_TRACK)) {
2535 return EINVAL;
2536 }
2537
2538 /* Deferral is only relevant if idle exit is specified */
2539 if ((pcontrol & PROC_DIRTY_DEFER) &&
2540 !(pcontrol & PROC_DIRTY_ALLOWS_IDLE_EXIT)) {
2541 return EINVAL;
2542 }
2543
2544 return(0);
2545 }
2546
2547 static void
2548 memorystatus_update_idle_priority_locked(proc_t p) {
2549 int32_t priority;
2550
2551 MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p->p_pid, p->p_memstat_dirty);
2552
2553 assert(isSysProc(p));
2554
2555 if ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED|P_DIRTY_IS_DIRTY)) == P_DIRTY_IDLE_EXIT_ENABLED) {
2556
2557 priority = (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) ? system_procs_aging_band : JETSAM_PRIORITY_IDLE;
2558 } else {
2559 priority = p->p_memstat_requestedpriority;
2560 }
2561
2562 if (priority != p->p_memstat_effectivepriority) {
2563
2564 if ((jetsam_aging_policy == kJetsamAgingPolicyLegacy) &&
2565 (priority == JETSAM_PRIORITY_IDLE)) {
2566
2567 /*
2568 * This process is on its way into the IDLE band. The system is
2569 * using 'legacy' jetsam aging policy. That means, this process
2570 * has already used up its idle-deferral aging time that is given
2571 * once per its lifetime. So we need to set the INACTIVE limits
2572 * explicitly because it won't be going through the demotion paths
2573 * that take care to apply the limits appropriately.
2574 */
2575 memorystatus_update_priority_locked(p, priority, false, true);
2576
2577 } else {
2578 memorystatus_update_priority_locked(p, priority, false, false);
2579 }
2580 }
2581 }
2582
2583 /*
2584 * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
2585 * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
2586 * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
2587 * priority idle band when clean (and killed earlier, protecting higher priority procesess).
2588 *
2589 * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
2590 * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
2591 * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
2592 * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
2593 * band. The deferral can be cleared early by clearing the appropriate flag.
2594 *
2595 * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
2596 * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
2597 * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
2598 */
2599
2600 int
2601 memorystatus_dirty_track(proc_t p, uint32_t pcontrol) {
2602 unsigned int old_dirty;
2603 boolean_t reschedule = FALSE;
2604 boolean_t already_deferred = FALSE;
2605 boolean_t defer_now = FALSE;
2606 int ret = 0;
2607
2608 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_TRACK),
2609 p->p_pid, p->p_memstat_dirty, pcontrol, 0, 0);
2610
2611 proc_list_lock();
2612
2613 if ((p->p_listflag & P_LIST_EXITED) != 0) {
2614 /*
2615 * Process is on its way out.
2616 */
2617 ret = EBUSY;
2618 goto exit;
2619 }
2620
2621 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
2622 ret = EPERM;
2623 goto exit;
2624 }
2625
2626 if ((ret = memorystatus_validate_track_flags(p, pcontrol)) != 0) {
2627 /* error */
2628 goto exit;
2629 }
2630
2631 old_dirty = p->p_memstat_dirty;
2632
2633 /* These bits are cumulative, as per <rdar://problem/11159924> */
2634 if (pcontrol & PROC_DIRTY_TRACK) {
2635 p->p_memstat_dirty |= P_DIRTY_TRACK;
2636 }
2637
2638 if (pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) {
2639 p->p_memstat_dirty |= P_DIRTY_ALLOW_IDLE_EXIT;
2640 }
2641
2642 if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
2643 p->p_memstat_dirty |= P_DIRTY_LAUNCH_IN_PROGRESS;
2644 }
2645
2646 if (old_dirty & P_DIRTY_AGING_IN_PROGRESS) {
2647 already_deferred = TRUE;
2648 }
2649
2650
2651 /* This can be set and cleared exactly once. */
2652 if (pcontrol & PROC_DIRTY_DEFER) {
2653
2654 if ( !(old_dirty & P_DIRTY_DEFER)) {
2655 p->p_memstat_dirty |= P_DIRTY_DEFER;
2656 }
2657
2658 defer_now = TRUE;
2659 }
2660
2661 MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
2662 ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) ? "Y" : "N",
2663 defer_now ? "Y" : "N",
2664 p->p_memstat_dirty & P_DIRTY ? "Y" : "N",
2665 p->p_pid);
2666
2667 /* Kick off or invalidate the idle exit deferment if there's a state transition. */
2668 if (!(p->p_memstat_dirty & P_DIRTY_IS_DIRTY)) {
2669 if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
2670
2671 if (defer_now && !already_deferred) {
2672
2673 /*
2674 * Request to defer a clean process that's idle-exit enabled
2675 * and not already in the jetsam deferred band. Most likely a
2676 * new launch.
2677 */
2678 memorystatus_schedule_idle_demotion_locked(p, TRUE);
2679 reschedule = TRUE;
2680
2681 } else if (!defer_now) {
2682
2683 /*
2684 * The process isn't asking for the 'aging' facility.
2685 * Could be that it is:
2686 */
2687
2688 if (already_deferred) {
2689 /*
2690 * already in the aging bands. Traditionally,
2691 * some processes have tried to use this to
2692 * opt out of the 'aging' facility.
2693 */
2694
2695 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2696 } else {
2697 /*
2698 * agnostic to the 'aging' facility. In that case,
2699 * we'll go ahead and opt it in because this is likely
2700 * a new launch (clean process, dirty tracking enabled)
2701 */
2702
2703 memorystatus_schedule_idle_demotion_locked(p, TRUE);
2704 }
2705
2706 reschedule = TRUE;
2707 }
2708 }
2709 } else {
2710
2711 /*
2712 * We are trying to operate on a dirty process. Dirty processes have to
2713 * be removed from the deferred band. The question is do we reset the
2714 * deferred state or not?
2715 *
2716 * This could be a legal request like:
2717 * - this process had opted into the 'aging' band
2718 * - but it's now dirty and requests to opt out.
2719 * In this case, we remove the process from the band and reset its
2720 * state too. It'll opt back in properly when needed.
2721 *
2722 * OR, this request could be a user-space bug. E.g.:
2723 * - this process had opted into the 'aging' band when clean
2724 * - and, then issues another request to again put it into the band except
2725 * this time the process is dirty.
2726 * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
2727 * the deferred band with its state intact. So our request below is no-op.
2728 * But we do it here anyways for coverage.
2729 *
2730 * memorystatus_update_idle_priority_locked()
2731 * single-mindedly treats a dirty process as "cannot be in the aging band".
2732 */
2733
2734 if (!defer_now && already_deferred) {
2735 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2736 reschedule = TRUE;
2737 } else {
2738
2739 boolean_t reset_state = (jetsam_aging_policy != kJetsamAgingPolicyLegacy) ? TRUE : FALSE;
2740
2741 memorystatus_invalidate_idle_demotion_locked(p, reset_state);
2742 reschedule = TRUE;
2743 }
2744 }
2745
2746 memorystatus_update_idle_priority_locked(p);
2747
2748 if (reschedule) {
2749 memorystatus_reschedule_idle_demotion_locked();
2750 }
2751
2752 ret = 0;
2753
2754 exit:
2755 proc_list_unlock();
2756
2757 return ret;
2758 }
2759
2760 int
2761 memorystatus_dirty_set(proc_t p, boolean_t self, uint32_t pcontrol) {
2762 int ret;
2763 boolean_t kill = false;
2764 boolean_t reschedule = FALSE;
2765 boolean_t was_dirty = FALSE;
2766 boolean_t now_dirty = FALSE;
2767
2768 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self, p->p_pid, pcontrol, p->p_memstat_dirty);
2769 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_SET), p->p_pid, self, pcontrol, 0, 0);
2770
2771 proc_list_lock();
2772
2773 if ((p->p_listflag & P_LIST_EXITED) != 0) {
2774 /*
2775 * Process is on its way out.
2776 */
2777 ret = EBUSY;
2778 goto exit;
2779 }
2780
2781 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
2782 ret = EPERM;
2783 goto exit;
2784 }
2785
2786 if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY)
2787 was_dirty = TRUE;
2788
2789 if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
2790 /* Dirty tracking not enabled */
2791 ret = EINVAL;
2792 } else if (pcontrol && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
2793 /*
2794 * Process is set to be terminated and we're attempting to mark it dirty.
2795 * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
2796 */
2797 ret = EBUSY;
2798 } else {
2799 int flag = (self == TRUE) ? P_DIRTY : P_DIRTY_SHUTDOWN;
2800 if (pcontrol && !(p->p_memstat_dirty & flag)) {
2801 /* Mark the process as having been dirtied at some point */
2802 p->p_memstat_dirty |= (flag | P_DIRTY_MARKED);
2803 memorystatus_dirty_count++;
2804 ret = 0;
2805 } else if ((pcontrol == 0) && (p->p_memstat_dirty & flag)) {
2806 if ((flag == P_DIRTY_SHUTDOWN) && (!(p->p_memstat_dirty & P_DIRTY))) {
2807 /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
2808 p->p_memstat_dirty |= P_DIRTY_TERMINATED;
2809 kill = true;
2810 } else if ((flag == P_DIRTY) && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
2811 /* Kill previously terminated processes if set clean */
2812 kill = true;
2813 }
2814 p->p_memstat_dirty &= ~flag;
2815 memorystatus_dirty_count--;
2816 ret = 0;
2817 } else {
2818 /* Already set */
2819 ret = EALREADY;
2820 }
2821 }
2822
2823 if (ret != 0) {
2824 goto exit;
2825 }
2826
2827 if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY)
2828 now_dirty = TRUE;
2829
2830 if ((was_dirty == TRUE && now_dirty == FALSE) ||
2831 (was_dirty == FALSE && now_dirty == TRUE)) {
2832
2833 /* Manage idle exit deferral, if applied */
2834 if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
2835
2836 /*
2837 * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
2838 * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
2839 *
2840 * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
2841 * in that band on it's way to IDLE.
2842 */
2843
2844 if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
2845 /*
2846 * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
2847 *
2848 * The process will move from its aging band to its higher requested
2849 * jetsam band.
2850 */
2851 boolean_t reset_state = (jetsam_aging_policy != kJetsamAgingPolicyLegacy) ? TRUE : FALSE;
2852
2853 memorystatus_invalidate_idle_demotion_locked(p, reset_state);
2854 reschedule = TRUE;
2855 } else {
2856
2857 /*
2858 * Process is back from "dirty" to "clean".
2859 */
2860
2861 if (jetsam_aging_policy == kJetsamAgingPolicyLegacy) {
2862 if (mach_absolute_time() >= p->p_memstat_idledeadline) {
2863 /*
2864 * The process' deadline has expired. It currently
2865 * does not reside in any of the aging buckets.
2866 *
2867 * It's on its way to the JETSAM_PRIORITY_IDLE
2868 * bucket via memorystatus_update_idle_priority_locked()
2869 * below.
2870
2871 * So all we need to do is reset all the state on the
2872 * process that's related to the aging bucket i.e.
2873 * the AGING_IN_PROGRESS flag and the timer deadline.
2874 */
2875
2876 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
2877 reschedule = TRUE;
2878 } else {
2879 /*
2880 * It still has some protection window left and so
2881 * we just re-arm the timer without modifying any
2882 * state on the process iff it still wants into that band.
2883 */
2884
2885 if (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) {
2886 memorystatus_schedule_idle_demotion_locked(p, FALSE);
2887 reschedule = TRUE;
2888 }
2889 }
2890 } else {
2891
2892 memorystatus_schedule_idle_demotion_locked(p, TRUE);
2893 reschedule = TRUE;
2894 }
2895 }
2896 }
2897
2898 memorystatus_update_idle_priority_locked(p);
2899
2900 if (memorystatus_highwater_enabled) {
2901 boolean_t ledger_update_needed = TRUE;
2902 boolean_t use_active;
2903 boolean_t is_fatal;
2904 /*
2905 * We are in this path because this process transitioned between
2906 * dirty <--> clean state. Update the cached memory limits.
2907 */
2908
2909 if (proc_jetsam_state_is_active_locked(p) == TRUE) {
2910 /*
2911 * process is dirty
2912 */
2913 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
2914 use_active = TRUE;
2915 ledger_update_needed = TRUE;
2916 } else {
2917 /*
2918 * process is clean...but if it has opted into pressured-exit
2919 * we don't apply the INACTIVE limit till the process has aged
2920 * out and is entering the IDLE band.
2921 * See memorystatus_update_priority_locked() for that.
2922 */
2923
2924 if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
2925 ledger_update_needed = FALSE;
2926 } else {
2927 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
2928 use_active = FALSE;
2929 ledger_update_needed = TRUE;
2930 }
2931 }
2932
2933 /*
2934 * Enforce the new limits by writing to the ledger.
2935 *
2936 * This is a hot path and holding the proc_list_lock while writing to the ledgers,
2937 * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
2938 * We aren't traversing the jetsam bucket list here, so we should be safe.
2939 * See rdar://21394491.
2940 */
2941
2942 if (ledger_update_needed && proc_ref_locked(p) == p) {
2943 int ledger_limit;
2944 if (p->p_memstat_memlimit > 0) {
2945 ledger_limit = p->p_memstat_memlimit;
2946 } else {
2947 ledger_limit = -1;
2948 }
2949 proc_list_unlock();
2950 task_set_phys_footprint_limit_internal(p->task, ledger_limit, NULL, use_active, is_fatal);
2951 proc_list_lock();
2952 proc_rele_locked(p);
2953
2954 MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
2955 p->p_pid, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
2956 (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, p->p_memstat_dirty,
2957 (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
2958 }
2959
2960 }
2961
2962 /* If the deferral state changed, reschedule the demotion timer */
2963 if (reschedule) {
2964 memorystatus_reschedule_idle_demotion_locked();
2965 }
2966 }
2967
2968 if (kill) {
2969 if (proc_ref_locked(p) == p) {
2970 proc_list_unlock();
2971 psignal(p, SIGKILL);
2972 proc_list_lock();
2973 proc_rele_locked(p);
2974 }
2975 }
2976
2977 exit:
2978 proc_list_unlock();
2979
2980 return ret;
2981 }
2982
2983 int
2984 memorystatus_dirty_clear(proc_t p, uint32_t pcontrol) {
2985
2986 int ret = 0;
2987
2988 MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p->p_pid, pcontrol, p->p_memstat_dirty);
2989
2990 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_CLEAR), p->p_pid, pcontrol, 0, 0, 0);
2991
2992 proc_list_lock();
2993
2994 if ((p->p_listflag & P_LIST_EXITED) != 0) {
2995 /*
2996 * Process is on its way out.
2997 */
2998 ret = EBUSY;
2999 goto exit;
3000 }
3001
3002 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
3003 ret = EPERM;
3004 goto exit;
3005 }
3006
3007 if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
3008 /* Dirty tracking not enabled */
3009 ret = EINVAL;
3010 goto exit;
3011 }
3012
3013 if (!pcontrol || (pcontrol & (PROC_DIRTY_LAUNCH_IN_PROGRESS | PROC_DIRTY_DEFER)) == 0) {
3014 ret = EINVAL;
3015 goto exit;
3016 }
3017
3018 if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
3019 p->p_memstat_dirty &= ~P_DIRTY_LAUNCH_IN_PROGRESS;
3020 }
3021
3022 /* This can be set and cleared exactly once. */
3023 if (pcontrol & PROC_DIRTY_DEFER) {
3024
3025 if (p->p_memstat_dirty & P_DIRTY_DEFER) {
3026
3027 p->p_memstat_dirty &= ~P_DIRTY_DEFER;
3028
3029 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
3030 memorystatus_update_idle_priority_locked(p);
3031 memorystatus_reschedule_idle_demotion_locked();
3032 }
3033 }
3034
3035 ret = 0;
3036 exit:
3037 proc_list_unlock();
3038
3039 return ret;
3040 }
3041
3042 int
3043 memorystatus_dirty_get(proc_t p) {
3044 int ret = 0;
3045
3046 proc_list_lock();
3047
3048 if (p->p_memstat_dirty & P_DIRTY_TRACK) {
3049 ret |= PROC_DIRTY_TRACKED;
3050 if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
3051 ret |= PROC_DIRTY_ALLOWS_IDLE_EXIT;
3052 }
3053 if (p->p_memstat_dirty & P_DIRTY) {
3054 ret |= PROC_DIRTY_IS_DIRTY;
3055 }
3056 if (p->p_memstat_dirty & P_DIRTY_LAUNCH_IN_PROGRESS) {
3057 ret |= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS;
3058 }
3059 }
3060
3061 proc_list_unlock();
3062
3063 return ret;
3064 }
3065
3066 int
3067 memorystatus_on_terminate(proc_t p) {
3068 int sig;
3069
3070 proc_list_lock();
3071
3072 p->p_memstat_dirty |= P_DIRTY_TERMINATED;
3073
3074 if ((p->p_memstat_dirty & (P_DIRTY_TRACK|P_DIRTY_IS_DIRTY)) == P_DIRTY_TRACK) {
3075 /* Clean; mark as terminated and issue SIGKILL */
3076 sig = SIGKILL;
3077 } else {
3078 /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
3079 sig = SIGTERM;
3080 }
3081
3082 proc_list_unlock();
3083
3084 return sig;
3085 }
3086
3087 void
3088 memorystatus_on_suspend(proc_t p)
3089 {
3090 #if CONFIG_FREEZE
3091 uint32_t pages;
3092 memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL, NULL);
3093 #endif
3094 proc_list_lock();
3095 #if CONFIG_FREEZE
3096 p->p_memstat_suspendedfootprint = pages;
3097 memorystatus_suspended_footprint_total += pages;
3098 memorystatus_suspended_count++;
3099 #endif
3100 p->p_memstat_state |= P_MEMSTAT_SUSPENDED;
3101 proc_list_unlock();
3102 }
3103
3104 void
3105 memorystatus_on_resume(proc_t p)
3106 {
3107 #if CONFIG_FREEZE
3108 boolean_t frozen;
3109 pid_t pid;
3110 #endif
3111
3112 proc_list_lock();
3113
3114 #if CONFIG_FREEZE
3115 frozen = (p->p_memstat_state & P_MEMSTAT_FROZEN);
3116 if (frozen) {
3117 memorystatus_frozen_count--;
3118 p->p_memstat_state |= P_MEMSTAT_PRIOR_THAW;
3119 }
3120
3121 memorystatus_suspended_footprint_total -= p->p_memstat_suspendedfootprint;
3122 memorystatus_suspended_count--;
3123
3124 pid = p->p_pid;
3125 #endif
3126
3127 p->p_memstat_state &= ~(P_MEMSTAT_SUSPENDED | P_MEMSTAT_FROZEN);
3128
3129 proc_list_unlock();
3130
3131 #if CONFIG_FREEZE
3132 if (frozen) {
3133 memorystatus_freeze_entry_t data = { pid, FALSE, 0 };
3134 memorystatus_send_note(kMemorystatusFreezeNote, &data, sizeof(data));
3135 }
3136 #endif
3137 }
3138
3139 void
3140 memorystatus_on_inactivity(proc_t p)
3141 {
3142 #pragma unused(p)
3143 #if CONFIG_FREEZE
3144 /* Wake the freeze thread */
3145 thread_wakeup((event_t)&memorystatus_freeze_wakeup);
3146 #endif
3147 }
3148
3149 /*
3150 * The proc_list_lock is held by the caller.
3151 */
3152 static uint32_t
3153 memorystatus_build_state(proc_t p) {
3154 uint32_t snapshot_state = 0;
3155
3156 /* General */
3157 if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
3158 snapshot_state |= kMemorystatusSuspended;
3159 }
3160 if (p->p_memstat_state & P_MEMSTAT_FROZEN) {
3161 snapshot_state |= kMemorystatusFrozen;
3162 }
3163 if (p->p_memstat_state & P_MEMSTAT_PRIOR_THAW) {
3164 snapshot_state |= kMemorystatusWasThawed;
3165 }
3166
3167 /* Tracking */
3168 if (p->p_memstat_dirty & P_DIRTY_TRACK) {
3169 snapshot_state |= kMemorystatusTracked;
3170 }
3171 if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
3172 snapshot_state |= kMemorystatusSupportsIdleExit;
3173 }
3174 if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3175 snapshot_state |= kMemorystatusDirty;
3176 }
3177
3178 return snapshot_state;
3179 }
3180
3181 #if !CONFIG_JETSAM
3182
3183 static boolean_t
3184 kill_idle_exit_proc(void)
3185 {
3186 proc_t p, victim_p = PROC_NULL;
3187 uint64_t current_time;
3188 boolean_t killed = FALSE;
3189 unsigned int i = 0;
3190 os_reason_t jetsam_reason = OS_REASON_NULL;
3191
3192 /* Pick next idle exit victim. */
3193 current_time = mach_absolute_time();
3194
3195 jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_IDLE_EXIT);
3196 if (jetsam_reason == OS_REASON_NULL) {
3197 printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
3198 }
3199
3200 proc_list_lock();
3201
3202 p = memorystatus_get_first_proc_locked(&i, FALSE);
3203 while (p) {
3204 /* No need to look beyond the idle band */
3205 if (p->p_memstat_effectivepriority != JETSAM_PRIORITY_IDLE) {
3206 break;
3207 }
3208
3209 if ((p->p_memstat_dirty & (P_DIRTY_ALLOW_IDLE_EXIT|P_DIRTY_IS_DIRTY|P_DIRTY_TERMINATED)) == (P_DIRTY_ALLOW_IDLE_EXIT)) {
3210 if (current_time >= p->p_memstat_idledeadline) {
3211 p->p_memstat_dirty |= P_DIRTY_TERMINATED;
3212 victim_p = proc_ref_locked(p);
3213 break;
3214 }
3215 }
3216
3217 p = memorystatus_get_next_proc_locked(&i, p, FALSE);
3218 }
3219
3220 proc_list_unlock();
3221
3222 if (victim_p) {
3223 printf("memorystatus_thread: idle exiting pid %d [%s]\n", victim_p->p_pid, (*victim_p->p_name ? victim_p->p_name : "(unknown)"));
3224 killed = memorystatus_do_kill(victim_p, kMemorystatusKilledIdleExit, jetsam_reason);
3225 proc_rele(victim_p);
3226 } else {
3227 os_reason_free(jetsam_reason);
3228 }
3229
3230 return killed;
3231 }
3232 #endif
3233
3234 #if CONFIG_JETSAM
3235 static void
3236 memorystatus_thread_wake(void) {
3237 thread_wakeup((event_t)&memorystatus_wakeup);
3238 }
3239 #endif /* CONFIG_JETSAM */
3240
3241 extern void vm_pressure_response(void);
3242
3243 static int
3244 memorystatus_thread_block(uint32_t interval_ms, thread_continue_t continuation)
3245 {
3246 if (interval_ms) {
3247 assert_wait_timeout(&memorystatus_wakeup, THREAD_UNINT, interval_ms, 1000 * NSEC_PER_USEC);
3248 } else {
3249 assert_wait(&memorystatus_wakeup, THREAD_UNINT);
3250 }
3251
3252 return thread_block(continuation);
3253 }
3254
3255 static void
3256 memorystatus_thread(void *param __unused, wait_result_t wr __unused)
3257 {
3258 static boolean_t is_vm_privileged = FALSE;
3259
3260 #if CONFIG_JETSAM
3261 boolean_t post_snapshot = FALSE;
3262 uint32_t errors = 0;
3263 uint32_t hwm_kill = 0;
3264 boolean_t sort_flag = TRUE;
3265 boolean_t corpse_list_purged = FALSE;
3266
3267 /* Jetsam Loop Detection - locals */
3268 memstat_bucket_t *bucket;
3269 int jld_bucket_count = 0;
3270 struct timeval jld_now_tstamp = {0,0};
3271 uint64_t jld_now_msecs = 0;
3272 int elevated_bucket_count = 0;
3273
3274 /* Jetsam Loop Detection - statics */
3275 static uint64_t jld_timestamp_msecs = 0;
3276 static int jld_idle_kill_candidates = 0; /* Number of available processes in band 0,1 at start */
3277 static int jld_idle_kills = 0; /* Number of procs killed during eval period */
3278 static int jld_eval_aggressive_count = 0; /* Bumps the max priority in aggressive loop */
3279 static int32_t jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
3280 #endif
3281
3282 if (is_vm_privileged == FALSE) {
3283 /*
3284 * It's the first time the thread has run, so just mark the thread as privileged and block.
3285 * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
3286 */
3287 thread_wire(host_priv_self(), current_thread(), TRUE);
3288 is_vm_privileged = TRUE;
3289
3290 if (vm_restricted_to_single_processor == TRUE)
3291 thread_vm_bind_group_add();
3292
3293 memorystatus_thread_block(0, memorystatus_thread);
3294 }
3295
3296 #if CONFIG_JETSAM
3297
3298 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_START,
3299 memorystatus_available_pages, memorystatus_jld_enabled, memorystatus_jld_eval_period_msecs, memorystatus_jld_eval_aggressive_count,0);
3300
3301 /*
3302 * Jetsam aware version.
3303 *
3304 * The VM pressure notification thread is working it's way through clients in parallel.
3305 *
3306 * So, while the pressure notification thread is targeting processes in order of
3307 * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
3308 * any processes that have exceeded their highwater mark.
3309 *
3310 * If we run out of HWM processes and our available pages drops below the critical threshold, then,
3311 * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
3312 */
3313 while (is_thrashing(kill_under_pressure_cause) ||
3314 memorystatus_available_pages <= memorystatus_available_pages_pressure) {
3315 boolean_t killed;
3316 int32_t priority;
3317 uint32_t cause;
3318 uint64_t jetsam_reason_code = JETSAM_REASON_INVALID;
3319 os_reason_t jetsam_reason = OS_REASON_NULL;
3320
3321 cause = kill_under_pressure_cause;
3322 switch (cause) {
3323 case kMemorystatusKilledFCThrashing:
3324 jetsam_reason_code = JETSAM_REASON_MEMORY_FCTHRASHING;
3325 break;
3326 case kMemorystatusKilledVMThrashing:
3327 jetsam_reason_code = JETSAM_REASON_MEMORY_VMTHRASHING;
3328 break;
3329 case kMemorystatusKilledVMPageShortage:
3330 /* falls through */
3331 default:
3332 jetsam_reason_code = JETSAM_REASON_MEMORY_VMPAGESHORTAGE;
3333 cause = kMemorystatusKilledVMPageShortage;
3334 break;
3335 }
3336
3337 /* Highwater */
3338 killed = memorystatus_kill_hiwat_proc(&errors);
3339 if (killed) {
3340 hwm_kill++;
3341 post_snapshot = TRUE;
3342 goto done;
3343 } else {
3344 memorystatus_hwm_candidates = FALSE;
3345 }
3346
3347 /* No highwater processes to kill. Continue or stop for now? */
3348 if (!is_thrashing(kill_under_pressure_cause) &&
3349 (memorystatus_available_pages > memorystatus_available_pages_critical)) {
3350 /*
3351 * We are _not_ out of pressure but we are above the critical threshold and there's:
3352 * - no compressor thrashing
3353 * - no more HWM processes left.
3354 * For now, don't kill any other processes.
3355 */
3356
3357 if (hwm_kill == 0) {
3358 memorystatus_thread_wasted_wakeup++;
3359 }
3360
3361 break;
3362 }
3363
3364 jetsam_reason = os_reason_create(OS_REASON_JETSAM, jetsam_reason_code);
3365 if (jetsam_reason == OS_REASON_NULL) {
3366 printf("memorystatus_thread: failed to allocate jetsam reason\n");
3367 }
3368
3369 if (memorystatus_jld_enabled == TRUE) {
3370
3371 /*
3372 * Jetsam Loop Detection: attempt to detect
3373 * rapid daemon relaunches in the lower bands.
3374 */
3375
3376 microuptime(&jld_now_tstamp);
3377
3378 /*
3379 * Ignore usecs in this calculation.
3380 * msecs granularity is close enough.
3381 */
3382 jld_now_msecs = (jld_now_tstamp.tv_sec * 1000);
3383
3384 proc_list_lock();
3385 switch (jetsam_aging_policy) {
3386 case kJetsamAgingPolicyLegacy:
3387 bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
3388 jld_bucket_count = bucket->count;
3389 bucket = &memstat_bucket[JETSAM_PRIORITY_AGING_BAND1];
3390 jld_bucket_count += bucket->count;
3391 break;
3392 case kJetsamAgingPolicySysProcsReclaimedFirst:
3393 case kJetsamAgingPolicyAppsReclaimedFirst:
3394 bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
3395 jld_bucket_count = bucket->count;
3396 bucket = &memstat_bucket[system_procs_aging_band];
3397 jld_bucket_count += bucket->count;
3398 bucket = &memstat_bucket[applications_aging_band];
3399 jld_bucket_count += bucket->count;
3400 break;
3401 case kJetsamAgingPolicyNone:
3402 default:
3403 bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
3404 jld_bucket_count = bucket->count;
3405 break;
3406 }
3407
3408 bucket = &memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE];
3409 elevated_bucket_count = bucket->count;
3410
3411 proc_list_unlock();
3412
3413 /*
3414 * memorystatus_jld_eval_period_msecs is a tunable
3415 * memorystatus_jld_eval_aggressive_count is a tunable
3416 * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
3417 */
3418 if ( (jld_bucket_count == 0) ||
3419 (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
3420
3421 /*
3422 * Refresh evaluation parameters
3423 */
3424 jld_timestamp_msecs = jld_now_msecs;
3425 jld_idle_kill_candidates = jld_bucket_count;
3426 jld_idle_kills = 0;
3427 jld_eval_aggressive_count = 0;
3428 jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
3429 }
3430
3431 if (jld_idle_kills > jld_idle_kill_candidates) {
3432 jld_eval_aggressive_count++;
3433
3434 #if DEVELOPMENT || DEBUG
3435 printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
3436 jld_eval_aggressive_count,
3437 jld_timestamp_msecs,
3438 jld_now_msecs);
3439 printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
3440 jld_eval_aggressive_count,
3441 jld_idle_kill_candidates,
3442 jld_idle_kills);
3443 #endif /* DEVELOPMENT || DEBUG */
3444
3445 if ((jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) &&
3446 (total_corpses_count > 0) && (corpse_list_purged == FALSE)) {
3447 /*
3448 * If we reach this aggressive cycle, corpses might be causing memory pressure.
3449 * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
3450 * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
3451 */
3452 task_purge_all_corpses();
3453 corpse_list_purged = TRUE;
3454 }
3455 else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
3456 /*
3457 * Bump up the jetsam priority limit (eg: the bucket index)
3458 * Enforce bucket index sanity.
3459 */
3460 if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
3461 (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
3462 /*
3463 * Do nothing. Stick with the default level.
3464 */
3465 } else {
3466 jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
3467 }
3468 }
3469
3470 /* Visit elevated processes first */
3471 while (elevated_bucket_count) {
3472
3473 elevated_bucket_count--;
3474
3475 /*
3476 * memorystatus_kill_elevated_process() drops a reference,
3477 * so take another one so we can continue to use this exit reason
3478 * even after it returns.
3479 */
3480
3481 os_reason_ref(jetsam_reason);
3482 killed = memorystatus_kill_elevated_process(
3483 kMemorystatusKilledVMThrashing,
3484 jetsam_reason,
3485 jld_eval_aggressive_count,
3486 &errors);
3487
3488 if (killed) {
3489 post_snapshot = TRUE;
3490 if (memorystatus_available_pages <= memorystatus_available_pages_pressure) {
3491 /*
3492 * Still under pressure.
3493 * Find another pinned processes.
3494 */
3495 continue;
3496 } else {
3497 goto done;
3498 }
3499 } else {
3500 /*
3501 * No pinned processes left to kill.
3502 * Abandon elevated band.
3503 */
3504 break;
3505 }
3506 }
3507
3508 /*
3509 * memorystatus_kill_top_process_aggressive() drops a reference,
3510 * so take another one so we can continue to use this exit reason
3511 * even after it returns
3512 */
3513 os_reason_ref(jetsam_reason);
3514 killed = memorystatus_kill_top_process_aggressive(
3515 TRUE,
3516 kMemorystatusKilledVMThrashing,
3517 jetsam_reason,
3518 jld_eval_aggressive_count,
3519 jld_priority_band_max,
3520 &errors);
3521
3522 if (killed) {
3523 /* Always generate logs after aggressive kill */
3524 post_snapshot = TRUE;
3525 jld_idle_kills = 0;
3526 goto done;
3527 }
3528 }
3529 }
3530
3531 /*
3532 * memorystatus_kill_top_process() drops a reference,
3533 * so take another one so we can continue to use this exit reason
3534 * even after it returns
3535 */
3536 os_reason_ref(jetsam_reason);
3537
3538 /* LRU */
3539 killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors);
3540 sort_flag = FALSE;
3541
3542 if (killed) {
3543 /*
3544 * Don't generate logs for steady-state idle-exit kills,
3545 * unless it is overridden for debug or by the device
3546 * tree.
3547 */
3548 if ((priority != JETSAM_PRIORITY_IDLE) || memorystatus_idle_snapshot) {
3549 post_snapshot = TRUE;
3550 }
3551
3552 /* Jetsam Loop Detection */
3553 if (memorystatus_jld_enabled == TRUE) {
3554 if ((priority == JETSAM_PRIORITY_IDLE) || (priority == system_procs_aging_band) || (priority == applications_aging_band)) {
3555 jld_idle_kills++;
3556 } else {
3557 /*
3558 * We've reached into bands beyond idle deferred.
3559 * We make no attempt to monitor them
3560 */
3561 }
3562 }
3563
3564 if ((priority >= JETSAM_PRIORITY_UI_SUPPORT) && (total_corpses_count > 0) && (corpse_list_purged == FALSE)) {
3565 /*
3566 * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
3567 * then we attempt to relieve pressure by purging corpse memory.
3568 */
3569 task_purge_all_corpses();
3570 corpse_list_purged = TRUE;
3571 }
3572 goto done;
3573 }
3574
3575 if (memorystatus_available_pages <= memorystatus_available_pages_critical) {
3576 /*
3577 * Still under pressure and unable to kill a process - purge corpse memory
3578 */
3579 if (total_corpses_count > 0) {
3580 task_purge_all_corpses();
3581 corpse_list_purged = TRUE;
3582 }
3583
3584 if (memorystatus_available_pages <= memorystatus_available_pages_critical) {
3585 /*
3586 * Still under pressure and unable to kill a process - panic
3587 */
3588 panic("memorystatus_jetsam_thread: no victim! available pages:%d\n", memorystatus_available_pages);
3589 }
3590 }
3591
3592 done:
3593
3594 /*
3595 * We do not want to over-kill when thrashing has been detected.
3596 * To avoid that, we reset the flag here and notify the
3597 * compressor.
3598 */
3599 if (is_thrashing(kill_under_pressure_cause)) {
3600 kill_under_pressure_cause = 0;
3601 vm_thrashing_jetsam_done();
3602 }
3603
3604 os_reason_free(jetsam_reason);
3605 }
3606
3607 kill_under_pressure_cause = 0;
3608
3609 if (errors) {
3610 memorystatus_clear_errors();
3611 }
3612
3613 #if VM_PRESSURE_EVENTS
3614 /*
3615 * LD: We used to target the foreground process first and foremost here.
3616 * Now, we target all processes, starting from the non-suspended, background
3617 * processes first. We will target foreground too.
3618 *
3619 * memorystatus_update_vm_pressure(TRUE);
3620 */
3621 //vm_pressure_response();
3622 #endif
3623
3624 if (post_snapshot) {
3625 proc_list_lock();
3626 size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
3627 sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count);
3628 uint64_t timestamp_now = mach_absolute_time();
3629 memorystatus_jetsam_snapshot->notification_time = timestamp_now;
3630 memorystatus_jetsam_snapshot->js_gencount++;
3631 if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
3632 timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
3633 proc_list_unlock();
3634 int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
3635 if (!ret) {
3636 proc_list_lock();
3637 memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
3638 proc_list_unlock();
3639 }
3640 } else {
3641 proc_list_unlock();
3642 }
3643 }
3644
3645 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_END,
3646 memorystatus_available_pages, 0, 0, 0, 0);
3647
3648 #else /* CONFIG_JETSAM */
3649
3650 /*
3651 * Jetsam not enabled
3652 */
3653
3654 #endif /* CONFIG_JETSAM */
3655
3656 memorystatus_thread_block(0, memorystatus_thread);
3657 }
3658
3659 #if !CONFIG_JETSAM
3660 /*
3661 * Returns TRUE:
3662 * when an idle-exitable proc was killed
3663 * Returns FALSE:
3664 * when there are no more idle-exitable procs found
3665 * when the attempt to kill an idle-exitable proc failed
3666 */
3667 boolean_t memorystatus_idle_exit_from_VM(void) {
3668 return(kill_idle_exit_proc());
3669 }
3670 #endif /* !CONFIG_JETSAM */
3671
3672 /*
3673 * Callback invoked when allowable physical memory footprint exceeded
3674 * (dirty pages + IOKit mappings)
3675 *
3676 * This is invoked for both advisory, non-fatal per-task high watermarks,
3677 * as well as the fatal task memory limits.
3678 */
3679 void
3680 memorystatus_on_ledger_footprint_exceeded(boolean_t warning, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
3681 {
3682 os_reason_t jetsam_reason = OS_REASON_NULL;
3683
3684 proc_t p = current_proc();
3685
3686 #if VM_PRESSURE_EVENTS
3687 if (warning == TRUE) {
3688 /*
3689 * This is a warning path which implies that the current process is close, but has
3690 * not yet exceeded its per-process memory limit.
3691 */
3692 if (memorystatus_warn_process(p->p_pid, memlimit_is_active, memlimit_is_fatal, FALSE /* not exceeded */) != TRUE) {
3693 /* Print warning, since it's possible that task has not registered for pressure notifications */
3694 printf("task_exceeded_footprint: failed to warn the current task (%d exiting, or no handler registered?).\n", p->p_pid);
3695 }
3696 return;
3697 }
3698 #endif /* VM_PRESSURE_EVENTS */
3699
3700 if (memlimit_is_fatal) {
3701 /*
3702 * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
3703 * has violated either the system-wide per-task memory limit OR its own task limit.
3704 */
3705 jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_PERPROCESSLIMIT);
3706 if (jetsam_reason == NULL) {
3707 printf("task_exceeded footprint: failed to allocate jetsam reason\n");
3708 } else if (corpse_for_fatal_memkill != 0) {
3709 /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
3710 jetsam_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
3711 }
3712
3713 if (memorystatus_kill_process_sync(p->p_pid, kMemorystatusKilledPerProcessLimit, jetsam_reason) != TRUE) {
3714 printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
3715 }
3716 } else {
3717 /*
3718 * HWM offender exists. Done without locks or synchronization.
3719 * See comment near its declaration for more details.
3720 */
3721 memorystatus_hwm_candidates = TRUE;
3722
3723 #if VM_PRESSURE_EVENTS
3724 /*
3725 * The current process is not in the warning path.
3726 * This path implies the current process has exceeded a non-fatal (soft) memory limit.
3727 * Failure to send note is ignored here.
3728 */
3729 (void)memorystatus_warn_process(p->p_pid, memlimit_is_active, memlimit_is_fatal, TRUE /* exceeded */);
3730
3731 #endif /* VM_PRESSURE_EVENTS */
3732 }
3733 }
3734
3735 void
3736 memorystatus_log_exception(const int max_footprint_mb, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
3737 {
3738 proc_t p = current_proc();
3739
3740 /*
3741 * The limit violation is logged here, but only once per process per limit.
3742 * Soft memory limit is a non-fatal high-water-mark
3743 * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
3744 */
3745
3746 printf("process %d (%s) exceeded physical memory footprint, the %s%sMemoryLimit of %d MB\n",
3747 p->p_pid, (*p->p_name ? p->p_name : "unknown"), (memlimit_is_active ? "Active" : "Inactive"),
3748 (memlimit_is_fatal ? "Hard" : "Soft"), max_footprint_mb);
3749
3750 return;
3751 }
3752
3753
3754 /*
3755 * Description:
3756 * Evaluates active vs. inactive process state.
3757 * Processes that opt into dirty tracking are evaluated
3758 * based on clean vs dirty state.
3759 * dirty ==> active
3760 * clean ==> inactive
3761 *
3762 * Process that do not opt into dirty tracking are
3763 * evalulated based on priority level.
3764 * Foreground or above ==> active
3765 * Below Foreground ==> inactive
3766 *
3767 * Return: TRUE if active
3768 * False if inactive
3769 */
3770
3771 static boolean_t
3772 proc_jetsam_state_is_active_locked(proc_t p) {
3773
3774 if (p->p_memstat_dirty & P_DIRTY_TRACK) {
3775 /*
3776 * process has opted into dirty tracking
3777 * active state is based on dirty vs. clean
3778 */
3779 if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
3780 /*
3781 * process is dirty
3782 * implies active state
3783 */
3784 return TRUE;
3785 } else {
3786 /*
3787 * process is clean
3788 * implies inactive state
3789 */
3790 return FALSE;
3791 }
3792 } else if (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND) {
3793 /*
3794 * process is Foreground or higher
3795 * implies active state
3796 */
3797 return TRUE;
3798 } else {
3799 /*
3800 * process found below Foreground
3801 * implies inactive state
3802 */
3803 return FALSE;
3804 }
3805 }
3806
3807 static boolean_t
3808 memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason) {
3809 boolean_t res;
3810
3811 #if CONFIG_JETSAM
3812 uint32_t errors = 0;
3813
3814 if (victim_pid == -1) {
3815 /* No pid, so kill first process */
3816 res = memorystatus_kill_top_process(TRUE, TRUE, cause, jetsam_reason, NULL, &errors);
3817 } else {
3818 res = memorystatus_kill_specific_process(victim_pid, cause, jetsam_reason);
3819 }
3820
3821 if (errors) {
3822 memorystatus_clear_errors();
3823 }
3824
3825 if (res == TRUE) {
3826 /* Fire off snapshot notification */
3827 proc_list_lock();
3828 size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
3829 sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_count;
3830 uint64_t timestamp_now = mach_absolute_time();
3831 memorystatus_jetsam_snapshot->notification_time = timestamp_now;
3832 if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
3833 timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
3834 proc_list_unlock();
3835 int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
3836 if (!ret) {
3837 proc_list_lock();
3838 memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
3839 proc_list_unlock();
3840 }
3841 } else {
3842 proc_list_unlock();
3843 }
3844 }
3845 #else /* !CONFIG_JETSAM */
3846
3847 res = memorystatus_kill_specific_process(victim_pid, cause, jetsam_reason);
3848
3849 #endif /* CONFIG_JETSAM */
3850
3851 return res;
3852 }
3853
3854 /*
3855 * Jetsam a specific process.
3856 */
3857 static boolean_t
3858 memorystatus_kill_specific_process(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason) {
3859 boolean_t killed;
3860 proc_t p;
3861 uint64_t killtime = 0;
3862 clock_sec_t tv_sec;
3863 clock_usec_t tv_usec;
3864 uint32_t tv_msec;
3865
3866 /* TODO - add a victim queue and push this into the main jetsam thread */
3867
3868 p = proc_find(victim_pid);
3869 if (!p) {
3870 os_reason_free(jetsam_reason);
3871 return FALSE;
3872 }
3873
3874 proc_list_lock();
3875
3876 #if CONFIG_JETSAM
3877 if (memorystatus_jetsam_snapshot_count == 0) {
3878 memorystatus_init_jetsam_snapshot_locked(NULL,0);
3879 }
3880
3881 killtime = mach_absolute_time();
3882 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
3883 tv_msec = tv_usec / 1000;
3884
3885 memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
3886
3887 proc_list_unlock();
3888
3889 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
3890 (unsigned long)tv_sec, tv_msec, victim_pid, (*p->p_name ? p->p_name : "(unknown)"),
3891 jetsam_kill_cause_name[cause], p->p_memstat_effectivepriority, memorystatus_available_pages);
3892 #else /* !CONFIG_JETSAM */
3893 proc_list_unlock();
3894
3895 killtime = mach_absolute_time();
3896 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
3897 tv_msec = tv_usec / 1000;
3898 printf("%lu.%02d memorystatus: specifically killing pid %d [%s] (%s %d)\n",
3899 (unsigned long)tv_sec, tv_msec, victim_pid, (*p->p_name ? p->p_name : "(unknown)"),
3900 jetsam_kill_cause_name[cause], p->p_memstat_effectivepriority);
3901 #endif /* CONFIG_JETSAM */
3902
3903 killed = memorystatus_do_kill(p, cause, jetsam_reason);
3904 proc_rele(p);
3905
3906 return killed;
3907 }
3908
3909
3910 /*
3911 * Toggle the P_MEMSTAT_TERMINATED state.
3912 * Takes the proc_list_lock.
3913 */
3914 void
3915 proc_memstat_terminated(proc_t p, boolean_t set)
3916 {
3917 #if DEVELOPMENT || DEBUG
3918 if (p) {
3919 proc_list_lock();
3920 if (set == TRUE) {
3921 p->p_memstat_state |= P_MEMSTAT_TERMINATED;
3922 } else {
3923 p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
3924 }
3925 proc_list_unlock();
3926 }
3927 #else
3928 #pragma unused(p, set)
3929 /*
3930 * do nothing
3931 */
3932 #endif /* DEVELOPMENT || DEBUG */
3933 return;
3934 }
3935
3936
3937 #if CONFIG_JETSAM
3938 /*
3939 * This is invoked when cpulimits have been exceeded while in fatal mode.
3940 * The jetsam_flags do not apply as those are for memory related kills.
3941 * We call this routine so that the offending process is killed with
3942 * a non-zero exit status.
3943 */
3944 void
3945 jetsam_on_ledger_cpulimit_exceeded(void)
3946 {
3947 int retval = 0;
3948 int jetsam_flags = 0; /* make it obvious */
3949 proc_t p = current_proc();
3950 os_reason_t jetsam_reason = OS_REASON_NULL;
3951
3952 printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
3953 p->p_pid, (*p->p_name ? p->p_name : "(unknown)"));
3954
3955 jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_CPULIMIT);
3956 if (jetsam_reason == OS_REASON_NULL) {
3957 printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
3958 }
3959
3960 retval = jetsam_do_kill(p, jetsam_flags, jetsam_reason);
3961
3962 if (retval) {
3963 printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
3964 }
3965 }
3966
3967 static void
3968 memorystatus_get_task_memory_region_count(task_t task, uint64_t *count)
3969 {
3970 assert(task);
3971 assert(count);
3972
3973 *count = get_task_memory_region_count(task);
3974 }
3975
3976 static void
3977 memorystatus_get_task_page_counts(task_t task, uint32_t *footprint, uint32_t *max_footprint, uint32_t *max_footprint_lifetime, uint32_t *purgeable_pages)
3978 {
3979 assert(task);
3980 assert(footprint);
3981
3982 uint64_t pages;
3983
3984 pages = (get_task_phys_footprint(task) / PAGE_SIZE_64);
3985 assert(((uint32_t)pages) == pages);
3986 *footprint = (uint32_t)pages;
3987
3988 if (max_footprint) {
3989 pages = (get_task_phys_footprint_max(task) / PAGE_SIZE_64);
3990 assert(((uint32_t)pages) == pages);
3991 *max_footprint = (uint32_t)pages;
3992 }
3993 if (max_footprint_lifetime) {
3994 pages = (get_task_resident_max(task) / PAGE_SIZE_64);
3995 assert(((uint32_t)pages) == pages);
3996 *max_footprint_lifetime = (uint32_t)pages;
3997 }
3998 if (purgeable_pages) {
3999 pages = (get_task_purgeable_size(task) / PAGE_SIZE_64);
4000 assert(((uint32_t)pages) == pages);
4001 *purgeable_pages = (uint32_t)pages;
4002 }
4003 }
4004
4005 static void
4006 memorystatus_get_task_phys_footprint_page_counts(task_t task,
4007 uint64_t *internal_pages, uint64_t *internal_compressed_pages,
4008 uint64_t *purgeable_nonvolatile_pages, uint64_t *purgeable_nonvolatile_compressed_pages,
4009 uint64_t *alternate_accounting_pages, uint64_t *alternate_accounting_compressed_pages,
4010 uint64_t *iokit_mapped_pages, uint64_t *page_table_pages)
4011 {
4012 assert(task);
4013
4014 if (internal_pages) {
4015 *internal_pages = (get_task_internal(task) / PAGE_SIZE_64);
4016 }
4017
4018 if (internal_compressed_pages) {
4019 *internal_compressed_pages = (get_task_internal_compressed(task) / PAGE_SIZE_64);
4020 }
4021
4022 if (purgeable_nonvolatile_pages) {
4023 *purgeable_nonvolatile_pages = (get_task_purgeable_nonvolatile(task) / PAGE_SIZE_64);
4024 }
4025
4026 if (purgeable_nonvolatile_compressed_pages) {
4027 *purgeable_nonvolatile_compressed_pages = (get_task_purgeable_nonvolatile_compressed(task) / PAGE_SIZE_64);
4028 }
4029
4030 if (alternate_accounting_pages) {
4031 *alternate_accounting_pages = (get_task_alternate_accounting(task) / PAGE_SIZE_64);
4032 }
4033
4034 if (alternate_accounting_compressed_pages) {
4035 *alternate_accounting_compressed_pages = (get_task_alternate_accounting_compressed(task) / PAGE_SIZE_64);
4036 }
4037
4038 if (iokit_mapped_pages) {
4039 *iokit_mapped_pages = (get_task_iokit_mapped(task) / PAGE_SIZE_64);
4040 }
4041
4042 if (page_table_pages) {
4043 *page_table_pages = (get_task_page_table(task) / PAGE_SIZE_64);
4044 }
4045 }
4046
4047 /*
4048 * This routine only acts on the global jetsam event snapshot.
4049 * Updating the process's entry can race when the memorystatus_thread
4050 * has chosen to kill a process that is racing to exit on another core.
4051 */
4052 static void
4053 memorystatus_update_jetsam_snapshot_entry_locked(proc_t p, uint32_t kill_cause, uint64_t killtime)
4054 {
4055 memorystatus_jetsam_snapshot_entry_t *entry = NULL;
4056 memorystatus_jetsam_snapshot_t *snapshot = NULL;
4057 memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
4058
4059 unsigned int i;
4060
4061 if (memorystatus_jetsam_snapshot_count == 0) {
4062 /*
4063 * No active snapshot.
4064 * Nothing to do.
4065 */
4066 return;
4067 }
4068
4069 /*
4070 * Sanity check as this routine should only be called
4071 * from a jetsam kill path.
4072 */
4073 assert(kill_cause != 0 && killtime != 0);
4074
4075 snapshot = memorystatus_jetsam_snapshot;
4076 snapshot_list = memorystatus_jetsam_snapshot->entries;
4077
4078 for (i = 0; i < memorystatus_jetsam_snapshot_count; i++) {
4079 if (snapshot_list[i].pid == p->p_pid) {
4080
4081 entry = &snapshot_list[i];
4082
4083 if (entry->killed || entry->jse_killtime) {
4084 /*
4085 * We apparently raced on the exit path
4086 * for this process, as it's snapshot entry
4087 * has already recorded a kill.
4088 */
4089 assert(entry->killed && entry->jse_killtime);
4090 break;
4091 }
4092
4093 /*
4094 * Update the entry we just found in the snapshot.
4095 */
4096
4097 entry->killed = kill_cause;
4098 entry->jse_killtime = killtime;
4099 entry->jse_gencount = snapshot->js_gencount;
4100 entry->jse_idle_delta = p->p_memstat_idle_delta;
4101
4102 /*
4103 * If a process has moved between bands since snapshot was
4104 * initialized, then likely these fields changed too.
4105 */
4106 if (entry->priority != p->p_memstat_effectivepriority) {
4107
4108 strlcpy(entry->name, p->p_name, sizeof(entry->name));
4109 entry->priority = p->p_memstat_effectivepriority;
4110 entry->state = memorystatus_build_state(p);
4111 entry->user_data = p->p_memstat_userdata;
4112 entry->fds = p->p_fd->fd_nfiles;
4113 }
4114
4115 /*
4116 * Always update the page counts on a kill.
4117 */
4118
4119 uint32_t pages = 0;
4120 uint32_t max_pages = 0;
4121 uint32_t max_pages_lifetime = 0;
4122 uint32_t purgeable_pages = 0;
4123
4124 memorystatus_get_task_page_counts(p->task, &pages, &max_pages, &max_pages_lifetime, &purgeable_pages);
4125 entry->pages = (uint64_t)pages;
4126 entry->max_pages = (uint64_t)max_pages;
4127 entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
4128 entry->purgeable_pages = (uint64_t)purgeable_pages;
4129
4130 uint64_t internal_pages = 0;
4131 uint64_t internal_compressed_pages = 0;
4132 uint64_t purgeable_nonvolatile_pages = 0;
4133 uint64_t purgeable_nonvolatile_compressed_pages = 0;
4134 uint64_t alternate_accounting_pages = 0;
4135 uint64_t alternate_accounting_compressed_pages = 0;
4136 uint64_t iokit_mapped_pages = 0;
4137 uint64_t page_table_pages = 0;
4138
4139 memorystatus_get_task_phys_footprint_page_counts(p->task, &internal_pages, &internal_compressed_pages,
4140 &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
4141 &alternate_accounting_pages, &alternate_accounting_compressed_pages,
4142 &iokit_mapped_pages, &page_table_pages);
4143
4144 entry->jse_internal_pages = internal_pages;
4145 entry->jse_internal_compressed_pages = internal_compressed_pages;
4146 entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
4147 entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
4148 entry->jse_alternate_accounting_pages = alternate_accounting_pages;
4149 entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
4150 entry->jse_iokit_mapped_pages = iokit_mapped_pages;
4151 entry->jse_page_table_pages = page_table_pages;
4152
4153 uint64_t region_count = 0;
4154 memorystatus_get_task_memory_region_count(p->task, &region_count);
4155 entry->jse_memory_region_count = region_count;
4156
4157 goto exit;
4158 }
4159 }
4160
4161 if (entry == NULL) {
4162 /*
4163 * The entry was not found in the snapshot, so the process must have
4164 * launched after the snapshot was initialized.
4165 * Let's try to append the new entry.
4166 */
4167 if (memorystatus_jetsam_snapshot_count < memorystatus_jetsam_snapshot_max) {
4168 /*
4169 * A populated snapshot buffer exists
4170 * and there is room to init a new entry.
4171 */
4172 assert(memorystatus_jetsam_snapshot_count == snapshot->entry_count);
4173
4174 unsigned int next = memorystatus_jetsam_snapshot_count;
4175
4176 if(memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[next], (snapshot->js_gencount)) == TRUE) {
4177
4178 entry = &snapshot_list[next];
4179 entry->killed = kill_cause;
4180 entry->jse_killtime = killtime;
4181
4182 snapshot->entry_count = ++next;
4183 memorystatus_jetsam_snapshot_count = next;
4184
4185 if (memorystatus_jetsam_snapshot_count >= memorystatus_jetsam_snapshot_max) {
4186 /*
4187 * We just used the last slot in the snapshot buffer.
4188 * We only want to log it once... so we do it here
4189 * when we notice we've hit the max.
4190 */
4191 printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
4192 memorystatus_jetsam_snapshot_count);
4193 }
4194 }
4195 }
4196 }
4197
4198 exit:
4199 if (entry == NULL) {
4200 /*
4201 * If we reach here, the snapshot buffer could not be updated.
4202 * Most likely, the buffer is full, in which case we would have
4203 * logged a warning in the previous call.
4204 *
4205 * For now, we will stop appending snapshot entries.
4206 * When the buffer is consumed, the snapshot state will reset.
4207 */
4208
4209 MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
4210 p->p_pid, p->p_memstat_effectivepriority, memorystatus_jetsam_snapshot_count);
4211 }
4212
4213 return;
4214 }
4215
4216 void memorystatus_pages_update(unsigned int pages_avail)
4217 {
4218 memorystatus_available_pages = pages_avail;
4219
4220 #if VM_PRESSURE_EVENTS
4221 /*
4222 * Since memorystatus_available_pages changes, we should
4223 * re-evaluate the pressure levels on the system and
4224 * check if we need to wake the pressure thread.
4225 * We also update memorystatus_level in that routine.
4226 */
4227 vm_pressure_response();
4228
4229 if (memorystatus_available_pages <= memorystatus_available_pages_pressure) {
4230
4231 if (memorystatus_hwm_candidates || (memorystatus_available_pages <= memorystatus_available_pages_critical)) {
4232 memorystatus_thread_wake();
4233 }
4234 }
4235 #else /* VM_PRESSURE_EVENTS */
4236
4237 boolean_t critical, delta;
4238
4239 if (!memorystatus_delta) {
4240 return;
4241 }
4242
4243 critical = (pages_avail < memorystatus_available_pages_critical) ? TRUE : FALSE;
4244 delta = ((pages_avail >= (memorystatus_available_pages + memorystatus_delta))
4245 || (memorystatus_available_pages >= (pages_avail + memorystatus_delta))) ? TRUE : FALSE;
4246
4247 if (critical || delta) {
4248 unsigned int total_pages;
4249
4250 total_pages = (unsigned int) atop_64(max_mem);
4251 #if CONFIG_SECLUDED_MEMORY
4252 total_pages -= vm_page_secluded_count;
4253 #endif /* CONFIG_SECLUDED_MEMORY */
4254 memorystatus_level = memorystatus_available_pages * 100 / total_pages;
4255 memorystatus_thread_wake();
4256 }
4257 #endif /* VM_PRESSURE_EVENTS */
4258 }
4259
4260 static boolean_t
4261 memorystatus_init_jetsam_snapshot_entry_locked(proc_t p, memorystatus_jetsam_snapshot_entry_t *entry, uint64_t gencount)
4262 {
4263 clock_sec_t tv_sec;
4264 clock_usec_t tv_usec;
4265 uint32_t pages = 0;
4266 uint32_t max_pages = 0;
4267 uint32_t max_pages_lifetime = 0;
4268 uint32_t purgeable_pages = 0;
4269 uint64_t internal_pages = 0;
4270 uint64_t internal_compressed_pages = 0;
4271 uint64_t purgeable_nonvolatile_pages = 0;
4272 uint64_t purgeable_nonvolatile_compressed_pages = 0;
4273 uint64_t alternate_accounting_pages = 0;
4274 uint64_t alternate_accounting_compressed_pages = 0;
4275 uint64_t iokit_mapped_pages = 0;
4276 uint64_t page_table_pages =0;
4277 uint64_t region_count = 0;
4278 uint64_t cids[COALITION_NUM_TYPES];
4279
4280 memset(entry, 0, sizeof(memorystatus_jetsam_snapshot_entry_t));
4281
4282 entry->pid = p->p_pid;
4283 strlcpy(&entry->name[0], p->p_name, sizeof(entry->name));
4284 entry->priority = p->p_memstat_effectivepriority;
4285
4286 memorystatus_get_task_page_counts(p->task, &pages, &max_pages, &max_pages_lifetime, &purgeable_pages);
4287 entry->pages = (uint64_t)pages;
4288 entry->max_pages = (uint64_t)max_pages;
4289 entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
4290 entry->purgeable_pages = (uint64_t)purgeable_pages;
4291
4292 memorystatus_get_task_phys_footprint_page_counts(p->task, &internal_pages, &internal_compressed_pages,
4293 &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
4294 &alternate_accounting_pages, &alternate_accounting_compressed_pages,
4295 &iokit_mapped_pages, &page_table_pages);
4296
4297 entry->jse_internal_pages = internal_pages;
4298 entry->jse_internal_compressed_pages = internal_compressed_pages;
4299 entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
4300 entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
4301 entry->jse_alternate_accounting_pages = alternate_accounting_pages;
4302 entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
4303 entry->jse_iokit_mapped_pages = iokit_mapped_pages;
4304 entry->jse_page_table_pages = page_table_pages;
4305
4306 memorystatus_get_task_memory_region_count(p->task, &region_count);
4307 entry->jse_memory_region_count = region_count;
4308
4309 entry->state = memorystatus_build_state(p);
4310 entry->user_data = p->p_memstat_userdata;
4311 memcpy(&entry->uuid[0], &p->p_uuid[0], sizeof(p->p_uuid));
4312 entry->fds = p->p_fd->fd_nfiles;
4313
4314 absolutetime_to_microtime(get_task_cpu_time(p->task), &tv_sec, &tv_usec);
4315 entry->cpu_time.tv_sec = tv_sec;
4316 entry->cpu_time.tv_usec = tv_usec;
4317
4318 assert(p->p_stats != NULL);
4319 entry->jse_starttime = p->p_stats->ps_start; /* abstime process started */
4320 entry->jse_killtime = 0; /* abstime jetsam chose to kill process */
4321 entry->killed = 0; /* the jetsam kill cause */
4322 entry->jse_gencount = gencount; /* indicates a pass through jetsam thread, when process was targeted to be killed */
4323
4324 entry->jse_idle_delta = p->p_memstat_idle_delta; /* Most recent timespan spent in idle-band */
4325
4326 proc_coalitionids(p, cids);
4327 entry->jse_coalition_jetsam_id = cids[COALITION_TYPE_JETSAM];
4328
4329 return TRUE;
4330 }
4331
4332 static void
4333 memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t *snapshot)
4334 {
4335 kern_return_t kr = KERN_SUCCESS;
4336 mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
4337 vm_statistics64_data_t vm_stat;
4338
4339 if ((kr = host_statistics64(host_self(), HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) != KERN_SUCCESS)) {
4340 printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr);
4341 memset(&snapshot->stats, 0, sizeof(snapshot->stats));
4342 } else {
4343 snapshot->stats.free_pages = vm_stat.free_count;
4344 snapshot->stats.active_pages = vm_stat.active_count;
4345 snapshot->stats.inactive_pages = vm_stat.inactive_count;
4346 snapshot->stats.throttled_pages = vm_stat.throttled_count;
4347 snapshot->stats.purgeable_pages = vm_stat.purgeable_count;
4348 snapshot->stats.wired_pages = vm_stat.wire_count;
4349
4350 snapshot->stats.speculative_pages = vm_stat.speculative_count;
4351 snapshot->stats.filebacked_pages = vm_stat.external_page_count;
4352 snapshot->stats.anonymous_pages = vm_stat.internal_page_count;
4353 snapshot->stats.compressions = vm_stat.compressions;
4354 snapshot->stats.decompressions = vm_stat.decompressions;
4355 snapshot->stats.compressor_pages = vm_stat.compressor_page_count;
4356 snapshot->stats.total_uncompressed_pages_in_compressor = vm_stat.total_uncompressed_pages_in_compressor;
4357 }
4358 }
4359
4360 /*
4361 * Collect vm statistics at boot.
4362 * Called only once (see kern_exec.c)
4363 * Data can be consumed at any time.
4364 */
4365 void
4366 memorystatus_init_at_boot_snapshot() {
4367 memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot);
4368 memorystatus_at_boot_snapshot.entry_count = 0;
4369 memorystatus_at_boot_snapshot.notification_time = 0; /* updated when consumed */
4370 memorystatus_at_boot_snapshot.snapshot_time = mach_absolute_time();
4371 }
4372
4373 static void
4374 memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t *od_snapshot, uint32_t ods_list_count )
4375 {
4376 proc_t p, next_p;
4377 unsigned int b = 0, i = 0;
4378
4379 memorystatus_jetsam_snapshot_t *snapshot = NULL;
4380 memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
4381 unsigned int snapshot_max = 0;
4382
4383 if (od_snapshot) {
4384 /*
4385 * This is an on_demand snapshot
4386 */
4387 snapshot = od_snapshot;
4388 snapshot_list = od_snapshot->entries;
4389 snapshot_max = ods_list_count;
4390 } else {
4391 /*
4392 * This is a jetsam event snapshot
4393 */
4394 snapshot = memorystatus_jetsam_snapshot;
4395 snapshot_list = memorystatus_jetsam_snapshot->entries;
4396 snapshot_max = memorystatus_jetsam_snapshot_max;
4397 }
4398
4399 /*
4400 * Init the snapshot header information
4401 */
4402 memorystatus_init_snapshot_vmstats(snapshot);
4403 snapshot->snapshot_time = mach_absolute_time();
4404 snapshot->notification_time = 0;
4405 snapshot->js_gencount = 0;
4406
4407 next_p = memorystatus_get_first_proc_locked(&b, TRUE);
4408 while (next_p) {
4409 p = next_p;
4410 next_p = memorystatus_get_next_proc_locked(&b, p, TRUE);
4411
4412 if (FALSE == memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[i], snapshot->js_gencount)) {
4413 continue;
4414 }
4415
4416 MEMORYSTATUS_DEBUG(0, "jetsam snapshot pid %d, uuid = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
4417 p->p_pid,
4418 p->p_uuid[0], p->p_uuid[1], p->p_uuid[2], p->p_uuid[3], p->p_uuid[4], p->p_uuid[5], p->p_uuid[6], p->p_uuid[7],
4419 p->p_uuid[8], p->p_uuid[9], p->p_uuid[10], p->p_uuid[11], p->p_uuid[12], p->p_uuid[13], p->p_uuid[14], p->p_uuid[15]);
4420
4421 if (++i == snapshot_max) {
4422 break;
4423 }
4424 }
4425
4426 snapshot->entry_count = i;
4427
4428 if (!od_snapshot) {
4429 /* update the system buffer count */
4430 memorystatus_jetsam_snapshot_count = i;
4431 }
4432 }
4433
4434 #if DEVELOPMENT || DEBUG
4435
4436 static int
4437 memorystatus_cmd_set_panic_bits(user_addr_t buffer, uint32_t buffer_size) {
4438 int ret;
4439 memorystatus_jetsam_panic_options_t debug;
4440
4441 if (buffer_size != sizeof(memorystatus_jetsam_panic_options_t)) {
4442 return EINVAL;
4443 }
4444
4445 ret = copyin(buffer, &debug, buffer_size);
4446 if (ret) {
4447 return ret;
4448 }
4449
4450 /* Panic bits match kMemorystatusKilled* enum */
4451 memorystatus_jetsam_panic_debug = (memorystatus_jetsam_panic_debug & ~debug.mask) | (debug.data & debug.mask);
4452
4453 /* Copyout new value */
4454 debug.data = memorystatus_jetsam_panic_debug;
4455 ret = copyout(&debug, buffer, sizeof(memorystatus_jetsam_panic_options_t));
4456
4457 return ret;
4458 }
4459
4460 /*
4461 * Triggers a sort_order on a specified jetsam priority band.
4462 * This is for testing only, used to force a path through the sort
4463 * function.
4464 */
4465 static int
4466 memorystatus_cmd_test_jetsam_sort(int priority, int sort_order) {
4467
4468 int error = 0;
4469
4470 unsigned int bucket_index = 0;
4471
4472 if (priority == -1) {
4473 /* Use as shorthand for default priority */
4474 bucket_index = JETSAM_PRIORITY_DEFAULT;
4475 } else {
4476 bucket_index = (unsigned int)priority;
4477 }
4478
4479 error = memorystatus_sort_bucket(bucket_index, sort_order);
4480
4481 return (error);
4482 }
4483
4484 #endif /* DEVELOPMENT || DEBUG */
4485
4486 /*
4487 * Jetsam the first process in the queue.
4488 */
4489 static boolean_t
4490 memorystatus_kill_top_process(boolean_t any, boolean_t sort_flag, uint32_t cause, os_reason_t jetsam_reason,
4491 int32_t *priority, uint32_t *errors)
4492 {
4493 pid_t aPid;
4494 proc_t p = PROC_NULL, next_p = PROC_NULL;
4495 boolean_t new_snapshot = FALSE, killed = FALSE;
4496 int kill_count = 0;
4497 unsigned int i = 0;
4498 uint32_t aPid_ep;
4499 uint64_t killtime = 0;
4500 clock_sec_t tv_sec;
4501 clock_usec_t tv_usec;
4502 uint32_t tv_msec;
4503
4504 #ifndef CONFIG_FREEZE
4505 #pragma unused(any)
4506 #endif
4507
4508 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
4509 memorystatus_available_pages, 0, 0, 0, 0);
4510
4511
4512 if (sort_flag == TRUE) {
4513 (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
4514 }
4515
4516 proc_list_lock();
4517
4518 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4519 while (next_p) {
4520 #if DEVELOPMENT || DEBUG
4521 int activeProcess;
4522 int procSuspendedForDiagnosis;
4523 #endif /* DEVELOPMENT || DEBUG */
4524
4525 p = next_p;
4526 next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
4527
4528 #if DEVELOPMENT || DEBUG
4529 activeProcess = p->p_memstat_state & P_MEMSTAT_FOREGROUND;
4530 procSuspendedForDiagnosis = p->p_memstat_state & P_MEMSTAT_DIAG_SUSPENDED;
4531 #endif /* DEVELOPMENT || DEBUG */
4532
4533 aPid = p->p_pid;
4534 aPid_ep = p->p_memstat_effectivepriority;
4535
4536 if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
4537 continue; /* with lock held */
4538 }
4539
4540 #if DEVELOPMENT || DEBUG
4541 if ((memorystatus_jetsam_policy & kPolicyDiagnoseActive) && procSuspendedForDiagnosis) {
4542 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid);
4543 continue;
4544 }
4545 #endif /* DEVELOPMENT || DEBUG */
4546
4547 if (cause == kMemorystatusKilledVnodes)
4548 {
4549 /*
4550 * If the system runs out of vnodes, we systematically jetsam
4551 * processes in hopes of stumbling onto a vnode gain that helps
4552 * the system recover. The process that happens to trigger
4553 * this path has no known relationship to the vnode consumption.
4554 * We attempt to safeguard that process e.g: do not jetsam it.
4555 */
4556
4557 if (p == current_proc()) {
4558 /* do not jetsam the current process */
4559 continue;
4560 }
4561 }
4562
4563 #if CONFIG_FREEZE
4564 boolean_t skip;
4565 boolean_t reclaim_proc = !(p->p_memstat_state & (P_MEMSTAT_LOCKED | P_MEMSTAT_NORECLAIM));
4566 if (any || reclaim_proc) {
4567 skip = FALSE;
4568 } else {
4569 skip = TRUE;
4570 }
4571
4572 if (skip) {
4573 continue;
4574 } else
4575 #endif
4576 {
4577 /*
4578 * Capture a snapshot if none exists and:
4579 * - priority was not requested (this is something other than an ambient kill)
4580 * - the priority was requested *and* the targeted process is not at idle priority
4581 */
4582 if ((memorystatus_jetsam_snapshot_count == 0) &&
4583 (memorystatus_idle_snapshot || ((!priority) || (priority && (aPid_ep != JETSAM_PRIORITY_IDLE))))) {
4584 memorystatus_init_jetsam_snapshot_locked(NULL,0);
4585 new_snapshot = TRUE;
4586 }
4587
4588 /*
4589 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4590 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4591 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4592 * acquisition of the proc lock.
4593 */
4594 p->p_memstat_state |= P_MEMSTAT_TERMINATED;
4595
4596 killtime = mach_absolute_time();
4597 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
4598 tv_msec = tv_usec / 1000;
4599
4600 #if DEVELOPMENT || DEBUG
4601 if ((memorystatus_jetsam_policy & kPolicyDiagnoseActive) && activeProcess) {
4602 MEMORYSTATUS_DEBUG(1, "jetsam: suspending pid %d [%s] (active) for diagnosis - memory_status_level: %d\n",
4603 aPid, (*p->p_name ? p->p_name: "(unknown)"), memorystatus_level);
4604 memorystatus_update_jetsam_snapshot_entry_locked(p, kMemorystatusKilledDiagnostic, killtime);
4605 p->p_memstat_state |= P_MEMSTAT_DIAG_SUSPENDED;
4606 if (memorystatus_jetsam_policy & kPolicyDiagnoseFirst) {
4607 jetsam_diagnostic_suspended_one_active_proc = 1;
4608 printf("jetsam: returning after suspending first active proc - %d\n", aPid);
4609 }
4610
4611 p = proc_ref_locked(p);
4612 proc_list_unlock();
4613 if (p) {
4614 task_suspend(p->task);
4615 if (priority) {
4616 *priority = aPid_ep;
4617 }
4618 proc_rele(p);
4619 killed = TRUE;
4620 }
4621
4622 goto exit;
4623 } else
4624 #endif /* DEVELOPMENT || DEBUG */
4625 {
4626 /* Shift queue, update stats */
4627 memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
4628
4629 if (proc_ref_locked(p) == p) {
4630 proc_list_unlock();
4631 printf("%lu.%02d memorystatus: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4632 (unsigned long)tv_sec, tv_msec,
4633 ((aPid_ep == JETSAM_PRIORITY_IDLE) ? "idle exiting pid" : "jetsam killing top process pid"),
4634 aPid, (*p->p_name ? p->p_name : "(unknown)"),
4635 jetsam_kill_cause_name[cause], aPid_ep, memorystatus_available_pages);
4636
4637 /*
4638 * memorystatus_do_kill() drops a reference, so take another one so we can
4639 * continue to use this exit reason even after memorystatus_do_kill()
4640 * returns.
4641 */
4642 os_reason_ref(jetsam_reason);
4643
4644 killed = memorystatus_do_kill(p, cause, jetsam_reason);
4645
4646 /* Success? */
4647 if (killed) {
4648 if (priority) {
4649 *priority = aPid_ep;
4650 }
4651 proc_rele(p);
4652 kill_count++;
4653 goto exit;
4654 }
4655
4656 /*
4657 * Failure - first unwind the state,
4658 * then fall through to restart the search.
4659 */
4660 proc_list_lock();
4661 proc_rele_locked(p);
4662 p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
4663 p->p_memstat_state |= P_MEMSTAT_ERROR;
4664 *errors += 1;
4665 }
4666
4667 /*
4668 * Failure - restart the search.
4669 *
4670 * We might have raced with "p" exiting on another core, resulting in no
4671 * ref on "p". Or, we may have failed to kill "p".
4672 *
4673 * Either way, we fall thru to here, leaving the proc in the
4674 * P_MEMSTAT_TERMINATED state.
4675 *
4676 * And, we hold the the proc_list_lock at this point.
4677 */
4678
4679 i = 0;
4680 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4681 }
4682 }
4683 }
4684
4685 proc_list_unlock();
4686
4687 exit:
4688 os_reason_free(jetsam_reason);
4689
4690 /* Clear snapshot if freshly captured and no target was found */
4691 if (new_snapshot && !killed) {
4692 proc_list_lock();
4693 memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
4694 proc_list_unlock();
4695 }
4696
4697 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
4698 memorystatus_available_pages, killed ? aPid : 0, kill_count, 0, 0);
4699
4700 return killed;
4701 }
4702
4703 /*
4704 * Jetsam aggressively
4705 */
4706 static boolean_t
4707 memorystatus_kill_top_process_aggressive(boolean_t any, uint32_t cause, os_reason_t jetsam_reason, int aggr_count,
4708 int32_t priority_max, uint32_t *errors)
4709 {
4710 pid_t aPid;
4711 proc_t p = PROC_NULL, next_p = PROC_NULL;
4712 boolean_t new_snapshot = FALSE, killed = FALSE;
4713 int kill_count = 0;
4714 unsigned int i = 0;
4715 int32_t aPid_ep = 0;
4716 unsigned int memorystatus_level_snapshot = 0;
4717 uint64_t killtime = 0;
4718 clock_sec_t tv_sec;
4719 clock_usec_t tv_usec;
4720 uint32_t tv_msec;
4721
4722 #pragma unused(any)
4723
4724 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
4725 memorystatus_available_pages, priority_max, 0, 0, 0);
4726
4727 memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
4728
4729 proc_list_lock();
4730
4731 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4732 while (next_p) {
4733 #if DEVELOPMENT || DEBUG
4734 int activeProcess;
4735 int procSuspendedForDiagnosis;
4736 #endif /* DEVELOPMENT || DEBUG */
4737
4738 if ((unsigned int)(next_p->p_memstat_effectivepriority) != i) {
4739
4740 /*
4741 * We have raced with next_p running on another core, as it has
4742 * moved to a different jetsam priority band. This means we have
4743 * lost our place in line while traversing the jetsam list. We
4744 * attempt to recover by rewinding to the beginning of the band
4745 * we were already traversing. By doing this, we do not guarantee
4746 * that no process escapes this aggressive march, but we can make
4747 * skipping an entire range of processes less likely. (PR-21069019)
4748 */
4749
4750 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding %s moved from band %d --> %d\n",
4751 aggr_count, (*next_p->p_name ? next_p->p_name : "unknown"), i, next_p->p_memstat_effectivepriority);
4752
4753 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4754 continue;
4755 }
4756
4757 p = next_p;
4758 next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
4759
4760 if (p->p_memstat_effectivepriority > priority_max) {
4761 /*
4762 * Bail out of this killing spree if we have
4763 * reached beyond the priority_max jetsam band.
4764 * That is, we kill up to and through the
4765 * priority_max jetsam band.
4766 */
4767 proc_list_unlock();
4768 goto exit;
4769 }
4770
4771 #if DEVELOPMENT || DEBUG
4772 activeProcess = p->p_memstat_state & P_MEMSTAT_FOREGROUND;
4773 procSuspendedForDiagnosis = p->p_memstat_state & P_MEMSTAT_DIAG_SUSPENDED;
4774 #endif /* DEVELOPMENT || DEBUG */
4775
4776 aPid = p->p_pid;
4777 aPid_ep = p->p_memstat_effectivepriority;
4778
4779 if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
4780 continue;
4781 }
4782
4783 #if DEVELOPMENT || DEBUG
4784 if ((memorystatus_jetsam_policy & kPolicyDiagnoseActive) && procSuspendedForDiagnosis) {
4785 printf("jetsam: continuing after ignoring proc suspended already for diagnosis - %d\n", aPid);
4786 continue;
4787 }
4788 #endif /* DEVELOPMENT || DEBUG */
4789
4790 /*
4791 * Capture a snapshot if none exists.
4792 */
4793 if (memorystatus_jetsam_snapshot_count == 0) {
4794 memorystatus_init_jetsam_snapshot_locked(NULL,0);
4795 new_snapshot = TRUE;
4796 }
4797
4798 /*
4799 * Mark as terminated so that if exit1() indicates success, but the process (for example)
4800 * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
4801 * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
4802 * acquisition of the proc lock.
4803 */
4804 p->p_memstat_state |= P_MEMSTAT_TERMINATED;
4805
4806 killtime = mach_absolute_time();
4807 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
4808 tv_msec = tv_usec / 1000;
4809
4810 /* Shift queue, update stats */
4811 memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
4812
4813 /*
4814 * In order to kill the target process, we will drop the proc_list_lock.
4815 * To guaranteee that p and next_p don't disappear out from under the lock,
4816 * we must take a ref on both.
4817 * If we cannot get a reference, then it's likely we've raced with
4818 * that process exiting on another core.
4819 */
4820 if (proc_ref_locked(p) == p) {
4821 if (next_p) {
4822 while (next_p && (proc_ref_locked(next_p) != next_p)) {
4823 proc_t temp_p;
4824
4825 /*
4826 * We must have raced with next_p exiting on another core.
4827 * Recover by getting the next eligible process in the band.
4828 */
4829
4830 MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
4831 aggr_count, next_p->p_pid, (*next_p->p_name ? next_p->p_name : "(unknown)"));
4832
4833 temp_p = next_p;
4834 next_p = memorystatus_get_next_proc_locked(&i, temp_p, TRUE);
4835 }
4836 }
4837 proc_list_unlock();
4838
4839 printf("%lu.%01d memorystatus: aggressive%d: %s %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
4840 (unsigned long)tv_sec, tv_msec, aggr_count,
4841 ((aPid_ep == JETSAM_PRIORITY_IDLE) ? "idle exiting pid" : "jetsam killing pid"),
4842 aPid, (*p->p_name ? p->p_name : "(unknown)"),
4843 jetsam_kill_cause_name[cause], aPid_ep, memorystatus_available_pages);
4844
4845 memorystatus_level_snapshot = memorystatus_level;
4846
4847 /*
4848 * memorystatus_do_kill() drops a reference, so take another one so we can
4849 * continue to use this exit reason even after memorystatus_do_kill()
4850 * returns.
4851 */
4852 os_reason_ref(jetsam_reason);
4853 killed = memorystatus_do_kill(p, cause, jetsam_reason);
4854
4855 /* Success? */
4856 if (killed) {
4857 proc_rele(p);
4858 kill_count++;
4859 p = NULL;
4860 killed = FALSE;
4861
4862 /*
4863 * Continue the killing spree.
4864 */
4865 proc_list_lock();
4866 if (next_p) {
4867 proc_rele_locked(next_p);
4868 }
4869
4870 if (aPid_ep == JETSAM_PRIORITY_FOREGROUND && memorystatus_aggressive_jetsam_lenient == TRUE) {
4871 if (memorystatus_level > memorystatus_level_snapshot && ((memorystatus_level - memorystatus_level_snapshot) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD)) {
4872 #if DEVELOPMENT || DEBUG
4873 printf("Disabling Lenient mode after one-time deployment.\n");
4874 #endif /* DEVELOPMENT || DEBUG */
4875 memorystatus_aggressive_jetsam_lenient = FALSE;
4876 break;
4877 }
4878 }
4879
4880 continue;
4881 }
4882
4883 /*
4884 * Failure - first unwind the state,
4885 * then fall through to restart the search.
4886 */
4887 proc_list_lock();
4888 proc_rele_locked(p);
4889 if (next_p) {
4890 proc_rele_locked(next_p);
4891 }
4892 p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
4893 p->p_memstat_state |= P_MEMSTAT_ERROR;
4894 *errors += 1;
4895 p = NULL;
4896 }
4897
4898 /*
4899 * Failure - restart the search at the beginning of
4900 * the band we were already traversing.
4901 *
4902 * We might have raced with "p" exiting on another core, resulting in no
4903 * ref on "p". Or, we may have failed to kill "p".
4904 *
4905 * Either way, we fall thru to here, leaving the proc in the
4906 * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
4907 *
4908 * And, we hold the the proc_list_lock at this point.
4909 */
4910
4911 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4912 }
4913
4914 proc_list_unlock();
4915
4916 exit:
4917 os_reason_free(jetsam_reason);
4918
4919 /* Clear snapshot if freshly captured and no target was found */
4920 if (new_snapshot && (kill_count == 0)) {
4921 memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
4922 }
4923
4924 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
4925 memorystatus_available_pages, killed ? aPid : 0, kill_count, 0, 0);
4926
4927 if (kill_count > 0) {
4928 return(TRUE);
4929 }
4930 else {
4931 return(FALSE);
4932 }
4933 }
4934
4935 static boolean_t
4936 memorystatus_kill_hiwat_proc(uint32_t *errors)
4937 {
4938 pid_t aPid = 0;
4939 proc_t p = PROC_NULL, next_p = PROC_NULL;
4940 boolean_t new_snapshot = FALSE, killed = FALSE;
4941 int kill_count = 0;
4942 unsigned int i = 0;
4943 uint32_t aPid_ep;
4944 uint64_t killtime = 0;
4945 clock_sec_t tv_sec;
4946 clock_usec_t tv_usec;
4947 uint32_t tv_msec;
4948 os_reason_t jetsam_reason = OS_REASON_NULL;
4949 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_START,
4950 memorystatus_available_pages, 0, 0, 0, 0);
4951
4952 jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_HIGHWATER);
4953 if (jetsam_reason == OS_REASON_NULL) {
4954 printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
4955 }
4956
4957 proc_list_lock();
4958
4959 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
4960 while (next_p) {
4961 uint64_t footprint_in_bytes = 0;
4962 uint64_t memlimit_in_bytes = 0;
4963 boolean_t skip = 0;
4964
4965 p = next_p;
4966 next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
4967
4968 aPid = p->p_pid;
4969 aPid_ep = p->p_memstat_effectivepriority;
4970
4971 if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
4972 continue;
4973 }
4974
4975 /* skip if no limit set */
4976 if (p->p_memstat_memlimit <= 0) {
4977 continue;
4978 }
4979
4980 #if 0
4981 /*
4982 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
4983 * Background limits are described via the inactive limit slots.
4984 * Their fatal/non-fatal setting will drive whether or not to be
4985 * considered in this kill path.
4986 */
4987
4988 /* skip if a currently inapplicable limit is encountered */
4989 if ((p->p_memstat_state & P_MEMSTAT_MEMLIMIT_BACKGROUND) && (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND)) {
4990 continue;
4991 }
4992 #endif
4993 footprint_in_bytes = get_task_phys_footprint(p->task);
4994 memlimit_in_bytes = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL); /* convert MB to bytes */
4995 skip = (footprint_in_bytes <= memlimit_in_bytes);
4996
4997 #if DEVELOPMENT || DEBUG
4998 if (!skip && (memorystatus_jetsam_policy & kPolicyDiagnoseActive)) {
4999 if (p->p_memstat_state & P_MEMSTAT_DIAG_SUSPENDED) {
5000 continue;
5001 }
5002 }
5003 #endif /* DEVELOPMENT || DEBUG */
5004
5005 #if CONFIG_FREEZE
5006 if (!skip) {
5007 if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
5008 skip = TRUE;
5009 } else {
5010 skip = FALSE;
5011 }
5012 }
5013 #endif
5014
5015 if (skip) {
5016 continue;
5017 } else {
5018 #if DEVELOPMENT || DEBUG
5019 MEMORYSTATUS_DEBUG(1, "jetsam: %s pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
5020 (memorystatus_jetsam_policy & kPolicyDiagnoseActive) ? "suspending": "killing",
5021 aPid, (*p->p_name ? p->p_name : "unknown"),
5022 (footprint_in_bytes / (1024ULL * 1024ULL)), /* converted bytes to MB */
5023 p->p_memstat_memlimit);
5024 #endif /* DEVELOPMENT || DEBUG */
5025
5026 if (memorystatus_jetsam_snapshot_count == 0) {
5027 memorystatus_init_jetsam_snapshot_locked(NULL,0);
5028 new_snapshot = TRUE;
5029 }
5030
5031 p->p_memstat_state |= P_MEMSTAT_TERMINATED;
5032
5033 killtime = mach_absolute_time();
5034 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
5035 tv_msec = tv_usec / 1000;
5036
5037 #if DEVELOPMENT || DEBUG
5038 if (memorystatus_jetsam_policy & kPolicyDiagnoseActive) {
5039 MEMORYSTATUS_DEBUG(1, "jetsam: pid %d suspended for diagnosis - memorystatus_available_pages: %d\n", aPid, memorystatus_available_pages);
5040 memorystatus_update_jetsam_snapshot_entry_locked(p, kMemorystatusKilledDiagnostic, killtime);
5041 p->p_memstat_state |= P_MEMSTAT_DIAG_SUSPENDED;
5042
5043 p = proc_ref_locked(p);
5044 proc_list_unlock();
5045 if (p) {
5046 task_suspend(p->task);
5047 proc_rele(p);
5048 killed = TRUE;
5049 }
5050
5051 goto exit;
5052 } else
5053 #endif /* DEVELOPMENT || DEBUG */
5054 {
5055 memorystatus_update_jetsam_snapshot_entry_locked(p, kMemorystatusKilledHiwat, killtime);
5056
5057 if (proc_ref_locked(p) == p) {
5058 proc_list_unlock();
5059
5060 printf("%lu.%02d memorystatus: jetsam killing pid %d [%s] (highwater %d) - memorystatus_available_pages: %d\n",
5061 (unsigned long)tv_sec, tv_msec, aPid, (*p->p_name ? p->p_name : "(unknown)"), aPid_ep, memorystatus_available_pages);
5062
5063 /*
5064 * memorystatus_do_kill drops a reference, so take another one so we can
5065 * continue to use this exit reason even after memorystatus_do_kill()
5066 * returns
5067 */
5068 os_reason_ref(jetsam_reason);
5069
5070 killed = memorystatus_do_kill(p, kMemorystatusKilledHiwat, jetsam_reason);
5071
5072 /* Success? */
5073 if (killed) {
5074 proc_rele(p);
5075 kill_count++;
5076 goto exit;
5077 }
5078
5079 /*
5080 * Failure - first unwind the state,
5081 * then fall through to restart the search.
5082 */
5083 proc_list_lock();
5084 proc_rele_locked(p);
5085 p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
5086 p->p_memstat_state |= P_MEMSTAT_ERROR;
5087 *errors += 1;
5088 }
5089
5090 /*
5091 * Failure - restart the search.
5092 *
5093 * We might have raced with "p" exiting on another core, resulting in no
5094 * ref on "p". Or, we may have failed to kill "p".
5095 *
5096 * Either way, we fall thru to here, leaving the proc in the
5097 * P_MEMSTAT_TERMINATED state.
5098 *
5099 * And, we hold the the proc_list_lock at this point.
5100 */
5101
5102 i = 0;
5103 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5104 }
5105 }
5106 }
5107
5108 proc_list_unlock();
5109
5110 exit:
5111 os_reason_free(jetsam_reason);
5112
5113 /* Clear snapshot if freshly captured and no target was found */
5114 if (new_snapshot && !killed) {
5115 proc_list_lock();
5116 memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
5117 proc_list_unlock();
5118 }
5119
5120 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_END,
5121 memorystatus_available_pages, killed ? aPid : 0, kill_count, 0, 0);
5122
5123 return killed;
5124 }
5125
5126 /*
5127 * Jetsam a process pinned in the elevated band.
5128 *
5129 * Return: true -- at least one pinned process was jetsammed
5130 * false -- no pinned process was jetsammed
5131 */
5132 static boolean_t
5133 memorystatus_kill_elevated_process(uint32_t cause, os_reason_t jetsam_reason, int aggr_count, uint32_t *errors)
5134 {
5135 pid_t aPid = 0;
5136 proc_t p = PROC_NULL, next_p = PROC_NULL;
5137 boolean_t new_snapshot = FALSE, killed = FALSE;
5138 int kill_count = 0;
5139 unsigned int i = JETSAM_PRIORITY_ELEVATED_INACTIVE;
5140 uint32_t aPid_ep;
5141 uint64_t killtime = 0;
5142 clock_sec_t tv_sec;
5143 clock_usec_t tv_usec;
5144 uint32_t tv_msec;
5145
5146
5147 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
5148 memorystatus_available_pages, 0, 0, 0, 0);
5149
5150 proc_list_lock();
5151
5152 next_p = memorystatus_get_first_proc_locked(&i, FALSE);
5153 while (next_p) {
5154
5155 p = next_p;
5156 next_p = memorystatus_get_next_proc_locked(&i, p, FALSE);
5157
5158 aPid = p->p_pid;
5159 aPid_ep = p->p_memstat_effectivepriority;
5160
5161 /*
5162 * Only pick a process pinned in this elevated band
5163 */
5164 if (!(p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) {
5165 continue;
5166 }
5167
5168 if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
5169 continue;
5170 }
5171
5172 #if CONFIG_FREEZE
5173 if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
5174 continue;
5175 }
5176 #endif
5177
5178 #if DEVELOPMENT || DEBUG
5179 MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
5180 aggr_count,
5181 aPid, (*p->p_name ? p->p_name : "unknown"),
5182 memorystatus_available_pages);
5183 #endif /* DEVELOPMENT || DEBUG */
5184
5185 if (memorystatus_jetsam_snapshot_count == 0) {
5186 memorystatus_init_jetsam_snapshot_locked(NULL,0);
5187 new_snapshot = TRUE;
5188 }
5189
5190 p->p_memstat_state |= P_MEMSTAT_TERMINATED;
5191
5192 killtime = mach_absolute_time();
5193 absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
5194 tv_msec = tv_usec / 1000;
5195
5196 memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
5197
5198 if (proc_ref_locked(p) == p) {
5199
5200 proc_list_unlock();
5201
5202 printf("%lu.%01d memorystatus: elevated%d: jetsam killing pid %d [%s] (%s %d) - memorystatus_available_pages: %d\n",
5203 (unsigned long)tv_sec, tv_msec,
5204 aggr_count,
5205 aPid, (*p->p_name ? p->p_name : "(unknown)"),
5206 jetsam_kill_cause_name[cause], aPid_ep, memorystatus_available_pages);
5207
5208 /*
5209 * memorystatus_do_kill drops a reference, so take another one so we can
5210 * continue to use this exit reason even after memorystatus_do_kill()
5211 * returns
5212 */
5213 os_reason_ref(jetsam_reason);
5214 killed = memorystatus_do_kill(p, cause, jetsam_reason);
5215
5216 /* Success? */
5217 if (killed) {
5218 proc_rele(p);
5219 kill_count++;
5220 goto exit;
5221 }
5222
5223 /*
5224 * Failure - first unwind the state,
5225 * then fall through to restart the search.
5226 */
5227 proc_list_lock();
5228 proc_rele_locked(p);
5229 p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
5230 p->p_memstat_state |= P_MEMSTAT_ERROR;
5231 *errors += 1;
5232 }
5233
5234 /*
5235 * Failure - restart the search.
5236 *
5237 * We might have raced with "p" exiting on another core, resulting in no
5238 * ref on "p". Or, we may have failed to kill "p".
5239 *
5240 * Either way, we fall thru to here, leaving the proc in the
5241 * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
5242 *
5243 * And, we hold the the proc_list_lock at this point.
5244 */
5245
5246 next_p = memorystatus_get_first_proc_locked(&i, FALSE);
5247 }
5248
5249 proc_list_unlock();
5250
5251 exit:
5252 os_reason_free(jetsam_reason);
5253
5254 /* Clear snapshot if freshly captured and no target was found */
5255 if (new_snapshot && (kill_count == 0)) {
5256 proc_list_lock();
5257 memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
5258 proc_list_unlock();
5259 }
5260
5261 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
5262 memorystatus_available_pages, killed ? aPid : 0, kill_count, 0, 0);
5263
5264 return (killed);
5265 }
5266
5267 static boolean_t
5268 memorystatus_kill_process_async(pid_t victim_pid, uint32_t cause) {
5269 /*
5270 * TODO: allow a general async path
5271 *
5272 * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
5273 * add the appropriate exit reason code mapping.
5274 */
5275 if ((victim_pid != -1) || (cause != kMemorystatusKilledVMPageShortage && cause != kMemorystatusKilledVMThrashing &&
5276 cause != kMemorystatusKilledFCThrashing)) {
5277 return FALSE;
5278 }
5279
5280 kill_under_pressure_cause = cause;
5281 memorystatus_thread_wake();
5282 return TRUE;
5283 }
5284
5285 boolean_t
5286 memorystatus_kill_on_VM_page_shortage(boolean_t async) {
5287 if (async) {
5288 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage);
5289 } else {
5290 os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMPAGESHORTAGE);
5291 if (jetsam_reason == OS_REASON_NULL) {
5292 printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
5293 }
5294
5295 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage, jetsam_reason);
5296 }
5297 }
5298
5299 boolean_t
5300 memorystatus_kill_on_VM_thrashing(boolean_t async) {
5301 if (async) {
5302 return memorystatus_kill_process_async(-1, kMemorystatusKilledVMThrashing);
5303 } else {
5304 os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMTHRASHING);
5305 if (jetsam_reason == OS_REASON_NULL) {
5306 printf("memorystatus_kill_on_VM_thrashing -- sync: failed to allocate jetsam reason\n");
5307 }
5308
5309 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMThrashing, jetsam_reason);
5310 }
5311 }
5312
5313 boolean_t
5314 memorystatus_kill_on_FC_thrashing(boolean_t async) {
5315
5316
5317 if (async) {
5318 return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing);
5319 } else {
5320 os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_FCTHRASHING);
5321 if (jetsam_reason == OS_REASON_NULL) {
5322 printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
5323 }
5324
5325 return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing, jetsam_reason);
5326 }
5327 }
5328
5329 boolean_t
5330 memorystatus_kill_on_vnode_limit(void) {
5331 os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_VNODE);
5332 if (jetsam_reason == OS_REASON_NULL) {
5333 printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
5334 }
5335
5336 return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes, jetsam_reason);
5337 }
5338
5339 #endif /* CONFIG_JETSAM */
5340
5341 #if CONFIG_FREEZE
5342
5343 __private_extern__ void
5344 memorystatus_freeze_init(void)
5345 {
5346 kern_return_t result;
5347 thread_t thread;
5348
5349 freezer_lck_grp_attr = lck_grp_attr_alloc_init();
5350 freezer_lck_grp = lck_grp_alloc_init("freezer", freezer_lck_grp_attr);
5351
5352 lck_mtx_init(&freezer_mutex, freezer_lck_grp, NULL);
5353
5354 result = kernel_thread_start(memorystatus_freeze_thread, NULL, &thread);
5355 if (result == KERN_SUCCESS) {
5356 thread_deallocate(thread);
5357 } else {
5358 panic("Could not create memorystatus_freeze_thread");
5359 }
5360 }
5361
5362 /*
5363 * Synchronously freeze the passed proc. Called with a reference to the proc held.
5364 *
5365 * Returns EINVAL or the value returned by task_freeze().
5366 */
5367 int
5368 memorystatus_freeze_process_sync(proc_t p)
5369 {
5370 int ret = EINVAL;
5371 pid_t aPid = 0;
5372 boolean_t memorystatus_freeze_swap_low = FALSE;
5373
5374 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_FREEZE) | DBG_FUNC_START,
5375 memorystatus_available_pages, 0, 0, 0, 0);
5376
5377 lck_mtx_lock(&freezer_mutex);
5378
5379 if (p == NULL) {
5380 goto exit;
5381 }
5382
5383 if (memorystatus_freeze_enabled == FALSE) {
5384 goto exit;
5385 }
5386
5387 if (!memorystatus_can_freeze(&memorystatus_freeze_swap_low)) {
5388 goto exit;
5389 }
5390
5391 if (memorystatus_freeze_update_throttle()) {
5392 printf("memorystatus_freeze_process_sync: in throttle, ignorning freeze\n");
5393 memorystatus_freeze_throttle_count++;
5394 goto exit;
5395 }
5396
5397 proc_list_lock();
5398
5399 if (p != NULL) {
5400 uint32_t purgeable, wired, clean, dirty, state;
5401 uint32_t max_pages, pages, i;
5402 boolean_t shared;
5403
5404 aPid = p->p_pid;
5405 state = p->p_memstat_state;
5406
5407 /* Ensure the process is eligible for freezing */
5408 if ((state & (P_MEMSTAT_TERMINATED | P_MEMSTAT_LOCKED | P_MEMSTAT_FROZEN)) || !(state & P_MEMSTAT_SUSPENDED)) {
5409 proc_list_unlock();
5410 goto exit;
5411 }
5412
5413 /* Only freeze processes meeting our minimum resident page criteria */
5414 memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL, NULL);
5415 if (pages < memorystatus_freeze_pages_min) {
5416 proc_list_unlock();
5417 goto exit;
5418 }
5419
5420 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5421
5422 unsigned int avail_swap_space = 0; /* in pages. */
5423
5424 /*
5425 * Freezer backed by the compressor and swap file(s)
5426 * while will hold compressed data.
5427 */
5428 avail_swap_space = vm_swap_get_free_space() / PAGE_SIZE_64;
5429
5430 max_pages = MIN(avail_swap_space, memorystatus_freeze_pages_max);
5431
5432 if (max_pages < memorystatus_freeze_pages_min) {
5433 proc_list_unlock();
5434 goto exit;
5435 }
5436 } else {
5437 /*
5438 * We only have the compressor without any swap.
5439 */
5440 max_pages = UINT32_MAX - 1;
5441 }
5442
5443 /* Mark as locked temporarily to avoid kill */
5444 p->p_memstat_state |= P_MEMSTAT_LOCKED;
5445 proc_list_unlock();
5446
5447 ret = task_freeze(p->task, &purgeable, &wired, &clean, &dirty, max_pages, &shared, FALSE);
5448
5449 DTRACE_MEMORYSTATUS6(memorystatus_freeze, proc_t, p, unsigned int, memorystatus_available_pages, boolean_t, purgeable, unsigned int, wired, uint32_t, clean, uint32_t, dirty);
5450
5451 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_process_sync: task_freeze %s for pid %d [%s] - "
5452 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5453 (ret == KERN_SUCCESS) ? "SUCCEEDED" : "FAILED", aPid, (*p->p_name ? p->p_name : "(unknown)"),
5454 memorystatus_available_pages, purgeable, wired, clean, dirty, max_pages, shared);
5455
5456 proc_list_lock();
5457 p->p_memstat_state &= ~P_MEMSTAT_LOCKED;
5458
5459 if (ret == KERN_SUCCESS) {
5460 memorystatus_freeze_entry_t data = { aPid, TRUE, dirty };
5461
5462 memorystatus_frozen_count++;
5463
5464 p->p_memstat_state |= (P_MEMSTAT_FROZEN | (shared ? 0: P_MEMSTAT_NORECLAIM));
5465
5466 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5467 /* Update stats */
5468 for (i = 0; i < sizeof(throttle_intervals) / sizeof(struct throttle_interval_t); i++) {
5469 throttle_intervals[i].pageouts += dirty;
5470 }
5471 }
5472
5473 memorystatus_freeze_pageouts += dirty;
5474 memorystatus_freeze_count++;
5475
5476 proc_list_unlock();
5477
5478 memorystatus_send_note(kMemorystatusFreezeNote, &data, sizeof(data));
5479 } else {
5480 proc_list_unlock();
5481 }
5482 }
5483
5484 exit:
5485 lck_mtx_unlock(&freezer_mutex);
5486 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_FREEZE) | DBG_FUNC_END,
5487 memorystatus_available_pages, aPid, 0, 0, 0);
5488
5489 return ret;
5490 }
5491
5492 static int
5493 memorystatus_freeze_top_process(boolean_t *memorystatus_freeze_swap_low)
5494 {
5495 pid_t aPid = 0;
5496 int ret = -1;
5497 proc_t p = PROC_NULL, next_p = PROC_NULL;
5498 unsigned int i = 0;
5499
5500 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_FREEZE) | DBG_FUNC_START,
5501 memorystatus_available_pages, 0, 0, 0, 0);
5502
5503 proc_list_lock();
5504
5505 next_p = memorystatus_get_first_proc_locked(&i, TRUE);
5506 while (next_p) {
5507 kern_return_t kr;
5508 uint32_t purgeable, wired, clean, dirty;
5509 boolean_t shared;
5510 uint32_t pages;
5511 uint32_t max_pages = 0;
5512 uint32_t state;
5513
5514 p = next_p;
5515 next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
5516
5517 aPid = p->p_pid;
5518 state = p->p_memstat_state;
5519
5520 /* Ensure the process is eligible for freezing */
5521 if ((state & (P_MEMSTAT_TERMINATED | P_MEMSTAT_LOCKED | P_MEMSTAT_FROZEN)) || !(state & P_MEMSTAT_SUSPENDED)) {
5522 continue; // with lock held
5523 }
5524
5525 /* Only freeze processes meeting our minimum resident page criteria */
5526 memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL, NULL);
5527 if (pages < memorystatus_freeze_pages_min) {
5528 continue; // with lock held
5529 }
5530
5531 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5532
5533 /* Ensure there's enough free space to freeze this process. */
5534
5535 unsigned int avail_swap_space = 0; /* in pages. */
5536
5537 /*
5538 * Freezer backed by the compressor and swap file(s)
5539 * while will hold compressed data.
5540 */
5541 avail_swap_space = vm_swap_get_free_space() / PAGE_SIZE_64;
5542
5543 max_pages = MIN(avail_swap_space, memorystatus_freeze_pages_max);
5544
5545 if (max_pages < memorystatus_freeze_pages_min) {
5546 *memorystatus_freeze_swap_low = TRUE;
5547 proc_list_unlock();
5548 goto exit;
5549 }
5550 } else {
5551 /*
5552 * We only have the compressor pool.
5553 */
5554 max_pages = UINT32_MAX - 1;
5555 }
5556
5557 /* Mark as locked temporarily to avoid kill */
5558 p->p_memstat_state |= P_MEMSTAT_LOCKED;
5559
5560 p = proc_ref_locked(p);
5561 proc_list_unlock();
5562 if (!p) {
5563 goto exit;
5564 }
5565
5566 kr = task_freeze(p->task, &purgeable, &wired, &clean, &dirty, max_pages, &shared, FALSE);
5567
5568 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_top_process: task_freeze %s for pid %d [%s] - "
5569 "memorystatus_pages: %d, purgeable: %d, wired: %d, clean: %d, dirty: %d, max_pages %d, shared %d\n",
5570 (kr == KERN_SUCCESS) ? "SUCCEEDED" : "FAILED", aPid, (*p->p_name ? p->p_name : "(unknown)"),
5571 memorystatus_available_pages, purgeable, wired, clean, dirty, max_pages, shared);
5572
5573 proc_list_lock();
5574 p->p_memstat_state &= ~P_MEMSTAT_LOCKED;
5575
5576 /* Success? */
5577 if (KERN_SUCCESS == kr) {
5578 memorystatus_freeze_entry_t data = { aPid, TRUE, dirty };
5579
5580 memorystatus_frozen_count++;
5581
5582 p->p_memstat_state |= (P_MEMSTAT_FROZEN | (shared ? 0: P_MEMSTAT_NORECLAIM));
5583
5584 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5585 /* Update stats */
5586 for (i = 0; i < sizeof(throttle_intervals) / sizeof(struct throttle_interval_t); i++) {
5587 throttle_intervals[i].pageouts += dirty;
5588 }
5589 }
5590
5591 memorystatus_freeze_pageouts += dirty;
5592 memorystatus_freeze_count++;
5593
5594 proc_list_unlock();
5595
5596 memorystatus_send_note(kMemorystatusFreezeNote, &data, sizeof(data));
5597
5598 /* Return KERN_SUCESS */
5599 ret = kr;
5600
5601 } else {
5602 proc_list_unlock();
5603 }
5604
5605 proc_rele(p);
5606 goto exit;
5607 }
5608
5609 proc_list_unlock();
5610
5611 exit:
5612 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_FREEZE) | DBG_FUNC_END,
5613 memorystatus_available_pages, aPid, 0, 0, 0);
5614
5615 return ret;
5616 }
5617
5618 static inline boolean_t
5619 memorystatus_can_freeze_processes(void)
5620 {
5621 boolean_t ret;
5622
5623 proc_list_lock();
5624
5625 if (memorystatus_suspended_count) {
5626 uint32_t average_resident_pages, estimated_processes;
5627
5628 /* Estimate the number of suspended processes we can fit */
5629 average_resident_pages = memorystatus_suspended_footprint_total / memorystatus_suspended_count;
5630 estimated_processes = memorystatus_suspended_count +
5631 ((memorystatus_available_pages - memorystatus_available_pages_critical) / average_resident_pages);
5632
5633 /* If it's predicted that no freeze will occur, lower the threshold temporarily */
5634 if (estimated_processes <= FREEZE_SUSPENDED_THRESHOLD_DEFAULT) {
5635 memorystatus_freeze_suspended_threshold = FREEZE_SUSPENDED_THRESHOLD_LOW;
5636 } else {
5637 memorystatus_freeze_suspended_threshold = FREEZE_SUSPENDED_THRESHOLD_DEFAULT;
5638 }
5639
5640 MEMORYSTATUS_DEBUG(1, "memorystatus_can_freeze_processes: %d suspended processes, %d average resident pages / process, %d suspended processes estimated\n",
5641 memorystatus_suspended_count, average_resident_pages, estimated_processes);
5642
5643 if ((memorystatus_suspended_count - memorystatus_frozen_count) > memorystatus_freeze_suspended_threshold) {
5644 ret = TRUE;
5645 } else {
5646 ret = FALSE;
5647 }
5648 } else {
5649 ret = FALSE;
5650 }
5651
5652 proc_list_unlock();
5653
5654 return ret;
5655 }
5656
5657 static boolean_t
5658 memorystatus_can_freeze(boolean_t *memorystatus_freeze_swap_low)
5659 {
5660 boolean_t can_freeze = TRUE;
5661
5662 /* Only freeze if we're sufficiently low on memory; this holds off freeze right
5663 after boot, and is generally is a no-op once we've reached steady state. */
5664 if (memorystatus_available_pages > memorystatus_freeze_threshold) {
5665 return FALSE;
5666 }
5667
5668 /* Check minimum suspended process threshold. */
5669 if (!memorystatus_can_freeze_processes()) {
5670 return FALSE;
5671 }
5672 assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
5673
5674 if ( !VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
5675 /*
5676 * In-core compressor used for freezing WITHOUT on-disk swap support.
5677 */
5678 if (vm_compressor_low_on_space()) {
5679 if (*memorystatus_freeze_swap_low) {
5680 *memorystatus_freeze_swap_low = TRUE;
5681 }
5682
5683 can_freeze = FALSE;
5684
5685 } else {
5686 if (*memorystatus_freeze_swap_low) {
5687 *memorystatus_freeze_swap_low = FALSE;
5688 }
5689
5690 can_freeze = TRUE;
5691 }
5692 } else {
5693 /*
5694 * Freezing WITH on-disk swap support.
5695 *
5696 * In-core compressor fronts the swap.
5697 */
5698 if (vm_swap_low_on_space()) {
5699 if (*memorystatus_freeze_swap_low) {
5700 *memorystatus_freeze_swap_low = TRUE;
5701 }
5702
5703 can_freeze = FALSE;
5704 }
5705
5706 }
5707
5708 return can_freeze;
5709 }
5710
5711 static void
5712 memorystatus_freeze_update_throttle_interval(mach_timespec_t *ts, struct throttle_interval_t *interval)
5713 {
5714 unsigned int freeze_daily_pageouts_max = memorystatus_freeze_daily_mb_max * (1024 * 1024 / PAGE_SIZE);
5715 if (CMP_MACH_TIMESPEC(ts, &interval->ts) >= 0) {
5716 if (!interval->max_pageouts) {
5717 interval->max_pageouts = (interval->burst_multiple * (((uint64_t)interval->mins * freeze_daily_pageouts_max) / (24 * 60)));
5718 } else {
5719 printf("memorystatus_freeze_update_throttle_interval: %d minute throttle timeout, resetting\n", interval->mins);
5720 }
5721 interval->ts.tv_sec = interval->mins * 60;
5722 interval->ts.tv_nsec = 0;
5723 ADD_MACH_TIMESPEC(&interval->ts, ts);
5724 /* Since we update the throttle stats pre-freeze, adjust for overshoot here */
5725 if (interval->pageouts > interval->max_pageouts) {
5726 interval->pageouts -= interval->max_pageouts;
5727 } else {
5728 interval->pageouts = 0;
5729 }
5730 interval->throttle = FALSE;
5731 } else if (!interval->throttle && interval->pageouts >= interval->max_pageouts) {
5732 printf("memorystatus_freeze_update_throttle_interval: %d minute pageout limit exceeded; enabling throttle\n", interval->mins);
5733 interval->throttle = TRUE;
5734 }
5735
5736 MEMORYSTATUS_DEBUG(1, "memorystatus_freeze_update_throttle_interval: throttle updated - %d frozen (%d max) within %dm; %dm remaining; throttle %s\n",
5737 interval->pageouts, interval->max_pageouts, interval->mins, (interval->ts.tv_sec - ts->tv_sec) / 60,
5738 interval->throttle ? "on" : "off");
5739 }
5740
5741 static boolean_t
5742 memorystatus_freeze_update_throttle(void)
5743 {
5744 clock_sec_t sec;
5745 clock_nsec_t nsec;
5746 mach_timespec_t ts;
5747 uint32_t i;
5748 boolean_t throttled = FALSE;
5749
5750 #if DEVELOPMENT || DEBUG
5751 if (!memorystatus_freeze_throttle_enabled)
5752 return FALSE;
5753 #endif
5754
5755 clock_get_system_nanotime(&sec, &nsec);
5756 ts.tv_sec = sec;
5757 ts.tv_nsec = nsec;
5758
5759 /* Check freeze pageouts over multiple intervals and throttle if we've exceeded our budget.
5760 *
5761 * This ensures that periods of inactivity can't be used as 'credit' towards freeze if the device has
5762 * remained dormant for a long period. We do, however, allow increased thresholds for shorter intervals in
5763 * order to allow for bursts of activity.
5764 */
5765 for (i = 0; i < sizeof(throttle_intervals) / sizeof(struct throttle_interval_t); i++) {
5766 memorystatus_freeze_update_throttle_interval(&ts, &throttle_intervals[i]);
5767 if (throttle_intervals[i].throttle == TRUE)
5768 throttled = TRUE;
5769 }
5770
5771 return throttled;
5772 }
5773
5774 static void
5775 memorystatus_freeze_thread(void *param __unused, wait_result_t wr __unused)
5776 {
5777 static boolean_t memorystatus_freeze_swap_low = FALSE;
5778
5779 lck_mtx_lock(&freezer_mutex);
5780 if (memorystatus_freeze_enabled) {
5781 if (memorystatus_can_freeze(&memorystatus_freeze_swap_low)) {
5782 /* Only freeze if we've not exceeded our pageout budgets.*/
5783 if (!memorystatus_freeze_update_throttle()) {
5784 memorystatus_freeze_top_process(&memorystatus_freeze_swap_low);
5785 } else {
5786 printf("memorystatus_freeze_thread: in throttle, ignoring freeze\n");
5787 memorystatus_freeze_throttle_count++; /* Throttled, update stats */
5788 }
5789 }
5790 }
5791 lck_mtx_unlock(&freezer_mutex);
5792
5793 assert_wait((event_t) &memorystatus_freeze_wakeup, THREAD_UNINT);
5794 thread_block((thread_continue_t) memorystatus_freeze_thread);
5795 }
5796
5797 static int
5798 sysctl_memorystatus_do_fastwake_warmup_all SYSCTL_HANDLER_ARGS
5799 {
5800 #pragma unused(oidp, req, arg1, arg2)
5801
5802 /* Need to be root or have entitlement */
5803 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT)) {
5804 return EPERM;
5805 }
5806
5807 if (memorystatus_freeze_enabled == FALSE) {
5808 return ENOTSUP;
5809 }
5810
5811 do_fastwake_warmup_all();
5812
5813 return 0;
5814 }
5815
5816 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_do_fastwake_warmup_all, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
5817 0, 0, &sysctl_memorystatus_do_fastwake_warmup_all, "I", "");
5818
5819 #endif /* CONFIG_FREEZE */
5820
5821 #if VM_PRESSURE_EVENTS
5822
5823 #if CONFIG_MEMORYSTATUS
5824
5825 static int
5826 memorystatus_send_note(int event_code, void *data, size_t data_length) {
5827 int ret;
5828 struct kev_msg ev_msg;
5829
5830 ev_msg.vendor_code = KEV_VENDOR_APPLE;
5831 ev_msg.kev_class = KEV_SYSTEM_CLASS;
5832 ev_msg.kev_subclass = KEV_MEMORYSTATUS_SUBCLASS;
5833
5834 ev_msg.event_code = event_code;
5835
5836 ev_msg.dv[0].data_length = data_length;
5837 ev_msg.dv[0].data_ptr = data;
5838 ev_msg.dv[1].data_length = 0;
5839
5840 ret = kev_post_msg(&ev_msg);
5841 if (ret) {
5842 printf("%s: kev_post_msg() failed, err %d\n", __func__, ret);
5843 }
5844
5845 return ret;
5846 }
5847
5848 boolean_t
5849 memorystatus_warn_process(pid_t pid, __unused boolean_t is_active, __unused boolean_t is_fatal, boolean_t limit_exceeded) {
5850
5851 boolean_t ret = FALSE;
5852 boolean_t found_knote = FALSE;
5853 struct knote *kn = NULL;
5854 int send_knote_count = 0;
5855
5856 /*
5857 * See comment in sysctl_memorystatus_vm_pressure_send.
5858 */
5859
5860 memorystatus_klist_lock();
5861
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;
5865
5866 if (knote_pid == pid) {
5867 /*
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().
5874 */
5875
5876 if (!limit_exceeded) {
5877
5878 /*
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.
5882 *
5883 * If the limit is soft, however, limit this to one notification per
5884 * active/inactive limit (per each registered listener).
5885 */
5886
5887 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) {
5888 found_knote=TRUE;
5889 if (!is_fatal) {
5890 /*
5891 * Restrict proc_limit_warn notifications when
5892 * non-fatal (soft) limit is at play.
5893 */
5894 if (is_active) {
5895 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE) {
5896 /*
5897 * Mark this knote for delivery.
5898 */
5899 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_WARN;
5900 /*
5901 * And suppress it from future notifications.
5902 */
5903 kn->kn_sfflags &= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE;
5904 send_knote_count++;
5905 }
5906 } else {
5907 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE) {
5908 /*
5909 * Mark this knote for delivery.
5910 */
5911 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_WARN;
5912 /*
5913 * And suppress it from future notifications.
5914 */
5915 kn->kn_sfflags &= ~NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE;
5916 send_knote_count++;
5917 }
5918 }
5919 } else {
5920 /*
5921 * No restriction on proc_limit_warn notifications when
5922 * fatal (hard) limit is at play.
5923 */
5924 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_WARN;
5925 send_knote_count++;
5926 }
5927 }
5928 } else {
5929 /*
5930 * Send this notification when a process has exceeded a soft limit,
5931 */
5932
5933 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL) {
5934 found_knote = TRUE;
5935 if (!is_fatal) {
5936 /*
5937 * Restrict critical notifications for soft limits.
5938 */
5939
5940 if (is_active) {
5941 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE) {
5942 /*
5943 * Suppress future proc_limit_critical notifications
5944 * for the active soft limit.
5945 */
5946 kn->kn_sfflags &= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE;
5947 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL;
5948 send_knote_count++;
5949
5950 }
5951 } else {
5952 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE) {
5953 /*
5954 * Suppress future proc_limit_critical_notifications
5955 * for the inactive soft limit.
5956 */
5957 kn->kn_sfflags &= ~NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE;
5958 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL;
5959 send_knote_count++;
5960 }
5961 }
5962 } else {
5963 /*
5964 * We should never be trying to send a critical notification for
5965 * a hard limit... the process would be killed before it could be
5966 * received.
5967 */
5968 panic("Caught sending pid %d a critical warning for a fatal limit.\n", pid);
5969 }
5970 }
5971 }
5972 }
5973 }
5974
5975 if (found_knote) {
5976 if (send_knote_count > 0) {
5977 KNOTE(&memorystatus_klist, 0);
5978 }
5979 ret = TRUE;
5980 }
5981
5982 memorystatus_klist_unlock();
5983
5984 return ret;
5985 }
5986
5987 /*
5988 * Can only be set by the current task on itself.
5989 */
5990 int
5991 memorystatus_low_mem_privileged_listener(uint32_t op_flags)
5992 {
5993 boolean_t set_privilege = FALSE;
5994 /*
5995 * Need an entitlement check here?
5996 */
5997 if (op_flags == MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE) {
5998 set_privilege = TRUE;
5999 } else if (op_flags == MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE) {
6000 set_privilege = FALSE;
6001 } else {
6002 return EINVAL;
6003 }
6004
6005 return (task_low_mem_privileged_listener(current_task(), set_privilege, NULL));
6006 }
6007
6008 int
6009 memorystatus_send_pressure_note(pid_t pid) {
6010 MEMORYSTATUS_DEBUG(1, "memorystatus_send_pressure_note(): pid %d\n", pid);
6011 return memorystatus_send_note(kMemorystatusPressureNote, &pid, sizeof(pid));
6012 }
6013
6014 void
6015 memorystatus_send_low_swap_note(void) {
6016
6017 struct knote *kn = NULL;
6018
6019 memorystatus_klist_lock();
6020 SLIST_FOREACH(kn, &memorystatus_klist, kn_selnext) {
6021 /* We call is_knote_registered_modify_task_pressure_bits to check if the sfflags for the
6022 * current note contain NOTE_MEMORYSTATUS_LOW_SWAP. Once we find one note in the memorystatus_klist
6023 * that has the NOTE_MEMORYSTATUS_LOW_SWAP flags in its sfflags set, we call KNOTE with
6024 * kMemoryStatusLowSwap as the hint to process and update all knotes on the memorystatus_klist accordingly. */
6025 if (is_knote_registered_modify_task_pressure_bits(kn, NOTE_MEMORYSTATUS_LOW_SWAP, NULL, 0, 0) == TRUE) {
6026 KNOTE(&memorystatus_klist, kMemorystatusLowSwap);
6027 break;
6028 }
6029 }
6030
6031 memorystatus_klist_unlock();
6032 }
6033
6034 boolean_t
6035 memorystatus_bg_pressure_eligible(proc_t p) {
6036 boolean_t eligible = FALSE;
6037
6038 proc_list_lock();
6039
6040 MEMORYSTATUS_DEBUG(1, "memorystatus_bg_pressure_eligible: pid %d, state 0x%x\n", p->p_pid, p->p_memstat_state);
6041
6042 /* Foreground processes have already been dealt with at this point, so just test for eligibility */
6043 if (!(p->p_memstat_state & (P_MEMSTAT_TERMINATED | P_MEMSTAT_LOCKED | P_MEMSTAT_SUSPENDED | P_MEMSTAT_FROZEN))) {
6044 eligible = TRUE;
6045 }
6046
6047 proc_list_unlock();
6048
6049 return eligible;
6050 }
6051
6052 boolean_t
6053 memorystatus_is_foreground_locked(proc_t p) {
6054 return ((p->p_memstat_effectivepriority == JETSAM_PRIORITY_FOREGROUND) ||
6055 (p->p_memstat_effectivepriority == JETSAM_PRIORITY_FOREGROUND_SUPPORT));
6056 }
6057
6058 /*
6059 * This is meant for stackshot and kperf -- it does not take the proc_list_lock
6060 * to access the p_memstat_dirty field.
6061 */
6062 boolean_t
6063 memorystatus_proc_is_dirty_unsafe(void *v)
6064 {
6065 if (!v) {
6066 return FALSE;
6067 }
6068 proc_t p = (proc_t)v;
6069 return (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) != 0;
6070 }
6071
6072 #endif /* CONFIG_MEMORYSTATUS */
6073
6074 /*
6075 * Trigger levels to test the mechanism.
6076 * Can be used via a sysctl.
6077 */
6078 #define TEST_LOW_MEMORY_TRIGGER_ONE 1
6079 #define TEST_LOW_MEMORY_TRIGGER_ALL 2
6080 #define TEST_PURGEABLE_TRIGGER_ONE 3
6081 #define TEST_PURGEABLE_TRIGGER_ALL 4
6082 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE 5
6083 #define TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL 6
6084
6085 boolean_t memorystatus_manual_testing_on = FALSE;
6086 vm_pressure_level_t memorystatus_manual_testing_level = kVMPressureNormal;
6087
6088 extern struct knote *
6089 vm_pressure_select_optimal_candidate_to_notify(struct klist *, int, boolean_t);
6090
6091 /*
6092 * This value is the threshold that a process must meet to be considered for scavenging.
6093 */
6094 #define VM_PRESSURE_MINIMUM_RSIZE 10 /* MB */
6095
6096 #define VM_PRESSURE_NOTIFY_WAIT_PERIOD 10000 /* milliseconds */
6097
6098 #if DEBUG
6099 #define VM_PRESSURE_DEBUG(cond, format, ...) \
6100 do { \
6101 if (cond) { printf(format, ##__VA_ARGS__); } \
6102 } while(0)
6103 #else
6104 #define VM_PRESSURE_DEBUG(cond, format, ...)
6105 #endif
6106
6107 #define INTER_NOTIFICATION_DELAY (250000) /* .25 second */
6108
6109 void memorystatus_on_pageout_scan_end(void) {
6110 /* No-op */
6111 }
6112
6113 /*
6114 * kn_max - knote
6115 *
6116 * knote_pressure_level - to check if the knote is registered for this notification level.
6117 *
6118 * task - task whose bits we'll be modifying
6119 *
6120 * pressure_level_to_clear - if the task has been notified of this past level, clear that notification bit so that if/when we revert to that level, the task will be notified again.
6121 *
6122 * pressure_level_to_set - the task is about to be notified of this new level. Update the task's bit notification information appropriately.
6123 *
6124 */
6125
6126 boolean_t
6127 is_knote_registered_modify_task_pressure_bits(struct knote *kn_max, int knote_pressure_level, task_t task, vm_pressure_level_t pressure_level_to_clear, vm_pressure_level_t pressure_level_to_set)
6128 {
6129 if (kn_max->kn_sfflags & knote_pressure_level) {
6130
6131 if (pressure_level_to_clear && task_has_been_notified(task, pressure_level_to_clear) == TRUE) {
6132
6133 task_clear_has_been_notified(task, pressure_level_to_clear);
6134 }
6135
6136 task_mark_has_been_notified(task, pressure_level_to_set);
6137 return TRUE;
6138 }
6139
6140 return FALSE;
6141 }
6142
6143 void
6144 memorystatus_klist_reset_all_for_level(vm_pressure_level_t pressure_level_to_clear)
6145 {
6146 struct knote *kn = NULL;
6147
6148 memorystatus_klist_lock();
6149 SLIST_FOREACH(kn, &memorystatus_klist, kn_selnext) {
6150
6151 proc_t p = PROC_NULL;
6152 struct task* t = TASK_NULL;
6153
6154 p = knote_get_kq(kn)->kq_p;
6155 proc_list_lock();
6156 if (p != proc_ref_locked(p)) {
6157 p = PROC_NULL;
6158 proc_list_unlock();
6159 continue;
6160 }
6161 proc_list_unlock();
6162
6163 t = (struct task *)(p->task);
6164
6165 task_clear_has_been_notified(t, pressure_level_to_clear);
6166
6167 proc_rele(p);
6168 }
6169
6170 memorystatus_klist_unlock();
6171 }
6172
6173 extern kern_return_t vm_pressure_notify_dispatch_vm_clients(boolean_t target_foreground_process);
6174
6175 struct knote *
6176 vm_pressure_select_optimal_candidate_to_notify(struct klist *candidate_list, int level, boolean_t target_foreground_process);
6177
6178 /*
6179 * Used by the vm_pressure_thread which is
6180 * signalled from within vm_pageout_scan().
6181 */
6182 static void vm_dispatch_memory_pressure(void);
6183 void consider_vm_pressure_events(void);
6184
6185 void consider_vm_pressure_events(void)
6186 {
6187 vm_dispatch_memory_pressure();
6188 }
6189 static void vm_dispatch_memory_pressure(void)
6190 {
6191 memorystatus_update_vm_pressure(FALSE);
6192 }
6193
6194 extern vm_pressure_level_t
6195 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t);
6196
6197 struct knote *
6198 vm_pressure_select_optimal_candidate_to_notify(struct klist *candidate_list, int level, boolean_t target_foreground_process)
6199 {
6200 struct knote *kn = NULL, *kn_max = NULL;
6201 uint64_t resident_max = 0; /* MB */
6202 struct timeval curr_tstamp = {0, 0};
6203 int elapsed_msecs = 0;
6204 int selected_task_importance = 0;
6205 static int pressure_snapshot = -1;
6206 boolean_t pressure_increase = FALSE;
6207
6208 if (pressure_snapshot == -1) {
6209 /*
6210 * Initial snapshot.
6211 */
6212 pressure_snapshot = level;
6213 pressure_increase = TRUE;
6214 } else {
6215
6216 if (level >= pressure_snapshot) {
6217 pressure_increase = TRUE;
6218 } else {
6219 pressure_increase = FALSE;
6220 }
6221
6222 pressure_snapshot = level;
6223 }
6224
6225 if (pressure_increase == TRUE) {
6226 /*
6227 * We'll start by considering the largest
6228 * unimportant task in our list.
6229 */
6230 selected_task_importance = INT_MAX;
6231 } else {
6232 /*
6233 * We'll start by considering the largest
6234 * important task in our list.
6235 */
6236 selected_task_importance = 0;
6237 }
6238
6239 microuptime(&curr_tstamp);
6240
6241 SLIST_FOREACH(kn, candidate_list, kn_selnext) {
6242
6243 uint64_t resident_size = 0; /* MB */
6244 proc_t p = PROC_NULL;
6245 struct task* t = TASK_NULL;
6246 int curr_task_importance = 0;
6247 boolean_t consider_knote = FALSE;
6248 boolean_t privileged_listener = FALSE;
6249
6250 p = knote_get_kq(kn)->kq_p;
6251 proc_list_lock();
6252 if (p != proc_ref_locked(p)) {
6253 p = PROC_NULL;
6254 proc_list_unlock();
6255 continue;
6256 }
6257 proc_list_unlock();
6258
6259 #if CONFIG_MEMORYSTATUS
6260 if (target_foreground_process == TRUE && !memorystatus_is_foreground_locked(p)) {
6261 /*
6262 * Skip process not marked foreground.
6263 */
6264 proc_rele(p);
6265 continue;
6266 }
6267 #endif /* CONFIG_MEMORYSTATUS */
6268
6269 t = (struct task *)(p->task);
6270
6271 timevalsub(&curr_tstamp, &p->vm_pressure_last_notify_tstamp);
6272 elapsed_msecs = curr_tstamp.tv_sec * 1000 + curr_tstamp.tv_usec / 1000;
6273
6274 vm_pressure_level_t dispatch_level = convert_internal_pressure_level_to_dispatch_level(level);
6275
6276 if ((kn->kn_sfflags & dispatch_level) == 0) {
6277 proc_rele(p);
6278 continue;
6279 }
6280
6281 #if CONFIG_MEMORYSTATUS
6282 if (target_foreground_process == FALSE && !memorystatus_bg_pressure_eligible(p)) {
6283 VM_PRESSURE_DEBUG(1, "[vm_pressure] skipping process %d\n", p->p_pid);
6284 proc_rele(p);
6285 continue;
6286 }
6287 #endif /* CONFIG_MEMORYSTATUS */
6288
6289 curr_task_importance = task_importance_estimate(t);
6290
6291 /*
6292 * Privileged listeners are only considered in the multi-level pressure scheme
6293 * AND only if the pressure is increasing.
6294 */
6295 if (level > 0) {
6296
6297 if (task_has_been_notified(t, level) == FALSE) {
6298
6299 /*
6300 * Is this a privileged listener?
6301 */
6302 if (task_low_mem_privileged_listener(t, FALSE, &privileged_listener) == 0) {
6303
6304 if (privileged_listener) {
6305 kn_max = kn;
6306 proc_rele(p);
6307 goto done_scanning;
6308 }
6309 }
6310 } else {
6311 proc_rele(p);
6312 continue;
6313 }
6314 } else if (level == 0) {
6315
6316 /*
6317 * Task wasn't notified when the pressure was increasing and so
6318 * no need to notify it that the pressure is decreasing.
6319 */
6320 if ((task_has_been_notified(t, kVMPressureWarning) == FALSE) && (task_has_been_notified(t, kVMPressureCritical) == FALSE)) {
6321 proc_rele(p);
6322 continue;
6323 }
6324 }
6325
6326 /*
6327 * We don't want a small process to block large processes from
6328 * being notified again. <rdar://problem/7955532>
6329 */
6330 resident_size = (get_task_phys_footprint(t))/(1024*1024ULL); /* MB */
6331
6332 if (resident_size >= VM_PRESSURE_MINIMUM_RSIZE) {
6333
6334 if (level > 0) {
6335 /*
6336 * Warning or Critical Pressure.
6337 */
6338 if (pressure_increase) {
6339 if ((curr_task_importance < selected_task_importance) ||
6340 ((curr_task_importance == selected_task_importance) && (resident_size > resident_max))) {
6341
6342 /*
6343 * We have found a candidate process which is:
6344 * a) at a lower importance than the current selected process
6345 * OR
6346 * b) has importance equal to that of the current selected process but is larger
6347 */
6348
6349 consider_knote = TRUE;
6350 }
6351 } else {
6352 if ((curr_task_importance > selected_task_importance) ||
6353 ((curr_task_importance == selected_task_importance) && (resident_size > resident_max))) {
6354
6355 /*
6356 * We have found a candidate process which is:
6357 * a) at a higher importance than the current selected process
6358 * OR
6359 * b) has importance equal to that of the current selected process but is larger
6360 */
6361
6362 consider_knote = TRUE;
6363 }
6364 }
6365 } else if (level == 0) {
6366 /*
6367 * Pressure back to normal.
6368 */
6369 if ((curr_task_importance > selected_task_importance) ||
6370 ((curr_task_importance == selected_task_importance) && (resident_size > resident_max))) {
6371
6372 consider_knote = TRUE;
6373 }
6374 }
6375
6376 if (consider_knote) {
6377 resident_max = resident_size;
6378 kn_max = kn;
6379 selected_task_importance = curr_task_importance;
6380 consider_knote = FALSE; /* reset for the next candidate */
6381 }
6382 } else {
6383 /* There was no candidate with enough resident memory to scavenge */
6384 VM_PRESSURE_DEBUG(0, "[vm_pressure] threshold failed for pid %d with %llu resident...\n", p->p_pid, resident_size);
6385 }
6386 proc_rele(p);
6387 }
6388
6389 done_scanning:
6390 if (kn_max) {
6391 VM_DEBUG_CONSTANT_EVENT(vm_pressure_event, VM_PRESSURE_EVENT, DBG_FUNC_NONE, knote_get_kq(kn_max)->kq_p->p_pid, resident_max, 0, 0);
6392 VM_PRESSURE_DEBUG(1, "[vm_pressure] sending event to pid %d with %llu resident\n", knote_get_kq(kn_max)->kq_p->p_pid, resident_max);
6393 }
6394
6395 return kn_max;
6396 }
6397
6398 #define VM_PRESSURE_DECREASED_SMOOTHING_PERIOD 5000 /* milliseconds */
6399 #define WARNING_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6400 #define CRITICAL_NOTIFICATION_RESTING_PERIOD 25 /* seconds */
6401
6402 uint64_t next_warning_notification_sent_at_ts = 0;
6403 uint64_t next_critical_notification_sent_at_ts = 0;
6404
6405 kern_return_t
6406 memorystatus_update_vm_pressure(boolean_t target_foreground_process)
6407 {
6408 struct knote *kn_max = NULL;
6409 struct knote *kn_cur = NULL, *kn_temp = NULL; /* for safe list traversal */
6410 pid_t target_pid = -1;
6411 struct klist dispatch_klist = { NULL };
6412 proc_t target_proc = PROC_NULL;
6413 struct task *task = NULL;
6414 boolean_t found_candidate = FALSE;
6415
6416 static vm_pressure_level_t level_snapshot = kVMPressureNormal;
6417 static vm_pressure_level_t prev_level_snapshot = kVMPressureNormal;
6418 boolean_t smoothing_window_started = FALSE;
6419 struct timeval smoothing_window_start_tstamp = {0, 0};
6420 struct timeval curr_tstamp = {0, 0};
6421 int elapsed_msecs = 0;
6422 uint64_t curr_ts = mach_absolute_time();
6423
6424 #if !CONFIG_JETSAM
6425 #define MAX_IDLE_KILLS 100 /* limit the number of idle kills allowed */
6426
6427 int idle_kill_counter = 0;
6428
6429 /*
6430 * On desktop we take this opportunity to free up memory pressure
6431 * by immediately killing idle exitable processes. We use a delay
6432 * to avoid overkill. And we impose a max counter as a fail safe
6433 * in case daemons re-launch too fast.
6434 */
6435 while ((memorystatus_vm_pressure_level != kVMPressureNormal) && (idle_kill_counter < MAX_IDLE_KILLS)) {
6436 if (memorystatus_idle_exit_from_VM() == FALSE) {
6437 /* No idle exitable processes left to kill */
6438 break;
6439 }
6440 idle_kill_counter++;
6441
6442 if (memorystatus_manual_testing_on == TRUE) {
6443 /*
6444 * Skip the delay when testing
6445 * the pressure notification scheme.
6446 */
6447 } else {
6448 delay(1000000); /* 1 second */
6449 }
6450 }
6451 #endif /* !CONFIG_JETSAM */
6452
6453 if (level_snapshot != kVMPressureNormal) {
6454
6455 /*
6456 * Check to see if we are still in the 'resting' period
6457 * after having notified all clients interested in
6458 * a particular pressure level.
6459 */
6460
6461 level_snapshot = memorystatus_vm_pressure_level;
6462
6463 if (level_snapshot == kVMPressureWarning || level_snapshot == kVMPressureUrgent) {
6464
6465 if (curr_ts < next_warning_notification_sent_at_ts) {
6466 delay(INTER_NOTIFICATION_DELAY * 4 /* 1 sec */);
6467 return KERN_SUCCESS;
6468 }
6469 } else if (level_snapshot == kVMPressureCritical) {
6470
6471 if (curr_ts < next_critical_notification_sent_at_ts) {
6472 delay(INTER_NOTIFICATION_DELAY * 4 /* 1 sec */);
6473 return KERN_SUCCESS;
6474 }
6475 }
6476 }
6477
6478 while (1) {
6479
6480 /*
6481 * There is a race window here. But it's not clear
6482 * how much we benefit from having extra synchronization.
6483 */
6484 level_snapshot = memorystatus_vm_pressure_level;
6485
6486 if (prev_level_snapshot > level_snapshot) {
6487 /*
6488 * Pressure decreased? Let's take a little breather
6489 * and see if this condition stays.
6490 */
6491 if (smoothing_window_started == FALSE) {
6492
6493 smoothing_window_started = TRUE;
6494 microuptime(&smoothing_window_start_tstamp);
6495 }
6496
6497 microuptime(&curr_tstamp);
6498 timevalsub(&curr_tstamp, &smoothing_window_start_tstamp);
6499 elapsed_msecs = curr_tstamp.tv_sec * 1000 + curr_tstamp.tv_usec / 1000;
6500
6501 if (elapsed_msecs < VM_PRESSURE_DECREASED_SMOOTHING_PERIOD) {
6502
6503 delay(INTER_NOTIFICATION_DELAY);
6504 continue;
6505 }
6506 }
6507
6508 prev_level_snapshot = level_snapshot;
6509 smoothing_window_started = FALSE;
6510
6511 memorystatus_klist_lock();
6512 kn_max = vm_pressure_select_optimal_candidate_to_notify(&memorystatus_klist, level_snapshot, target_foreground_process);
6513
6514 if (kn_max == NULL) {
6515 memorystatus_klist_unlock();
6516
6517 /*
6518 * No more level-based clients to notify.
6519 *
6520 * Start the 'resting' window within which clients will not be re-notified.
6521 */
6522
6523 if (level_snapshot != kVMPressureNormal) {
6524 if (level_snapshot == kVMPressureWarning || level_snapshot == kVMPressureUrgent) {
6525 nanoseconds_to_absolutetime(WARNING_NOTIFICATION_RESTING_PERIOD * NSEC_PER_SEC, &curr_ts);
6526 next_warning_notification_sent_at_ts = mach_absolute_time() + curr_ts;
6527
6528 memorystatus_klist_reset_all_for_level(kVMPressureWarning);
6529 }
6530
6531 if (level_snapshot == kVMPressureCritical) {
6532 nanoseconds_to_absolutetime(CRITICAL_NOTIFICATION_RESTING_PERIOD * NSEC_PER_SEC, &curr_ts);
6533 next_critical_notification_sent_at_ts = mach_absolute_time() + curr_ts;
6534
6535 memorystatus_klist_reset_all_for_level(kVMPressureCritical);
6536 }
6537 }
6538 return KERN_FAILURE;
6539 }
6540
6541 target_proc = knote_get_kq(kn_max)->kq_p;
6542
6543 proc_list_lock();
6544 if (target_proc != proc_ref_locked(target_proc)) {
6545 target_proc = PROC_NULL;
6546 proc_list_unlock();
6547 memorystatus_klist_unlock();
6548 continue;
6549 }
6550 proc_list_unlock();
6551
6552 target_pid = target_proc->p_pid;
6553
6554 task = (struct task *)(target_proc->task);
6555
6556 if (level_snapshot != kVMPressureNormal) {
6557
6558 if (level_snapshot == kVMPressureWarning || level_snapshot == kVMPressureUrgent) {
6559
6560 if (is_knote_registered_modify_task_pressure_bits(kn_max, NOTE_MEMORYSTATUS_PRESSURE_WARN, task, 0, kVMPressureWarning) == TRUE) {
6561 found_candidate = TRUE;
6562 }
6563 } else {
6564 if (level_snapshot == kVMPressureCritical) {
6565
6566 if (is_knote_registered_modify_task_pressure_bits(kn_max, NOTE_MEMORYSTATUS_PRESSURE_CRITICAL, task, 0, kVMPressureCritical) == TRUE) {
6567 found_candidate = TRUE;
6568 }
6569 }
6570 }
6571 } else {
6572 if (kn_max->kn_sfflags & NOTE_MEMORYSTATUS_PRESSURE_NORMAL) {
6573
6574 task_clear_has_been_notified(task, kVMPressureWarning);
6575 task_clear_has_been_notified(task, kVMPressureCritical);
6576
6577 found_candidate = TRUE;
6578 }
6579 }
6580
6581 if (found_candidate == FALSE) {
6582 proc_rele(target_proc);
6583 memorystatus_klist_unlock();
6584 continue;
6585 }
6586
6587 SLIST_FOREACH_SAFE(kn_cur, &memorystatus_klist, kn_selnext, kn_temp) {
6588
6589 int knote_pressure_level = convert_internal_pressure_level_to_dispatch_level(level_snapshot);
6590
6591 if (is_knote_registered_modify_task_pressure_bits(kn_cur, knote_pressure_level, task, 0, level_snapshot) == TRUE) {
6592 proc_t knote_proc = knote_get_kq(kn_cur)->kq_p;
6593 pid_t knote_pid = knote_proc->p_pid;
6594 if (knote_pid == target_pid) {
6595 KNOTE_DETACH(&memorystatus_klist, kn_cur);
6596 KNOTE_ATTACH(&dispatch_klist, kn_cur);
6597 }
6598 }
6599 }
6600
6601 KNOTE(&dispatch_klist, (level_snapshot != kVMPressureNormal) ? kMemorystatusPressure : kMemorystatusNoPressure);
6602
6603 SLIST_FOREACH_SAFE(kn_cur, &dispatch_klist, kn_selnext, kn_temp) {
6604 KNOTE_DETACH(&dispatch_klist, kn_cur);
6605 KNOTE_ATTACH(&memorystatus_klist, kn_cur);
6606 }
6607
6608 memorystatus_klist_unlock();
6609
6610 microuptime(&target_proc->vm_pressure_last_notify_tstamp);
6611 proc_rele(target_proc);
6612
6613 if (memorystatus_manual_testing_on == TRUE && target_foreground_process == TRUE) {
6614 break;
6615 }
6616
6617 if (memorystatus_manual_testing_on == TRUE) {
6618 /*
6619 * Testing out the pressure notification scheme.
6620 * No need for delays etc.
6621 */
6622 } else {
6623
6624 uint32_t sleep_interval = INTER_NOTIFICATION_DELAY;
6625 #if CONFIG_JETSAM
6626 unsigned int page_delta = 0;
6627 unsigned int skip_delay_page_threshold = 0;
6628
6629 assert(memorystatus_available_pages_pressure >= memorystatus_available_pages_critical_base);
6630
6631 page_delta = (memorystatus_available_pages_pressure - memorystatus_available_pages_critical_base) / 2;
6632 skip_delay_page_threshold = memorystatus_available_pages_pressure - page_delta;
6633
6634 if (memorystatus_available_pages <= skip_delay_page_threshold) {
6635 /*
6636 * We are nearing the critcal mark fast and can't afford to wait between
6637 * notifications.
6638 */
6639 sleep_interval = 0;
6640 }
6641 #endif /* CONFIG_JETSAM */
6642
6643 if (sleep_interval) {
6644 delay(sleep_interval);
6645 }
6646 }
6647 }
6648
6649 return KERN_SUCCESS;
6650 }
6651
6652 vm_pressure_level_t
6653 convert_internal_pressure_level_to_dispatch_level(vm_pressure_level_t internal_pressure_level)
6654 {
6655 vm_pressure_level_t dispatch_level = NOTE_MEMORYSTATUS_PRESSURE_NORMAL;
6656
6657 switch (internal_pressure_level) {
6658
6659 case kVMPressureNormal:
6660 {
6661 dispatch_level = NOTE_MEMORYSTATUS_PRESSURE_NORMAL;
6662 break;
6663 }
6664
6665 case kVMPressureWarning:
6666 case kVMPressureUrgent:
6667 {
6668 dispatch_level = NOTE_MEMORYSTATUS_PRESSURE_WARN;
6669 break;
6670 }
6671
6672 case kVMPressureCritical:
6673 {
6674 dispatch_level = NOTE_MEMORYSTATUS_PRESSURE_CRITICAL;
6675 break;
6676 }
6677
6678 default:
6679 break;
6680 }
6681
6682 return dispatch_level;
6683 }
6684
6685 static int
6686 sysctl_memorystatus_vm_pressure_level SYSCTL_HANDLER_ARGS
6687 {
6688 #pragma unused(arg1, arg2, oidp)
6689 vm_pressure_level_t dispatch_level = convert_internal_pressure_level_to_dispatch_level(memorystatus_vm_pressure_level);
6690
6691 return SYSCTL_OUT(req, &dispatch_level, sizeof(dispatch_level));
6692 }
6693
6694 #if DEBUG || DEVELOPMENT
6695
6696 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_vm_pressure_level, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_LOCKED,
6697 0, 0, &sysctl_memorystatus_vm_pressure_level, "I", "");
6698
6699 #else /* DEBUG || DEVELOPMENT */
6700
6701 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_vm_pressure_level, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_LOCKED|CTLFLAG_MASKED,
6702 0, 0, &sysctl_memorystatus_vm_pressure_level, "I", "");
6703
6704 #endif /* DEBUG || DEVELOPMENT */
6705
6706 extern int memorystatus_purge_on_warning;
6707 extern int memorystatus_purge_on_critical;
6708
6709 static int
6710 sysctl_memorypressure_manual_trigger SYSCTL_HANDLER_ARGS
6711 {
6712 #pragma unused(arg1, arg2)
6713
6714 int level = 0;
6715 int error = 0;
6716 int pressure_level = 0;
6717 int trigger_request = 0;
6718 int force_purge;
6719
6720 error = sysctl_handle_int(oidp, &level, 0, req);
6721 if (error || !req->newptr) {
6722 return (error);
6723 }
6724
6725 memorystatus_manual_testing_on = TRUE;
6726
6727 trigger_request = (level >> 16) & 0xFFFF;
6728 pressure_level = (level & 0xFFFF);
6729
6730 if (trigger_request < TEST_LOW_MEMORY_TRIGGER_ONE ||
6731 trigger_request > TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL) {
6732 return EINVAL;
6733 }
6734 switch (pressure_level) {
6735 case NOTE_MEMORYSTATUS_PRESSURE_NORMAL:
6736 case NOTE_MEMORYSTATUS_PRESSURE_WARN:
6737 case NOTE_MEMORYSTATUS_PRESSURE_CRITICAL:
6738 break;
6739 default:
6740 return EINVAL;
6741 }
6742
6743 /*
6744 * The pressure level is being set from user-space.
6745 * And user-space uses the constants in sys/event.h
6746 * So we translate those events to our internal levels here.
6747 */
6748 if (pressure_level == NOTE_MEMORYSTATUS_PRESSURE_NORMAL) {
6749
6750 memorystatus_manual_testing_level = kVMPressureNormal;
6751 force_purge = 0;
6752
6753 } else if (pressure_level == NOTE_MEMORYSTATUS_PRESSURE_WARN) {
6754
6755 memorystatus_manual_testing_level = kVMPressureWarning;
6756 force_purge = memorystatus_purge_on_warning;
6757
6758 } else if (pressure_level == NOTE_MEMORYSTATUS_PRESSURE_CRITICAL) {
6759
6760 memorystatus_manual_testing_level = kVMPressureCritical;
6761 force_purge = memorystatus_purge_on_critical;
6762 }
6763
6764 memorystatus_vm_pressure_level = memorystatus_manual_testing_level;
6765
6766 /* purge according to the new pressure level */
6767 switch (trigger_request) {
6768 case TEST_PURGEABLE_TRIGGER_ONE:
6769 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE:
6770 if (force_purge == 0) {
6771 /* no purging requested */
6772 break;
6773 }
6774 vm_purgeable_object_purge_one_unlocked(force_purge);
6775 break;
6776 case TEST_PURGEABLE_TRIGGER_ALL:
6777 case TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL:
6778 if (force_purge == 0) {
6779 /* no purging requested */
6780 break;
6781 }
6782 while (vm_purgeable_object_purge_one_unlocked(force_purge));
6783 break;
6784 }
6785
6786 if ((trigger_request == TEST_LOW_MEMORY_TRIGGER_ONE) ||
6787 (trigger_request == TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ONE)) {
6788
6789 memorystatus_update_vm_pressure(TRUE);
6790 }
6791
6792 if ((trigger_request == TEST_LOW_MEMORY_TRIGGER_ALL) ||
6793 (trigger_request == TEST_LOW_MEMORY_PURGEABLE_TRIGGER_ALL)) {
6794
6795 while (memorystatus_update_vm_pressure(FALSE) == KERN_SUCCESS) {
6796 continue;
6797 }
6798 }
6799
6800 if (pressure_level == NOTE_MEMORYSTATUS_PRESSURE_NORMAL) {
6801 memorystatus_manual_testing_on = FALSE;
6802 }
6803
6804 return 0;
6805 }
6806
6807 SYSCTL_PROC(_kern, OID_AUTO, memorypressure_manual_trigger, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
6808 0, 0, &sysctl_memorypressure_manual_trigger, "I", "");
6809
6810
6811 extern int memorystatus_purge_on_warning;
6812 extern int memorystatus_purge_on_urgent;
6813 extern int memorystatus_purge_on_critical;
6814
6815 SYSCTL_INT(_kern, OID_AUTO, memorystatus_purge_on_warning, CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_purge_on_warning, 0, "");
6816 SYSCTL_INT(_kern, OID_AUTO, memorystatus_purge_on_urgent, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_purge_on_urgent, 0, "");
6817 SYSCTL_INT(_kern, OID_AUTO, memorystatus_purge_on_critical, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_LOCKED, &memorystatus_purge_on_critical, 0, "");
6818
6819
6820 #endif /* VM_PRESSURE_EVENTS */
6821
6822 /* Return both allocated and actual size, since there's a race between allocation and list compilation */
6823 static int
6824 memorystatus_get_priority_list(memorystatus_priority_entry_t **list_ptr, size_t *buffer_size, size_t *list_size, boolean_t size_only)
6825 {
6826 uint32_t list_count, i = 0;
6827 memorystatus_priority_entry_t *list_entry;
6828 proc_t p;
6829
6830 list_count = memorystatus_list_count;
6831 *list_size = sizeof(memorystatus_priority_entry_t) * list_count;
6832
6833 /* Just a size check? */
6834 if (size_only) {
6835 return 0;
6836 }
6837
6838 /* Otherwise, validate the size of the buffer */
6839 if (*buffer_size < *list_size) {
6840 return EINVAL;
6841 }
6842
6843 *list_ptr = (memorystatus_priority_entry_t*)kalloc(*list_size);
6844 if (!list_ptr) {
6845 return ENOMEM;
6846 }
6847
6848 memset(*list_ptr, 0, *list_size);
6849
6850 *buffer_size = *list_size;
6851 *list_size = 0;
6852
6853 list_entry = *list_ptr;
6854
6855 proc_list_lock();
6856
6857 p = memorystatus_get_first_proc_locked(&i, TRUE);
6858 while (p && (*list_size < *buffer_size)) {
6859 list_entry->pid = p->p_pid;
6860 list_entry->priority = p->p_memstat_effectivepriority;
6861 list_entry->user_data = p->p_memstat_userdata;
6862
6863 /*
6864 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
6865 * Background limits are described via the inactive limit slots.
6866 * So, here, the cached limit should always be valid.
6867 */
6868
6869 if (p->p_memstat_memlimit <= 0) {
6870 task_get_phys_footprint_limit(p->task, &list_entry->limit);
6871 } else {
6872 list_entry->limit = p->p_memstat_memlimit;
6873 }
6874
6875 list_entry->state = memorystatus_build_state(p);
6876 list_entry++;
6877
6878 *list_size += sizeof(memorystatus_priority_entry_t);
6879
6880 p = memorystatus_get_next_proc_locked(&i, p, TRUE);
6881 }
6882
6883 proc_list_unlock();
6884
6885 MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size);
6886
6887 return 0;
6888 }
6889
6890 static int
6891 memorystatus_cmd_get_priority_list(user_addr_t buffer, size_t buffer_size, int32_t *retval) {
6892 int error = EINVAL;
6893 boolean_t size_only;
6894 memorystatus_priority_entry_t *list = NULL;
6895 size_t list_size;
6896
6897 size_only = ((buffer == USER_ADDR_NULL) ? TRUE: FALSE);
6898
6899 error = memorystatus_get_priority_list(&list, &buffer_size, &list_size, size_only);
6900 if (error) {
6901 goto out;
6902 }
6903
6904 if (!size_only) {
6905 error = copyout(list, buffer, list_size);
6906 }
6907
6908 if (error == 0) {
6909 *retval = list_size;
6910 }
6911 out:
6912
6913 if (list) {
6914 kfree(list, buffer_size);
6915 }
6916
6917 return error;
6918 }
6919
6920 #if CONFIG_JETSAM
6921
6922 static void
6923 memorystatus_clear_errors(void)
6924 {
6925 proc_t p;
6926 unsigned int i = 0;
6927
6928 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_START, 0, 0, 0, 0, 0);
6929
6930 proc_list_lock();
6931
6932 p = memorystatus_get_first_proc_locked(&i, TRUE);
6933 while (p) {
6934 if (p->p_memstat_state & P_MEMSTAT_ERROR) {
6935 p->p_memstat_state &= ~P_MEMSTAT_ERROR;
6936 }
6937 p = memorystatus_get_next_proc_locked(&i, p, TRUE);
6938 }
6939
6940 proc_list_unlock();
6941
6942 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_END, 0, 0, 0, 0, 0);
6943 }
6944
6945 static void
6946 memorystatus_update_levels_locked(boolean_t critical_only) {
6947
6948 memorystatus_available_pages_critical = memorystatus_available_pages_critical_base;
6949
6950 /*
6951 * If there's an entry in the first bucket, we have idle processes.
6952 */
6953
6954 memstat_bucket_t *first_bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
6955 if (first_bucket->count) {
6956 memorystatus_available_pages_critical += memorystatus_available_pages_critical_idle_offset;
6957
6958 if (memorystatus_available_pages_critical > memorystatus_available_pages_pressure ) {
6959 /*
6960 * The critical threshold must never exceed the pressure threshold
6961 */
6962 memorystatus_available_pages_critical = memorystatus_available_pages_pressure;
6963 }
6964 }
6965
6966 #if DEBUG || DEVELOPMENT
6967 if (memorystatus_jetsam_policy & kPolicyDiagnoseActive) {
6968 memorystatus_available_pages_critical += memorystatus_jetsam_policy_offset_pages_diagnostic;
6969
6970 if (memorystatus_available_pages_critical > memorystatus_available_pages_pressure ) {
6971 /*
6972 * The critical threshold must never exceed the pressure threshold
6973 */
6974 memorystatus_available_pages_critical = memorystatus_available_pages_pressure;
6975 }
6976 }
6977 #endif
6978
6979 if (memorystatus_jetsam_policy & kPolicyMoreFree) {
6980 memorystatus_available_pages_critical += memorystatus_policy_more_free_offset_pages;
6981 }
6982
6983 if (critical_only) {
6984 return;
6985 }
6986
6987 #if VM_PRESSURE_EVENTS
6988 memorystatus_available_pages_pressure = (pressure_threshold_percentage / delta_percentage) * memorystatus_delta;
6989 #if DEBUG || DEVELOPMENT
6990 if (memorystatus_jetsam_policy & kPolicyDiagnoseActive) {
6991 memorystatus_available_pages_pressure += memorystatus_jetsam_policy_offset_pages_diagnostic;
6992 }
6993 #endif
6994 #endif
6995 }
6996
6997 static int
6998 sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
6999 {
7000 #pragma unused(arg1, arg2, oidp)
7001 int error = 0, more_free = 0;
7002
7003 /*
7004 * TODO: Enable this privilege check?
7005 *
7006 * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
7007 * if (error)
7008 * return (error);
7009 */
7010
7011 error = sysctl_handle_int(oidp, &more_free, 0, req);
7012 if (error || !req->newptr)
7013 return (error);
7014
7015 if ((more_free && ((memorystatus_jetsam_policy & kPolicyMoreFree) == kPolicyMoreFree)) ||
7016 (!more_free && ((memorystatus_jetsam_policy & kPolicyMoreFree) == 0))) {
7017
7018 /*
7019 * No change in state.
7020 */
7021 return 0;
7022 }
7023
7024 proc_list_lock();
7025
7026 if (more_free) {
7027 memorystatus_jetsam_policy |= kPolicyMoreFree;
7028 } else {
7029 memorystatus_jetsam_policy &= ~kPolicyMoreFree;
7030 }
7031
7032 memorystatus_update_levels_locked(TRUE);
7033
7034 proc_list_unlock();
7035
7036 return 0;
7037 }
7038 SYSCTL_PROC(_kern, OID_AUTO, memorystatus_policy_more_free, CTLTYPE_INT|CTLFLAG_WR|CTLFLAG_LOCKED|CTLFLAG_MASKED,
7039 0, 0, &sysctl_kern_memorystatus_policy_more_free, "I", "");
7040
7041 /*
7042 * Get the at_boot snapshot
7043 */
7044 static int
7045 memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only) {
7046 size_t input_size = *snapshot_size;
7047
7048 /*
7049 * The at_boot snapshot has no entry list.
7050 */
7051 *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t);
7052
7053 if (size_only) {
7054 return 0;
7055 }
7056
7057 /*
7058 * Validate the size of the snapshot buffer
7059 */
7060 if (input_size < *snapshot_size) {
7061 return EINVAL;
7062 }
7063
7064 /*
7065 * Update the notification_time only
7066 */
7067 memorystatus_at_boot_snapshot.notification_time = mach_absolute_time();
7068 *snapshot = &memorystatus_at_boot_snapshot;
7069
7070 MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
7071 (long)input_size, (long)*snapshot_size, 0);
7072 return 0;
7073 }
7074
7075 static int
7076 memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only) {
7077 size_t input_size = *snapshot_size;
7078 uint32_t ods_list_count = memorystatus_list_count;
7079 memorystatus_jetsam_snapshot_t *ods = NULL; /* The on_demand snapshot buffer */
7080
7081 *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (ods_list_count));
7082
7083 if (size_only) {
7084 return 0;
7085 }
7086
7087 /*
7088 * Validate the size of the snapshot buffer.
7089 * This is inherently racey. May want to revisit
7090 * this error condition and trim the output when
7091 * it doesn't fit.
7092 */
7093 if (input_size < *snapshot_size) {
7094 return EINVAL;
7095 }
7096
7097 /*
7098 * Allocate and initialize a snapshot buffer.
7099 */
7100 ods = (memorystatus_jetsam_snapshot_t *)kalloc(*snapshot_size);
7101 if (!ods) {
7102 return (ENOMEM);
7103 }
7104
7105 memset(ods, 0, *snapshot_size);
7106
7107 proc_list_lock();
7108 memorystatus_init_jetsam_snapshot_locked(ods, ods_list_count);
7109 proc_list_unlock();
7110
7111 /*
7112 * Return the kernel allocated, on_demand buffer.
7113 * The caller of this routine will copy the data out
7114 * to user space and then free the kernel allocated
7115 * buffer.
7116 */
7117 *snapshot = ods;
7118
7119 MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7120 (long)input_size, (long)*snapshot_size, (long)ods_list_count);
7121
7122 return 0;
7123 }
7124
7125 static int
7126 memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only) {
7127 size_t input_size = *snapshot_size;
7128
7129 if (memorystatus_jetsam_snapshot_count > 0) {
7130 *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count));
7131 } else {
7132 *snapshot_size = 0;
7133 }
7134
7135 if (size_only) {
7136 return 0;
7137 }
7138
7139 if (input_size < *snapshot_size) {
7140 return EINVAL;
7141 }
7142
7143 *snapshot = memorystatus_jetsam_snapshot;
7144
7145 MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
7146 (long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_count);
7147
7148 return 0;
7149 }
7150
7151
7152 static int
7153 memorystatus_cmd_get_jetsam_snapshot(int32_t flags, user_addr_t buffer, size_t buffer_size, int32_t *retval) {
7154 int error = EINVAL;
7155 boolean_t size_only;
7156 boolean_t is_default_snapshot = FALSE;
7157 boolean_t is_on_demand_snapshot = FALSE;
7158 boolean_t is_at_boot_snapshot = FALSE;
7159 memorystatus_jetsam_snapshot_t *snapshot;
7160
7161 size_only = ((buffer == USER_ADDR_NULL) ? TRUE : FALSE);
7162
7163 if (flags == 0) {
7164 /* Default */
7165 is_default_snapshot = TRUE;
7166 error = memorystatus_get_jetsam_snapshot(&snapshot, &buffer_size, size_only);
7167 } else {
7168 if (flags & ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND | MEMORYSTATUS_SNAPSHOT_AT_BOOT)) {
7169 /*
7170 * Unsupported bit set in flag.
7171 */
7172 return EINVAL;
7173 }
7174
7175 if ((flags & (MEMORYSTATUS_SNAPSHOT_ON_DEMAND | MEMORYSTATUS_SNAPSHOT_AT_BOOT)) ==
7176 (MEMORYSTATUS_SNAPSHOT_ON_DEMAND | MEMORYSTATUS_SNAPSHOT_AT_BOOT)) {
7177 /*
7178 * Can't have both set at the same time.
7179 */
7180 return EINVAL;
7181 }
7182
7183 if (flags & MEMORYSTATUS_SNAPSHOT_ON_DEMAND) {
7184 is_on_demand_snapshot = TRUE;
7185 /*
7186 * When not requesting the size only, the following call will allocate
7187 * an on_demand snapshot buffer, which is freed below.
7188 */
7189 error = memorystatus_get_on_demand_snapshot(&snapshot, &buffer_size, size_only);
7190
7191 } else if (flags & MEMORYSTATUS_SNAPSHOT_AT_BOOT) {
7192 is_at_boot_snapshot = TRUE;
7193 error = memorystatus_get_at_boot_snapshot(&snapshot, &buffer_size, size_only);
7194 } else {
7195 /*
7196 * Invalid flag setting.
7197 */
7198 return EINVAL;
7199 }
7200 }
7201
7202 if (error) {
7203 goto out;
7204 }
7205
7206 /*
7207 * Copy the data out to user space and clear the snapshot buffer.
7208 * If working with the jetsam snapshot,
7209 * clearing the buffer means, reset the count.
7210 * If working with an on_demand snapshot
7211 * clearing the buffer means, free it.
7212 * If working with the at_boot snapshot
7213 * there is nothing to clear or update.
7214 */
7215 if (!size_only) {
7216 if ((error = copyout(snapshot, buffer, buffer_size)) == 0) {
7217 if (is_default_snapshot) {
7218 /*
7219 * The jetsam snapshot is never freed, its count is simply reset.
7220 */
7221 proc_list_lock();
7222 snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
7223 memorystatus_jetsam_snapshot_last_timestamp = 0;
7224 proc_list_unlock();
7225 }
7226 }
7227
7228 if (is_on_demand_snapshot) {
7229 /*
7230 * The on_demand snapshot is always freed,
7231 * even if the copyout failed.
7232 */
7233 if(snapshot) {
7234 kfree(snapshot, buffer_size);
7235 }
7236 }
7237 }
7238
7239 if (error == 0) {
7240 *retval = buffer_size;
7241 }
7242 out:
7243 return error;
7244 }
7245
7246 /*
7247 * Routine: memorystatus_cmd_grp_set_properties
7248 * Purpose: Update properties for a group of processes.
7249 *
7250 * Supported Properties:
7251 * [priority]
7252 * Move each process out of its effective priority
7253 * band and into a new priority band.
7254 * Maintains relative order from lowest to highest priority.
7255 * In single band, maintains relative order from head to tail.
7256 *
7257 * eg: before [effectivepriority | pid]
7258 * [18 | p101 ]
7259 * [17 | p55, p67, p19 ]
7260 * [12 | p103 p10 ]
7261 * [ 7 | p25 ]
7262 * [ 0 | p71, p82, ]
7263 *
7264 * after [ new band | pid]
7265 * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
7266 *
7267 * Returns: 0 on success, else non-zero.
7268 *
7269 * Caveat: We know there is a race window regarding recycled pids.
7270 * A process could be killed before the kernel can act on it here.
7271 * If a pid cannot be found in any of the jetsam priority bands,
7272 * then we simply ignore it. No harm.
7273 * But, if the pid has been recycled then it could be an issue.
7274 * In that scenario, we might move an unsuspecting process to the new
7275 * priority band. It's not clear how the kernel can safeguard
7276 * against this, but it would be an extremely rare case anyway.
7277 * The caller of this api might avoid such race conditions by
7278 * ensuring that the processes passed in the pid list are suspended.
7279 */
7280
7281
7282 /* This internal structure can expand when we add support for more properties */
7283 typedef struct memorystatus_internal_properties
7284 {
7285 proc_t proc;
7286 int32_t priority; /* see memorytstatus_priority_entry_t : priority */
7287 } memorystatus_internal_properties_t;
7288
7289
7290 static int
7291 memorystatus_cmd_grp_set_properties(int32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval) {
7292
7293 #pragma unused (flags)
7294
7295 /*
7296 * We only handle setting priority
7297 * per process
7298 */
7299
7300 int error = 0;
7301 memorystatus_priority_entry_t *entries = NULL;
7302 uint32_t entry_count = 0;
7303
7304 /* This will be the ordered proc list */
7305 memorystatus_internal_properties_t *table = NULL;
7306 size_t table_size = 0;
7307 uint32_t table_count = 0;
7308
7309 uint32_t i = 0;
7310 uint32_t bucket_index = 0;
7311 boolean_t head_insert;
7312 int32_t new_priority;
7313
7314 proc_t p;
7315
7316 /* Verify inputs */
7317 if ((buffer == USER_ADDR_NULL) || (buffer_size == 0) || ((buffer_size % sizeof(memorystatus_priority_entry_t)) != 0)) {
7318 error = EINVAL;
7319 goto out;
7320 }
7321
7322 entry_count = (buffer_size / sizeof(memorystatus_priority_entry_t));
7323 if ((entries = (memorystatus_priority_entry_t *)kalloc(buffer_size)) == NULL) {
7324 error = ENOMEM;
7325 goto out;
7326 }
7327
7328 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_START, entry_count, 0, 0, 0, 0);
7329
7330 if ((error = copyin(buffer, entries, buffer_size)) != 0) {
7331 goto out;
7332 }
7333
7334 /* Verify sanity of input priorities */
7335 for (i=0; i < entry_count; i++) {
7336 if (entries[i].priority == -1) {
7337 /* Use as shorthand for default priority */
7338 entries[i].priority = JETSAM_PRIORITY_DEFAULT;
7339 } else if ((entries[i].priority == system_procs_aging_band) || (entries[i].priority == applications_aging_band)) {
7340 /* Both the aging bands are reserved for internal use;
7341 * if requested, adjust to JETSAM_PRIORITY_IDLE. */
7342 entries[i].priority = JETSAM_PRIORITY_IDLE;
7343 } else if (entries[i].priority == JETSAM_PRIORITY_IDLE_HEAD) {
7344 /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
7345 * queue */
7346 /* Deal with this later */
7347 } else if ((entries[i].priority < 0) || (entries[i].priority >= MEMSTAT_BUCKET_COUNT)) {
7348 /* Sanity check */
7349 error = EINVAL;
7350 goto out;
7351 }
7352 }
7353
7354 table_size = sizeof(memorystatus_internal_properties_t) * entry_count;
7355 if ( (table = (memorystatus_internal_properties_t *)kalloc(table_size)) == NULL) {
7356 error = ENOMEM;
7357 goto out;
7358 }
7359 memset(table, 0, table_size);
7360
7361
7362 /*
7363 * For each jetsam bucket entry, spin through the input property list.
7364 * When a matching pid is found, populate an adjacent table with the
7365 * appropriate proc pointer and new property values.
7366 * This traversal automatically preserves order from lowest
7367 * to highest priority.
7368 */
7369
7370 bucket_index=0;
7371
7372 proc_list_lock();
7373
7374 /* Create the ordered table */
7375 p = memorystatus_get_first_proc_locked(&bucket_index, TRUE);
7376 while (p && (table_count < entry_count)) {
7377 for (i=0; i < entry_count; i++ ) {
7378 if (p->p_pid == entries[i].pid) {
7379 /* Build the table data */
7380 table[table_count].proc = p;
7381 table[table_count].priority = entries[i].priority;
7382 table_count++;
7383 break;
7384 }
7385 }
7386 p = memorystatus_get_next_proc_locked(&bucket_index, p, TRUE);
7387 }
7388
7389 /* We now have ordered list of procs ready to move */
7390 for (i=0; i < table_count; i++) {
7391 p = table[i].proc;
7392 assert(p != NULL);
7393
7394 /* Allow head inserts -- but relative order is now */
7395 if (table[i].priority == JETSAM_PRIORITY_IDLE_HEAD) {
7396 new_priority = JETSAM_PRIORITY_IDLE;
7397 head_insert = true;
7398 } else {
7399 new_priority = table[i].priority;
7400 head_insert = false;
7401 }
7402
7403 /* Not allowed */
7404 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
7405 continue;
7406 }
7407
7408 /*
7409 * Take appropriate steps if moving proc out of
7410 * either of the aging bands.
7411 */
7412 if ((p->p_memstat_effectivepriority == system_procs_aging_band) || (p->p_memstat_effectivepriority == applications_aging_band)) {
7413 memorystatus_invalidate_idle_demotion_locked(p, TRUE);
7414 }
7415
7416 memorystatus_update_priority_locked(p, new_priority, head_insert, false);
7417 }
7418
7419 proc_list_unlock();
7420
7421 /*
7422 * if (table_count != entry_count)
7423 * then some pids were not found in a jetsam band.
7424 * harmless but interesting...
7425 */
7426 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_END, entry_count, table_count, 0, 0, 0);
7427
7428 out:
7429 if (entries)
7430 kfree(entries, buffer_size);
7431 if (table)
7432 kfree(table, table_size);
7433
7434 return (error);
7435 }
7436
7437
7438 /*
7439 * This routine is used to update a process's jetsam priority position and stored user_data.
7440 * It is not used for the setting of memory limits, which is why the last 6 args to the
7441 * memorystatus_update() call are 0 or FALSE.
7442 */
7443
7444 static int
7445 memorystatus_cmd_set_priority_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval) {
7446 int error = 0;
7447 memorystatus_priority_properties_t mpp_entry;
7448
7449 /* Validate inputs */
7450 if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_priority_properties_t))) {
7451 return EINVAL;
7452 }
7453
7454 error = copyin(buffer, &mpp_entry, buffer_size);
7455
7456 if (error == 0) {
7457 proc_t p;
7458
7459 p = proc_find(pid);
7460 if (!p) {
7461 return ESRCH;
7462 }
7463
7464 if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
7465 proc_rele(p);
7466 return EPERM;
7467 }
7468
7469 error = memorystatus_update(p, mpp_entry.priority, mpp_entry.user_data, FALSE, FALSE, 0, 0, FALSE, FALSE, FALSE);
7470 proc_rele(p);
7471 }
7472
7473 return(error);
7474 }
7475
7476 static int
7477 memorystatus_cmd_set_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval) {
7478 int error = 0;
7479 memorystatus_memlimit_properties_t mmp_entry;
7480
7481 /* Validate inputs */
7482 if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_memlimit_properties_t))) {
7483 return EINVAL;
7484 }
7485
7486 error = copyin(buffer, &mmp_entry, buffer_size);
7487
7488 if (error == 0) {
7489 error = memorystatus_set_memlimit_properties(pid, &mmp_entry);
7490 }
7491
7492 return(error);
7493 }
7494
7495 /*
7496 * When getting the memlimit settings, we can't simply call task_get_phys_footprint_limit().
7497 * That gets the proc's cached memlimit and there is no guarantee that the active/inactive
7498 * limits will be the same in the no-limit case. Instead we convert limits <= 0 using
7499 * task_convert_phys_footprint_limit(). It computes the same limit value that would be written
7500 * to the task's ledgers via task_set_phys_footprint_limit().
7501 */
7502 static int
7503 memorystatus_cmd_get_memlimit_properties(pid_t pid, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval) {
7504 int error = 0;
7505 memorystatus_memlimit_properties_t mmp_entry;
7506
7507 /* Validate inputs */
7508 if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_memlimit_properties_t))) {
7509 return EINVAL;
7510 }
7511
7512 memset (&mmp_entry, 0, sizeof(memorystatus_memlimit_properties_t));
7513
7514 proc_t p = proc_find(pid);
7515 if (!p) {
7516 return ESRCH;
7517 }
7518
7519 /*
7520 * Get the active limit and attributes.
7521 * No locks taken since we hold a reference to the proc.
7522 */
7523
7524 if (p->p_memstat_memlimit_active > 0 ) {
7525 mmp_entry.memlimit_active = p->p_memstat_memlimit_active;
7526 } else {
7527 task_convert_phys_footprint_limit(-1, &mmp_entry.memlimit_active);
7528 }
7529
7530 if (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL) {
7531 mmp_entry.memlimit_active_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7532 }
7533
7534 /*
7535 * Get the inactive limit and attributes
7536 */
7537 if (p->p_memstat_memlimit_inactive <= 0) {
7538 task_convert_phys_footprint_limit(-1, &mmp_entry.memlimit_inactive);
7539 } else {
7540 mmp_entry.memlimit_inactive = p->p_memstat_memlimit_inactive;
7541 }
7542 if (p->p_memstat_state & P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL) {
7543 mmp_entry.memlimit_inactive_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7544 }
7545 proc_rele(p);
7546
7547 error = copyout(&mmp_entry, buffer, buffer_size);
7548
7549 return(error);
7550 }
7551
7552
7553 /*
7554 * SPI for kbd - pr24956468
7555 * This is a very simple snapshot that calculates how much a
7556 * process's phys_footprint exceeds a specific memory limit.
7557 * Only the inactive memory limit is supported for now.
7558 * The delta is returned as bytes in excess or zero.
7559 */
7560 static int
7561 memorystatus_cmd_get_memlimit_excess_np(pid_t pid, uint32_t flags, user_addr_t buffer, size_t buffer_size, __unused int32_t *retval) {
7562 int error = 0;
7563 uint64_t footprint_in_bytes = 0;
7564 uint64_t delta_in_bytes = 0;
7565 int32_t memlimit_mb = 0;
7566 uint64_t memlimit_bytes = 0;
7567
7568 /* Validate inputs */
7569 if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(uint64_t)) || (flags != 0)) {
7570 return EINVAL;
7571 }
7572
7573 proc_t p = proc_find(pid);
7574 if (!p) {
7575 return ESRCH;
7576 }
7577
7578 /*
7579 * Get the inactive limit.
7580 * No locks taken since we hold a reference to the proc.
7581 */
7582
7583 if (p->p_memstat_memlimit_inactive <= 0) {
7584 task_convert_phys_footprint_limit(-1, &memlimit_mb);
7585 } else {
7586 memlimit_mb = p->p_memstat_memlimit_inactive;
7587 }
7588
7589 footprint_in_bytes = get_task_phys_footprint(p->task);
7590
7591 proc_rele(p);
7592
7593 memlimit_bytes = memlimit_mb * 1024 * 1024; /* MB to bytes */
7594
7595 /*
7596 * Computed delta always returns >= 0 bytes
7597 */
7598 if (footprint_in_bytes > memlimit_bytes) {
7599 delta_in_bytes = footprint_in_bytes - memlimit_bytes;
7600 }
7601
7602 error = copyout(&delta_in_bytes, buffer, sizeof(delta_in_bytes));
7603
7604 return(error);
7605 }
7606
7607
7608 static int
7609 memorystatus_cmd_get_pressure_status(int32_t *retval) {
7610 int error;
7611
7612 /* Need privilege for check */
7613 error = priv_check_cred(kauth_cred_get(), PRIV_VM_PRESSURE, 0);
7614 if (error) {
7615 return (error);
7616 }
7617
7618 /* Inherently racy, so it's not worth taking a lock here */
7619 *retval = (kVMPressureNormal != memorystatus_vm_pressure_level) ? 1 : 0;
7620
7621 return error;
7622 }
7623
7624 int
7625 memorystatus_get_pressure_status_kdp() {
7626 return (kVMPressureNormal != memorystatus_vm_pressure_level) ? 1 : 0;
7627 }
7628
7629 /*
7630 * Every process, including a P_MEMSTAT_INTERNAL process (currently only pid 1), is allowed to set a HWM.
7631 *
7632 * This call is inflexible -- it does not distinguish between active/inactive, fatal/non-fatal
7633 * So, with 2-level HWM preserving previous behavior will map as follows.
7634 * - treat the limit passed in as both an active and inactive limit.
7635 * - treat the is_fatal_limit flag as though it applies to both active and inactive limits.
7636 *
7637 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK
7638 * - the is_fatal_limit is FALSE, meaning the active and inactive limits are non-fatal/soft
7639 * - so mapping is (active/non-fatal, inactive/non-fatal)
7640 *
7641 * When invoked via MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT
7642 * - the is_fatal_limit is TRUE, meaning the process's active and inactive limits are fatal/hard
7643 * - so mapping is (active/fatal, inactive/fatal)
7644 */
7645
7646 static int
7647 memorystatus_cmd_set_jetsam_memory_limit(pid_t pid, int32_t high_water_mark, __unused int32_t *retval, boolean_t is_fatal_limit) {
7648 int error = 0;
7649 memorystatus_memlimit_properties_t entry;
7650
7651 entry.memlimit_active = high_water_mark;
7652 entry.memlimit_active_attr = 0;
7653 entry.memlimit_inactive = high_water_mark;
7654 entry.memlimit_inactive_attr = 0;
7655
7656 if (is_fatal_limit == TRUE) {
7657 entry.memlimit_active_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7658 entry.memlimit_inactive_attr |= MEMORYSTATUS_MEMLIMIT_ATTR_FATAL;
7659 }
7660
7661 error = memorystatus_set_memlimit_properties(pid, &entry);
7662 return (error);
7663 }
7664
7665 static int
7666 memorystatus_set_memlimit_properties(pid_t pid, memorystatus_memlimit_properties_t *entry) {
7667
7668 int32_t memlimit_active;
7669 boolean_t memlimit_active_is_fatal;
7670 int32_t memlimit_inactive;
7671 boolean_t memlimit_inactive_is_fatal;
7672 uint32_t valid_attrs = 0;
7673 int error = 0;
7674
7675 proc_t p = proc_find(pid);
7676 if (!p) {
7677 return ESRCH;
7678 }
7679
7680 /*
7681 * Check for valid attribute flags.
7682 */
7683 valid_attrs |= (MEMORYSTATUS_MEMLIMIT_ATTR_FATAL);
7684 if ((entry->memlimit_active_attr & (~valid_attrs)) != 0) {
7685 proc_rele(p);
7686 return EINVAL;
7687 }
7688 if ((entry->memlimit_inactive_attr & (~valid_attrs)) != 0) {
7689 proc_rele(p);
7690 return EINVAL;
7691 }
7692
7693 /*
7694 * Setup the active memlimit properties
7695 */
7696 memlimit_active = entry->memlimit_active;
7697 if (entry->memlimit_active_attr & MEMORYSTATUS_MEMLIMIT_ATTR_FATAL) {
7698 memlimit_active_is_fatal = TRUE;
7699 } else {
7700 memlimit_active_is_fatal = FALSE;
7701 }
7702
7703 /*
7704 * Setup the inactive memlimit properties
7705 */
7706 memlimit_inactive = entry->memlimit_inactive;
7707 if (entry->memlimit_inactive_attr & MEMORYSTATUS_MEMLIMIT_ATTR_FATAL) {
7708 memlimit_inactive_is_fatal = TRUE;
7709 } else {
7710 memlimit_inactive_is_fatal = FALSE;
7711 }
7712
7713 /*
7714 * Setting a limit of <= 0 implies that the process has no
7715 * high-water-mark and has no per-task-limit. That means
7716 * the system_wide task limit is in place, which by the way,
7717 * is always fatal.
7718 */
7719
7720 if (memlimit_active <= 0) {
7721 /*
7722 * Enforce the fatal system_wide task limit while process is active.
7723 */
7724 memlimit_active = -1;
7725 memlimit_active_is_fatal = TRUE;
7726 }
7727
7728 if (memlimit_inactive <= 0) {
7729 /*
7730 * Enforce the fatal system_wide task limit while process is inactive.
7731 */
7732 memlimit_inactive = -1;
7733 memlimit_inactive_is_fatal = TRUE;
7734 }
7735
7736 proc_list_lock();
7737
7738 /*
7739 * Store the active limit variants in the proc.
7740 */
7741 SET_ACTIVE_LIMITS_LOCKED(p, memlimit_active, memlimit_active_is_fatal);
7742
7743 /*
7744 * Store the inactive limit variants in the proc.
7745 */
7746 SET_INACTIVE_LIMITS_LOCKED(p, memlimit_inactive, memlimit_inactive_is_fatal);
7747
7748 /*
7749 * Enforce appropriate limit variant by updating the cached values
7750 * and writing the ledger.
7751 * Limit choice is based on process active/inactive state.
7752 */
7753
7754 if (memorystatus_highwater_enabled) {
7755 boolean_t is_fatal;
7756 boolean_t use_active;
7757 /*
7758 * No need to consider P_MEMSTAT_MEMLIMIT_BACKGROUND anymore.
7759 * Background limits are described via the inactive limit slots.
7760 */
7761
7762 if (proc_jetsam_state_is_active_locked(p) == TRUE) {
7763 CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
7764 use_active = TRUE;
7765 } else {
7766 CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
7767 use_active = FALSE;
7768 }
7769
7770 /* Enforce the limit by writing to the ledgers */
7771 error = (task_set_phys_footprint_limit_internal(p->task, ((p->p_memstat_memlimit > 0) ? p->p_memstat_memlimit : -1), NULL, use_active, is_fatal) == 0) ? 0 : EINVAL;
7772
7773 MEMORYSTATUS_DEBUG(3, "memorystatus_set_memlimit_properties: new limit on pid %d (%dMB %s) current priority (%d) dirty_state?=0x%x %s\n",
7774 p->p_pid, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
7775 (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, p->p_memstat_dirty,
7776 (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
7777 DTRACE_MEMORYSTATUS2(memorystatus_set_memlimit, proc_t, p, int32_t, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1));
7778 }
7779
7780 proc_list_unlock();
7781 proc_rele(p);
7782
7783 return error;
7784 }
7785
7786 /*
7787 * Returns the jetsam priority (effective or requested) of the process
7788 * associated with this task.
7789 */
7790 int
7791 proc_get_memstat_priority(proc_t p, boolean_t effective_priority)
7792 {
7793 if (p) {
7794 if (effective_priority) {
7795 return p->p_memstat_effectivepriority;
7796 } else {
7797 return p->p_memstat_requestedpriority;
7798 }
7799 }
7800 return 0;
7801 }
7802
7803 #endif /* CONFIG_JETSAM */
7804
7805 int
7806 memorystatus_control(struct proc *p __unused, struct memorystatus_control_args *args, int *ret) {
7807 int error = EINVAL;
7808 os_reason_t jetsam_reason = OS_REASON_NULL;
7809
7810 #if !CONFIG_JETSAM
7811 #pragma unused(ret)
7812 #pragma unused(jetsam_reason)
7813 #endif
7814
7815 /* Need to be root or have entitlement */
7816 if (!kauth_cred_issuser(kauth_cred_get()) && !IOTaskHasEntitlement(current_task(), MEMORYSTATUS_ENTITLEMENT)) {
7817 error = EPERM;
7818 goto out;
7819 }
7820
7821 /*
7822 * Sanity check.
7823 * Do not enforce it for snapshots.
7824 */
7825 if (args->command != MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT) {
7826 if (args->buffersize > MEMORYSTATUS_BUFFERSIZE_MAX) {
7827 error = EINVAL;
7828 goto out;
7829 }
7830 }
7831
7832 switch (args->command) {
7833 case MEMORYSTATUS_CMD_GET_PRIORITY_LIST:
7834 error = memorystatus_cmd_get_priority_list(args->buffer, args->buffersize, ret);
7835 break;
7836 #if CONFIG_JETSAM
7837 case MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES:
7838 error = memorystatus_cmd_set_priority_properties(args->pid, args->buffer, args->buffersize, ret);
7839 break;
7840 case MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES:
7841 error = memorystatus_cmd_set_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
7842 break;
7843 case MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES:
7844 error = memorystatus_cmd_get_memlimit_properties(args->pid, args->buffer, args->buffersize, ret);
7845 break;
7846 case MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS:
7847 error = memorystatus_cmd_get_memlimit_excess_np(args->pid, args->flags, args->buffer, args->buffersize, ret);
7848 break;
7849 case MEMORYSTATUS_CMD_GRP_SET_PROPERTIES:
7850 error = memorystatus_cmd_grp_set_properties((int32_t)args->flags, args->buffer, args->buffersize, ret);
7851 break;
7852 case MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT:
7853 error = memorystatus_cmd_get_jetsam_snapshot((int32_t)args->flags, args->buffer, args->buffersize, ret);
7854 break;
7855 case MEMORYSTATUS_CMD_GET_PRESSURE_STATUS:
7856 error = memorystatus_cmd_get_pressure_status(ret);
7857 break;
7858 case MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK:
7859 /*
7860 * This call does not distinguish between active and inactive limits.
7861 * Default behavior in 2-level HWM world is to set both.
7862 * Non-fatal limit is also assumed for both.
7863 */
7864 error = memorystatus_cmd_set_jetsam_memory_limit(args->pid, (int32_t)args->flags, ret, FALSE);
7865 break;
7866 case MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT:
7867 /*
7868 * This call does not distinguish between active and inactive limits.
7869 * Default behavior in 2-level HWM world is to set both.
7870 * Fatal limit is also assumed for both.
7871 */
7872 error = memorystatus_cmd_set_jetsam_memory_limit(args->pid, (int32_t)args->flags, ret, TRUE);
7873 break;
7874 /* Test commands */
7875 #if DEVELOPMENT || DEBUG
7876 case MEMORYSTATUS_CMD_TEST_JETSAM:
7877 jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_GENERIC);
7878 if (jetsam_reason == OS_REASON_NULL) {
7879 printf("memorystatus_control: failed to allocate jetsam reason\n");
7880 }
7881
7882 error = memorystatus_kill_process_sync(args->pid, kMemorystatusKilled, jetsam_reason) ? 0 : EINVAL;
7883 break;
7884 case MEMORYSTATUS_CMD_TEST_JETSAM_SORT:
7885 error = memorystatus_cmd_test_jetsam_sort(args->pid, (int32_t)args->flags);
7886 break;
7887 case MEMORYSTATUS_CMD_SET_JETSAM_PANIC_BITS:
7888 error = memorystatus_cmd_set_panic_bits(args->buffer, args->buffersize);
7889 break;
7890 #else /* DEVELOPMENT || DEBUG */
7891 #pragma unused(jetsam_reason)
7892 #endif /* DEVELOPMENT || DEBUG */
7893 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE:
7894 if (memorystatus_aggressive_jetsam_lenient_allowed == FALSE) {
7895 #if DEVELOPMENT || DEBUG
7896 printf("Enabling Lenient Mode\n");
7897 #endif /* DEVELOPMENT || DEBUG */
7898
7899 memorystatus_aggressive_jetsam_lenient_allowed = TRUE;
7900 memorystatus_aggressive_jetsam_lenient = TRUE;
7901 error = 0;
7902 }
7903 break;
7904 case MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE:
7905 #if DEVELOPMENT || DEBUG
7906 printf("Disabling Lenient mode\n");
7907 #endif /* DEVELOPMENT || DEBUG */
7908 memorystatus_aggressive_jetsam_lenient_allowed = FALSE;
7909 memorystatus_aggressive_jetsam_lenient = FALSE;
7910 error = 0;
7911 break;
7912 #endif /* CONFIG_JETSAM */
7913 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE:
7914 case MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE:
7915 error = memorystatus_low_mem_privileged_listener(args->command);
7916 break;
7917
7918 #if CONFIG_JETSAM
7919 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE:
7920 case MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE:
7921 error = memorystatus_update_inactive_jetsam_priority_band(args->pid, args->command, args->flags ? TRUE : FALSE);
7922 break;
7923 #endif /* CONFIG_JETSAM */
7924
7925 default:
7926 break;
7927 }
7928
7929 out:
7930 return error;
7931 }
7932
7933
7934 static int
7935 filt_memorystatusattach(struct knote *kn)
7936 {
7937 int error;
7938
7939 kn->kn_flags |= EV_CLEAR;
7940 error = memorystatus_knote_register(kn);
7941 if (error) {
7942 kn->kn_flags = EV_ERROR;
7943 kn->kn_data = error;
7944 }
7945 return 0;
7946 }
7947
7948 static void
7949 filt_memorystatusdetach(struct knote *kn)
7950 {
7951 memorystatus_knote_unregister(kn);
7952 }
7953
7954 static int
7955 filt_memorystatus(struct knote *kn __unused, long hint)
7956 {
7957 if (hint) {
7958 switch (hint) {
7959 case kMemorystatusNoPressure:
7960 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PRESSURE_NORMAL) {
7961 kn->kn_fflags = NOTE_MEMORYSTATUS_PRESSURE_NORMAL;
7962 }
7963 break;
7964 case kMemorystatusPressure:
7965 if (memorystatus_vm_pressure_level == kVMPressureWarning || memorystatus_vm_pressure_level == kVMPressureUrgent) {
7966 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PRESSURE_WARN) {
7967 kn->kn_fflags = NOTE_MEMORYSTATUS_PRESSURE_WARN;
7968 }
7969 } else if (memorystatus_vm_pressure_level == kVMPressureCritical) {
7970
7971 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PRESSURE_CRITICAL) {
7972 kn->kn_fflags = NOTE_MEMORYSTATUS_PRESSURE_CRITICAL;
7973 }
7974 }
7975 break;
7976 case kMemorystatusLowSwap:
7977 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_LOW_SWAP) {
7978 kn->kn_fflags = NOTE_MEMORYSTATUS_LOW_SWAP;
7979 }
7980 break;
7981
7982 case kMemorystatusProcLimitWarn:
7983 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) {
7984 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_WARN;
7985 }
7986 break;
7987
7988 case kMemorystatusProcLimitCritical:
7989 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL) {
7990 kn->kn_fflags = NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL;
7991 }
7992 break;
7993
7994 default:
7995 break;
7996 }
7997 }
7998
7999 #if 0
8000 if (kn->kn_fflags != 0) {
8001 proc_t knote_proc = knote_get_kq(kn)->kq_p;
8002 pid_t knote_pid = knote_proc->p_pid;
8003
8004 printf("filt_memorystatus: sending kn 0x%lx (event 0x%x) for pid (%d)\n",
8005 (unsigned long)kn, kn->kn_fflags, knote_pid);
8006 }
8007 #endif
8008
8009 return (kn->kn_fflags != 0);
8010 }
8011
8012 static int
8013 filt_memorystatustouch(struct knote *kn, struct kevent_internal_s *kev)
8014 {
8015 int res;
8016 int prev_kn_sfflags = 0;
8017
8018 memorystatus_klist_lock();
8019
8020 /*
8021 * copy in new kevent settings
8022 * (saving the "desired" data and fflags).
8023 */
8024
8025 prev_kn_sfflags = kn->kn_sfflags;
8026 kn->kn_sfflags = (kev->fflags & EVFILT_MEMORYSTATUS_ALL_MASK);
8027
8028 /*
8029 * Only on desktop do we restrict notifications to
8030 * one per active/inactive state (soft limits only).
8031 */
8032 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) {
8033 /*
8034 * Is there previous state to preserve?
8035 */
8036 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) {
8037 /*
8038 * This knote was previously interested in proc_limit_warn,
8039 * so yes, preserve previous state.
8040 */
8041 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE) {
8042 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE;
8043 }
8044 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE) {
8045 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE;
8046 }
8047 } else {
8048 /*
8049 * This knote was not previously interested in proc_limit_warn,
8050 * but it is now. Set both states.
8051 */
8052 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE;
8053 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE;
8054 }
8055 }
8056
8057 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL) {
8058 /*
8059 * Is there previous state to preserve?
8060 */
8061 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL) {
8062 /*
8063 * This knote was previously interested in proc_limit_critical,
8064 * so yes, preserve previous state.
8065 */
8066 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE) {
8067 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE;
8068 }
8069 if (prev_kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE) {
8070 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE;
8071 }
8072 } else {
8073 /*
8074 * This knote was not previously interested in proc_limit_critical,
8075 * but it is now. Set both states.
8076 */
8077 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE;
8078 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE;
8079 }
8080 }
8081
8082 if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0)
8083 kn->kn_udata = kev->udata;
8084
8085 /*
8086 * reset the output flags based on a
8087 * combination of the old events and
8088 * the new desired event list.
8089 */
8090 //kn->kn_fflags &= kn->kn_sfflags;
8091
8092 res = (kn->kn_fflags != 0);
8093
8094 memorystatus_klist_unlock();
8095
8096 return res;
8097 }
8098
8099 static int
8100 filt_memorystatusprocess(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev)
8101 {
8102 #pragma unused(data)
8103 int res;
8104
8105 memorystatus_klist_lock();
8106 res = (kn->kn_fflags != 0);
8107 if (res) {
8108 *kev = kn->kn_kevent;
8109 kn->kn_flags |= EV_CLEAR; /* automatic */
8110 kn->kn_fflags = 0;
8111 kn->kn_data = 0;
8112 }
8113 memorystatus_klist_unlock();
8114
8115 return res;
8116 }
8117
8118 static void
8119 memorystatus_klist_lock(void) {
8120 lck_mtx_lock(&memorystatus_klist_mutex);
8121 }
8122
8123 static void
8124 memorystatus_klist_unlock(void) {
8125 lck_mtx_unlock(&memorystatus_klist_mutex);
8126 }
8127
8128 void
8129 memorystatus_kevent_init(lck_grp_t *grp, lck_attr_t *attr) {
8130 lck_mtx_init(&memorystatus_klist_mutex, grp, attr);
8131 klist_init(&memorystatus_klist);
8132 }
8133
8134 int
8135 memorystatus_knote_register(struct knote *kn) {
8136 int error = 0;
8137
8138 memorystatus_klist_lock();
8139
8140 /*
8141 * Support only userspace visible flags.
8142 */
8143 if ((kn->kn_sfflags & EVFILT_MEMORYSTATUS_ALL_MASK) == kn->kn_sfflags) {
8144
8145 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) {
8146 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_ACTIVE;
8147 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_WARN_INACTIVE;
8148 }
8149
8150 if (kn->kn_sfflags & NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL) {
8151 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_ACTIVE;
8152 kn->kn_sfflags |= NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL_INACTIVE;
8153 }
8154
8155 KNOTE_ATTACH(&memorystatus_klist, kn);
8156
8157 } else {
8158 error = ENOTSUP;
8159 }
8160
8161 memorystatus_klist_unlock();
8162
8163 return error;
8164 }
8165
8166 void
8167 memorystatus_knote_unregister(struct knote *kn __unused) {
8168 memorystatus_klist_lock();
8169 KNOTE_DETACH(&memorystatus_klist, kn);
8170 memorystatus_klist_unlock();
8171 }
8172
8173
8174 #if 0
8175 #if CONFIG_JETSAM && VM_PRESSURE_EVENTS
8176 static boolean_t
8177 memorystatus_issue_pressure_kevent(boolean_t pressured) {
8178 memorystatus_klist_lock();
8179 KNOTE(&memorystatus_klist, pressured ? kMemorystatusPressure : kMemorystatusNoPressure);
8180 memorystatus_klist_unlock();
8181 return TRUE;
8182 }
8183 #endif /* CONFIG_JETSAM && VM_PRESSURE_EVENTS */
8184 #endif /* 0 */
8185
8186 #if CONFIG_JETSAM
8187 /* Coalition support */
8188
8189 /* sorting info for a particular priority bucket */
8190 typedef struct memstat_sort_info {
8191 coalition_t msi_coal;
8192 uint64_t msi_page_count;
8193 pid_t msi_pid;
8194 int msi_ntasks;
8195 } memstat_sort_info_t;
8196
8197 /*
8198 * qsort from smallest page count to largest page count
8199 *
8200 * return < 0 for a < b
8201 * 0 for a == b
8202 * > 0 for a > b
8203 */
8204 static int memstat_asc_cmp(const void *a, const void *b)
8205 {
8206 const memstat_sort_info_t *msA = (const memstat_sort_info_t *)a;
8207 const memstat_sort_info_t *msB = (const memstat_sort_info_t *)b;
8208
8209 return (int)((uint64_t)msA->msi_page_count - (uint64_t)msB->msi_page_count);
8210 }
8211
8212 /*
8213 * Return the number of pids rearranged during this sort.
8214 */
8215 static int
8216 memorystatus_sort_by_largest_coalition_locked(unsigned int bucket_index, int coal_sort_order)
8217 {
8218 #define MAX_SORT_PIDS 80
8219 #define MAX_COAL_LEADERS 10
8220
8221 unsigned int b = bucket_index;
8222 int nleaders = 0;
8223 int ntasks = 0;
8224 proc_t p = NULL;
8225 coalition_t coal = COALITION_NULL;
8226 int pids_moved = 0;
8227 int total_pids_moved = 0;
8228 int i;
8229
8230 /*
8231 * The system is typically under memory pressure when in this
8232 * path, hence, we want to avoid dynamic memory allocation.
8233 */
8234 memstat_sort_info_t leaders[MAX_COAL_LEADERS];
8235 pid_t pid_list[MAX_SORT_PIDS];
8236
8237 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
8238 return(0);
8239 }
8240
8241 /*
8242 * Clear the array that holds coalition leader information
8243 */
8244 for (i=0; i < MAX_COAL_LEADERS; i++) {
8245 leaders[i].msi_coal = COALITION_NULL;
8246 leaders[i].msi_page_count = 0; /* will hold total coalition page count */
8247 leaders[i].msi_pid = 0; /* will hold coalition leader pid */
8248 leaders[i].msi_ntasks = 0; /* will hold the number of tasks in a coalition */
8249 }
8250
8251 p = memorystatus_get_first_proc_locked(&b, FALSE);
8252 while (p) {
8253 if (coalition_is_leader(p->task, COALITION_TYPE_JETSAM, &coal)) {
8254 if (nleaders < MAX_COAL_LEADERS) {
8255 int coal_ntasks = 0;
8256 uint64_t coal_page_count = coalition_get_page_count(coal, &coal_ntasks);
8257 leaders[nleaders].msi_coal = coal;
8258 leaders[nleaders].msi_page_count = coal_page_count;
8259 leaders[nleaders].msi_pid = p->p_pid; /* the coalition leader */
8260 leaders[nleaders].msi_ntasks = coal_ntasks;
8261 nleaders++;
8262 } else {
8263 /*
8264 * We've hit MAX_COAL_LEADERS meaning we can handle no more coalitions.
8265 * Abandoned coalitions will linger at the tail of the priority band
8266 * when this sort session ends.
8267 * TODO: should this be an assert?
8268 */
8269 printf("%s: WARNING: more than %d leaders in priority band [%d]\n",
8270 __FUNCTION__, MAX_COAL_LEADERS, bucket_index);
8271 break;
8272 }
8273 }
8274 p=memorystatus_get_next_proc_locked(&b, p, FALSE);
8275 }
8276
8277 if (nleaders == 0) {
8278 /* Nothing to sort */
8279 return(0);
8280 }
8281
8282 /*
8283 * Sort the coalition leader array, from smallest coalition page count
8284 * to largest coalition page count. When inserted in the priority bucket,
8285 * smallest coalition is handled first, resulting in the last to be jetsammed.
8286 */
8287 if (nleaders > 1) {
8288 qsort(leaders, nleaders, sizeof(memstat_sort_info_t), memstat_asc_cmp);
8289 }
8290
8291 #if 0
8292 for (i = 0; i < nleaders; i++) {
8293 printf("%s: coal_leader[%d of %d] pid[%d] pages[%llu] ntasks[%d]\n",
8294 __FUNCTION__, i, nleaders, leaders[i].msi_pid, leaders[i].msi_page_count,
8295 leaders[i].msi_ntasks);
8296 }
8297 #endif
8298
8299 /*
8300 * During coalition sorting, processes in a priority band are rearranged
8301 * by being re-inserted at the head of the queue. So, when handling a
8302 * list, the first process that gets moved to the head of the queue,
8303 * ultimately gets pushed toward the queue tail, and hence, jetsams last.
8304 *
8305 * So, for example, the coalition leader is expected to jetsam last,
8306 * after its coalition members. Therefore, the coalition leader is
8307 * inserted at the head of the queue first.
8308 *
8309 * After processing a coalition, the jetsam order is as follows:
8310 * undefs(jetsam first), extensions, xpc services, leader(jetsam last)
8311 */
8312
8313 /*
8314 * Coalition members are rearranged in the priority bucket here,
8315 * based on their coalition role.
8316 */
8317 total_pids_moved = 0;
8318 for (i=0; i < nleaders; i++) {
8319
8320 /* a bit of bookkeeping */
8321 pids_moved = 0;
8322
8323 /* Coalition leaders are jetsammed last, so move into place first */
8324 pid_list[0] = leaders[i].msi_pid;
8325 pids_moved += memorystatus_move_list_locked(bucket_index, pid_list, 1);
8326
8327 /* xpc services should jetsam after extensions */
8328 ntasks = coalition_get_pid_list (leaders[i].msi_coal, COALITION_ROLEMASK_XPC,
8329 coal_sort_order, pid_list, MAX_SORT_PIDS);
8330
8331 if (ntasks > 0) {
8332 pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8333 (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8334 }
8335
8336 /* extensions should jetsam after unmarked processes */
8337 ntasks = coalition_get_pid_list (leaders[i].msi_coal, COALITION_ROLEMASK_EXT,
8338 coal_sort_order, pid_list, MAX_SORT_PIDS);
8339
8340 if (ntasks > 0) {
8341 pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8342 (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8343 }
8344
8345 /* undefined coalition members should be the first to jetsam */
8346 ntasks = coalition_get_pid_list (leaders[i].msi_coal, COALITION_ROLEMASK_UNDEF,
8347 coal_sort_order, pid_list, MAX_SORT_PIDS);
8348
8349 if (ntasks > 0) {
8350 pids_moved += memorystatus_move_list_locked(bucket_index, pid_list,
8351 (ntasks <= MAX_SORT_PIDS ? ntasks : MAX_SORT_PIDS));
8352 }
8353
8354 #if 0
8355 if (pids_moved == leaders[i].msi_ntasks) {
8356 /*
8357 * All the pids in the coalition were found in this band.
8358 */
8359 printf("%s: pids_moved[%d] equal total coalition ntasks[%d] \n", __FUNCTION__,
8360 pids_moved, leaders[i].msi_ntasks);
8361 } else if (pids_moved > leaders[i].msi_ntasks) {
8362 /*
8363 * Apparently new coalition members showed up during the sort?
8364 */
8365 printf("%s: pids_moved[%d] were greater than expected coalition ntasks[%d] \n", __FUNCTION__,
8366 pids_moved, leaders[i].msi_ntasks);
8367 } else {
8368 /*
8369 * Apparently not all the pids in the coalition were found in this band?
8370 */
8371 printf("%s: pids_moved[%d] were less than expected coalition ntasks[%d] \n", __FUNCTION__,
8372 pids_moved, leaders[i].msi_ntasks);
8373 }
8374 #endif
8375
8376 total_pids_moved += pids_moved;
8377
8378 } /* end for */
8379
8380 return(total_pids_moved);
8381 }
8382
8383
8384 /*
8385 * Traverse a list of pids, searching for each within the priority band provided.
8386 * If pid is found, move it to the front of the priority band.
8387 * Never searches outside the priority band provided.
8388 *
8389 * Input:
8390 * bucket_index - jetsam priority band.
8391 * pid_list - pointer to a list of pids.
8392 * list_sz - number of pids in the list.
8393 *
8394 * Pid list ordering is important in that,
8395 * pid_list[n] is expected to jetsam ahead of pid_list[n+1].
8396 * The sort_order is set by the coalition default.
8397 *
8398 * Return:
8399 * the number of pids found and hence moved within the priority band.
8400 */
8401 static int
8402 memorystatus_move_list_locked(unsigned int bucket_index, pid_t *pid_list, int list_sz)
8403 {
8404 memstat_bucket_t *current_bucket;
8405 int i;
8406 int found_pids = 0;
8407
8408 if ((pid_list == NULL) || (list_sz <= 0)) {
8409 return(0);
8410 }
8411
8412 if (bucket_index >= MEMSTAT_BUCKET_COUNT) {
8413 return(0);
8414 }
8415
8416 current_bucket = &memstat_bucket[bucket_index];
8417 for (i=0; i < list_sz; i++) {
8418 unsigned int b = bucket_index;
8419 proc_t p = NULL;
8420 proc_t aProc = NULL;
8421 pid_t aPid;
8422 int list_index;
8423
8424 list_index = ((list_sz - 1) - i);
8425 aPid = pid_list[list_index];
8426
8427 /* never search beyond bucket_index provided */
8428 p = memorystatus_get_first_proc_locked(&b, FALSE);
8429 while (p) {
8430 if (p->p_pid == aPid) {
8431 aProc = p;
8432 break;
8433 }
8434 p = memorystatus_get_next_proc_locked(&b, p, FALSE);
8435 }
8436
8437 if (aProc == NULL) {
8438 /* pid not found in this band, just skip it */
8439 continue;
8440 } else {
8441 TAILQ_REMOVE(&current_bucket->list, aProc, p_memstat_list);
8442 TAILQ_INSERT_HEAD(&current_bucket->list, aProc, p_memstat_list);
8443 found_pids++;
8444 }
8445 }
8446 return(found_pids);
8447 }
8448 #endif /* CONFIG_JETSAM */