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