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