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