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