xref: /xnu-8020.140.41/bsd/sys/kern_memorystatus.h (revision 27b03b360a988dfd3dfdf34262bb0042026747cc)
1 /*
2  * Copyright (c) 2006-2018 Apple Computer, Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #ifndef SYS_MEMORYSTATUS_H
30 #define SYS_MEMORYSTATUS_H
31 
32 #include <sys/time.h>
33 #include <mach_debug/zone_info.h>
34 #include <sys/proc.h>
35 #include <sys/reason.h>
36 
37 #define MEMORYSTATUS_ENTITLEMENT "com.apple.private.memorystatus"
38 
39 #define JETSAM_PRIORITY_REVISION                  2
40 
41 #define JETSAM_PRIORITY_IDLE_HEAD                -2
42 /* The value -1 is an alias to JETSAM_PRIORITY_DEFAULT */
43 #define JETSAM_PRIORITY_IDLE                      0
44 #define JETSAM_PRIORITY_IDLE_DEFERRED             1 /* Keeping this around till all xnu_quick_tests can be moved away from it.*/
45 #define JETSAM_PRIORITY_AGING_BAND1               JETSAM_PRIORITY_IDLE_DEFERRED
46 #define JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC  2
47 #define JETSAM_PRIORITY_AGING_BAND2               JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC
48 #define JETSAM_PRIORITY_BACKGROUND                3
49 /*
50  * NB: This band is no longer used by mail, but IS used by many active
51  * processes doing background work.
52  */
53 #define JETSAM_PRIORITY_MAIL                      4
54 #define JETSAM_PRIORITY_ELEVATED_INACTIVE         JETSAM_PRIORITY_MAIL
55 #define JETSAM_PRIORITY_PHONE                     5
56 #define JETSAM_PRIORITY_UI_SUPPORT                8
57 #define JETSAM_PRIORITY_FOREGROUND_SUPPORT        9
58 #define JETSAM_PRIORITY_FOREGROUND               10
59 #define JETSAM_PRIORITY_AUDIO_AND_ACCESSORY      12
60 #define JETSAM_PRIORITY_CONDUCTOR                13
61 #define JETSAM_PRIORITY_DRIVER_APPLE             15
62 #define JETSAM_PRIORITY_HOME                     16
63 #define JETSAM_PRIORITY_EXECUTIVE                17
64 #define JETSAM_PRIORITY_IMPORTANT                18
65 #define JETSAM_PRIORITY_CRITICAL                 19
66 
67 #define JETSAM_PRIORITY_MAX                      21
68 
69 /* TODO - tune. This should probably be lower priority */
70 #define JETSAM_PRIORITY_DEFAULT                  18
71 #define JETSAM_PRIORITY_TELEPHONY                19
72 
73 /* Compatibility */
74 #define DEFAULT_JETSAM_PRIORITY                  18
75 
76 /*
77  * The deferral time used by default for apps and daemons in all aging
78  * policies except kJetsamAgingPolicySysProcsReclaimedFirst is
79  * DEFERRED_IDLE_EXIT_TIME_SECS.
80  *
81  * For kJetsamAgingPolicySysProcsReclaimedFirst,
82  *
83  * Daemons: The actual idle deferred time for the daemon is based on
84  * the relaunch behavior of the daemon. The relaunch behavior determines
85  * the scaling factor applied to DEFERRED_IDLE_EXIT_TIME_SECS. See
86  * kJetsamSysProcsIdleDelayTime* ratios defined in kern_memorystatus.c
87  *
88  * Apps: The apps are aged for DEFERRED_IDLE_EXIT_TIME_SECS factored
89  * by kJetsamAppsIdleDelayTimeRatio.
90  */
91 #define DEFERRED_IDLE_EXIT_TIME_SECS             10
92 
93 #define KEV_MEMORYSTATUS_SUBCLASS                 3
94 
95 enum {
96 	kMemorystatusLevelNote = 1,
97 	kMemorystatusSnapshotNote = 2,
98 	kMemorystatusFreezeNote = 3,
99 	kMemorystatusPressureNote = 4
100 };
101 
102 enum {
103 	kMemorystatusLevelAny = -1,
104 	kMemorystatusLevelNormal = 0,
105 	kMemorystatusLevelWarning = 1,
106 	kMemorystatusLevelUrgent = 2,
107 	kMemorystatusLevelCritical = 3
108 };
109 
110 typedef struct memorystatus_priority_entry {
111 	pid_t pid;
112 	int32_t priority;
113 	uint64_t user_data;
114 	int32_t limit;  /* MB */
115 	uint32_t state;
116 } memorystatus_priority_entry_t;
117 
118 /*
119  * This should be the structure to specify different properties
120  * for processes (group or single) from user-space. Unfortunately,
121  * we can't move to it completely because the priority_entry structure
122  * above has been in use for a while now. We'll have to deprecate it.
123  *
124  * To support new fields/properties, we will add a new structure with a
125  * new version and a new size.
126  */
127 #define MEMORYSTATUS_MPE_VERSION_1              1
128 
129 #define MEMORYSTATUS_MPE_VERSION_1_SIZE         sizeof(struct memorystatus_properties_entry_v1)
130 
131 typedef struct memorystatus_properties_entry_v1 {
132 	int version;
133 	pid_t pid;
134 	int32_t priority;
135 	int use_probability;
136 	uint64_t user_data;
137 	int32_t limit;  /* MB */
138 	uint32_t state;
139 	char proc_name[MAXCOMLEN + 1];
140 	char __pad1[3];
141 } memorystatus_properties_entry_v1_t;
142 
143 /*
144  * Represents a freeze or demotion candidate.
145  */
146 typedef struct memorystatus_properties_freeze_entry_v1 {
147 	int version;
148 	pid_t pid;
149 	uint32_t priority;
150 	char proc_name[(2 * MAXCOMLEN) + 1];
151 	char __pad1[3];
152 } memorystatus_properties_freeze_entry_v1;
153 
154 typedef struct memorystatus_kernel_stats {
155 	uint32_t free_pages;
156 	uint32_t active_pages;
157 	uint32_t inactive_pages;
158 	uint32_t throttled_pages;
159 	uint32_t purgeable_pages;
160 	uint32_t wired_pages;
161 	uint32_t speculative_pages;
162 	uint32_t filebacked_pages;
163 	uint32_t anonymous_pages;
164 	uint32_t compressor_pages;
165 	uint64_t compressions;
166 	uint64_t decompressions;
167 	uint64_t total_uncompressed_pages_in_compressor;
168 	uint64_t zone_map_size;
169 	uint64_t zone_map_capacity;
170 	uint64_t largest_zone_size;
171 	char     largest_zone_name[MACH_ZONE_NAME_MAX_LEN];
172 } memorystatus_kernel_stats_t;
173 
174 typedef enum memorystatus_freeze_skip_reason {
175 	kMemorystatusFreezeSkipReasonNone = 0,
176 	kMemorystatusFreezeSkipReasonExcessSharedMemory = 1,
177 	kMemorystatusFreezeSkipReasonLowPrivateSharedRatio = 2,
178 	kMemorystatusFreezeSkipReasonNoCompressorSpace = 3,
179 	kMemorystatusFreezeSkipReasonNoSwapSpace = 4,
180 	kMemorystatusFreezeSkipReasonBelowMinPages = 5,
181 	kMemorystatusFreezeSkipReasonLowProbOfUse = 6,
182 	kMemorystatusFreezeSkipReasonOther = 7,
183 	kMemorystatusFreezeSkipReasonOutOfBudget = 8,
184 	kMemorystatusFreezeSkipReasonOutOfSlots = 9,
185 	kMemorystatusFreezeSkipReasonDisabled = 10,
186 	kMemorystatusFreezeSkipReasonElevated = 11,
187 	_kMemorystatusFreezeSkipReasonMax
188 } memorystatus_freeze_skip_reason_t;
189 /*
190 ** This is a variable-length struct.
191 ** Allocate a buffer of the size returned by the sysctl, cast to a memorystatus_snapshot_t *
192 */
193 
194 typedef struct jetsam_snapshot_entry {
195 	pid_t    pid;
196 	char     name[(2 * MAXCOMLEN) + 1];
197 	int32_t  priority;
198 	uint32_t state;
199 	uint32_t fds;
200 	memorystatus_freeze_skip_reason_t jse_freeze_skip_reason; /* why wasn't this process frozen? */
201 	uint8_t  uuid[16];
202 	uint64_t user_data;
203 	uint64_t killed;
204 	uint64_t pages;
205 	uint64_t max_pages_lifetime;
206 	uint64_t purgeable_pages;
207 	uint64_t jse_internal_pages;
208 	uint64_t jse_internal_compressed_pages;
209 	uint64_t jse_purgeable_nonvolatile_pages;
210 	uint64_t jse_purgeable_nonvolatile_compressed_pages;
211 	uint64_t jse_alternate_accounting_pages;
212 	uint64_t jse_alternate_accounting_compressed_pages;
213 	uint64_t jse_iokit_mapped_pages;
214 	uint64_t jse_page_table_pages;
215 	uint64_t jse_memory_region_count;
216 	uint64_t jse_gencount;                  /* memorystatus_thread generation counter */
217 	uint64_t jse_starttime;                 /* absolute time when process starts */
218 	uint64_t jse_killtime;                  /* absolute time when jetsam chooses to kill a process */
219 	uint64_t jse_idle_delta;                /* time spent in idle band */
220 	uint64_t jse_coalition_jetsam_id;       /* we only expose coalition id for COALITION_TYPE_JETSAM */
221 	struct timeval64 cpu_time;
222 	uint64_t jse_thaw_count;
223 	uint64_t jse_frozen_to_swap_pages;
224 } memorystatus_jetsam_snapshot_entry_t;
225 
226 typedef struct jetsam_snapshot {
227 	uint64_t snapshot_time;                 /* absolute time snapshot was initialized */
228 	uint64_t notification_time;             /* absolute time snapshot was consumed */
229 	uint64_t js_gencount;                   /* memorystatus_thread generation counter */
230 	memorystatus_kernel_stats_t stats;      /* system stat when snapshot is initialized */
231 	size_t entry_count;
232 	memorystatus_jetsam_snapshot_entry_t entries[];
233 } memorystatus_jetsam_snapshot_t;
234 
235 /* TODO - deprecate; see <rdar://problem/12969599> */
236 #define kMaxSnapshotEntries 192
237 
238 /*
239  * default jetsam snapshot support
240  */
241 extern memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot;
242 extern memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot_copy;
243 #if CONFIG_FREEZE
244 extern memorystatus_jetsam_snapshot_t *memorystatus_jetsam_snapshot_freezer;
245 extern unsigned int memorystatus_jetsam_snapshot_freezer_max;
246 extern unsigned int memorystatus_jetsam_snapshot_freezer_size;
247 #endif /* CONFIG_FREEZE */
248 extern unsigned int memorystatus_jetsam_snapshot_count;
249 extern unsigned int memorystatus_jetsam_snapshot_copy_count;
250 extern unsigned int memorystatus_jetsam_snapshot_max;
251 extern unsigned int memorystatus_jetsam_snapshot_size;
252 extern uint64_t memorystatus_jetsam_snapshot_last_timestamp;
253 extern uint64_t memorystatus_jetsam_snapshot_timeout;
254 #define memorystatus_jetsam_snapshot_list memorystatus_jetsam_snapshot->entries
255 #define JETSAM_SNAPSHOT_TIMEOUT_SECS 30
256 
257 /* General memorystatus stuff */
258 
259 extern uint64_t memorystatus_sysprocs_idle_delay_time;
260 extern uint64_t memorystatus_apps_idle_delay_time;
261 
262 /* State */
263 #define kMemorystatusSuspended        0x01
264 #define kMemorystatusFrozen           0x02
265 #define kMemorystatusWasThawed        0x04
266 #define kMemorystatusTracked          0x08
267 #define kMemorystatusSupportsIdleExit 0x10
268 #define kMemorystatusDirty            0x20
269 #define kMemorystatusAssertion        0x40
270 
271 /*
272  * Jetsam exit reason definitions - related to memorystatus
273  *
274  * When adding new exit reasons also update:
275  *	JETSAM_REASON_MEMORYSTATUS_MAX
276  *	kMemorystatusKilled... Cause enum
277  *	memorystatus_kill_cause_name[]
278  */
279 #define JETSAM_REASON_INVALID                                                           0
280 #define JETSAM_REASON_GENERIC                                                           1
281 #define JETSAM_REASON_MEMORY_HIGHWATER                                          2
282 #define JETSAM_REASON_VNODE                                                                     3
283 #define JETSAM_REASON_MEMORY_VMPAGESHORTAGE                                     4
284 #define JETSAM_REASON_MEMORY_PROCTHRASHING                                      5
285 #define JETSAM_REASON_MEMORY_FCTHRASHING                                        6
286 #define JETSAM_REASON_MEMORY_PERPROCESSLIMIT                            7
287 #define JETSAM_REASON_MEMORY_DISK_SPACE_SHORTAGE                        8
288 #define JETSAM_REASON_MEMORY_IDLE_EXIT                                          9
289 #define JETSAM_REASON_ZONE_MAP_EXHAUSTION                                       10
290 #define JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING                     11
291 #define JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE        12
292 #define JETSAM_REASON_LOWSWAP                                   13
293 #define JETSAM_REASON_MEMORY_SUSTAINED_PRESSURE                 14
294 #define JETSAM_REASON_MEMORYSTATUS_MAX  JETSAM_REASON_MEMORY_SUSTAINED_PRESSURE
295 
296 /*
297  * Jetsam exit reason definitions - not related to memorystatus
298  */
299 #define JETSAM_REASON_CPULIMIT                  100
300 
301 /* Cause */
302 enum {
303 	kMemorystatusInvalid                                                    = JETSAM_REASON_INVALID,
304 	kMemorystatusKilled                                                             = JETSAM_REASON_GENERIC,
305 	kMemorystatusKilledHiwat                                                = JETSAM_REASON_MEMORY_HIGHWATER,
306 	kMemorystatusKilledVnodes                                               = JETSAM_REASON_VNODE,
307 	kMemorystatusKilledVMPageShortage                               = JETSAM_REASON_MEMORY_VMPAGESHORTAGE,
308 	kMemorystatusKilledProcThrashing                                = JETSAM_REASON_MEMORY_PROCTHRASHING,
309 	kMemorystatusKilledFCThrashing                                  = JETSAM_REASON_MEMORY_FCTHRASHING,
310 	kMemorystatusKilledPerProcessLimit                              = JETSAM_REASON_MEMORY_PERPROCESSLIMIT,
311 	kMemorystatusKilledDiskSpaceShortage                    = JETSAM_REASON_MEMORY_DISK_SPACE_SHORTAGE,
312 	kMemorystatusKilledIdleExit                                             = JETSAM_REASON_MEMORY_IDLE_EXIT,
313 	kMemorystatusKilledZoneMapExhaustion                    = JETSAM_REASON_ZONE_MAP_EXHAUSTION,
314 	kMemorystatusKilledVMCompressorThrashing                = JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING,
315 	kMemorystatusKilledVMCompressorSpaceShortage    = JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE,
316 	kMemorystatusKilledLowSwap                      = JETSAM_REASON_LOWSWAP,
317 	kMemorystatusKilledSustainedPressure            = JETSAM_REASON_MEMORY_SUSTAINED_PRESSURE
318 };
319 
320 /*
321  * For backwards compatibility
322  * Keeping these around for external users (e.g. ReportCrash, Ariadne).
323  * TODO: Remove once they stop using these.
324  */
325 #define kMemorystatusKilledDiagnostic           kMemorystatusKilledDiskSpaceShortage
326 #define kMemorystatusKilledVMThrashing          kMemorystatusKilledVMCompressorThrashing
327 #define JETSAM_REASON_MEMORY_VMTHRASHING        JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING
328 
329 /* Memorystatus control */
330 #define MEMORYSTATUS_BUFFERSIZE_MAX 65536
331 
332 #ifndef KERNEL
333 __BEGIN_DECLS
334 int memorystatus_get_level(user_addr_t level);
335 int memorystatus_control(uint32_t command, int32_t pid, uint32_t flags, void *buffer, size_t buffersize);
336 __END_DECLS
337 #endif
338 
339 /* Commands */
340 #define MEMORYSTATUS_CMD_GET_PRIORITY_LIST            1
341 #define MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES      2
342 #define MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT          3
343 #define MEMORYSTATUS_CMD_GET_PRESSURE_STATUS          4
344 #define MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK   5    /* Set active memory limit = inactive memory limit, both non-fatal	*/
345 #define MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT        6    /* Set active memory limit = inactive memory limit, both fatal	*/
346 #define MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES      7    /* Set memory limits plus attributes independently			*/
347 #define MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES      8    /* Get memory limits plus attributes					*/
348 #define MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_ENABLE   9    /* Set the task's status as a privileged listener w.r.t memory notifications  */
349 #define MEMORYSTATUS_CMD_PRIVILEGED_LISTENER_DISABLE  10   /* Reset the task's status as a privileged listener w.r.t memory notifications  */
350 #define MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_ENABLE  11   /* Enable the 'lenient' mode for aggressive jetsam. See comments in kern_memorystatus.c near the top. */
351 #define MEMORYSTATUS_CMD_AGGRESSIVE_JETSAM_LENIENT_MODE_DISABLE 12   /* Disable the 'lenient' mode for aggressive jetsam. */
352 #define MEMORYSTATUS_CMD_GET_MEMLIMIT_EXCESS          13   /* Compute how much a process's phys_footprint exceeds inactive memory limit */
353 #define MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE         14 /* Set the inactive jetsam band for a process to JETSAM_PRIORITY_ELEVATED_INACTIVE */
354 #define MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_DISABLE        15 /* Reset the inactive jetsam band for a process to the default band (0)*/
355 #define MEMORYSTATUS_CMD_SET_PROCESS_IS_MANAGED       16   /* (Re-)Set state on a process that marks it as (un-)managed by a system entity e.g. assertiond */
356 #define MEMORYSTATUS_CMD_GET_PROCESS_IS_MANAGED       17   /* Return the 'managed' status of a process */
357 #define MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE     18   /* Is the process eligible for freezing? Apps and extensions can pass in FALSE to opt out of freezing, i.e.,
358 	                                                    *  if they would prefer being jetsam'ed in the idle band to being frozen in an elevated band. */
359 #define MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE     19   /* Return the freezable state of a process. */
360 
361 #define MEMORYSTATUS_CMD_FREEZER_CONTROL              20
362 
363 #define MEMORYSTATUS_CMD_GET_AGGRESSIVE_JETSAM_LENIENT_MODE      21   /* Query if the lenient mode for aggressive jetsam is enabled. */
364 
365 #define MEMORYSTATUS_CMD_INCREASE_JETSAM_TASK_LIMIT   22   /* Used by DYLD to increase the jetsam active and inactive limits, when using roots */
366 
367 #if PRIVATE
368 #define MEMORYSTATUS_CMD_SET_TESTING_PID 23 /* Used by unit tests in the development kernel only. */
369 #endif /* PRIVATE */
370 
371 #define MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN 24 /* Check if the process is frozen. */
372 
373 /* Commands that act on a group of processes */
374 #define MEMORYSTATUS_CMD_GRP_SET_PROPERTIES           100
375 
376 #if PRIVATE
377 /* Test commands */
378 
379 /* Trigger forced jetsam */
380 #define MEMORYSTATUS_CMD_TEST_JETSAM            1000
381 #define MEMORYSTATUS_CMD_TEST_JETSAM_SORT       1001
382 
383 /* Select priority band sort order */
384 #define JETSAM_SORT_NOSORT      0
385 #define JETSAM_SORT_DEFAULT     1
386 
387 #endif /* PRIVATE */
388 
389 /* memorystatus_control() flags */
390 
391 #define MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND           0x1     /* A populated snapshot buffer is returned on demand */
392 #define MEMORYSTATUS_FLAGS_SNAPSHOT_AT_BOOT             0x2     /* Returns a snapshot with memstats collected at boot */
393 #define MEMORYSTATUS_FLAGS_SNAPSHOT_COPY                0x4     /* No longer supported. Used to return the previously populated snapshot created by the system */
394 #define MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY             0x8     /* Set jetsam priorities for a group of pids */
395 #define MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY          0x10    /* Set probability of use for a group of processes */
396 
397 #if PRIVATE
398 #define MEMORYSTATUS_FLAGS_SET_TESTING_PID     0x20 /* Only used by xnu unit tests. */
399 #define MEMORYSTATUS_FLAGS_UNSET_TESTING_PID   0x40 /* Only used by xnu unit tests. */
400 #endif /* PRIVATE */
401 
402 #define MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER             0x80    /* A snapshot buffer containing app kills since last consumption */
403 
404 #define MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY      0x100   /* Set a new ordered list of freeze candidates */
405 #define MEMORYSTATUS_FLAGS_GRP_SET_DEMOTE_PRIORITY      0x200   /* Set a new ordered list of demote candidates */
406 /*
407  * For use with memorystatus_control:
408  * MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT
409  *
410  * A jetsam snapshot is initialized when a non-idle
411  * jetsam event occurs.  The data is held in the
412  * buffer until it is reaped. This is the default
413  * behavior.
414  *
415  * Flags change the default behavior:
416  *	Demand mode - this is an on_demand snapshot,
417  *	meaning data is populated upon request.
418  *
419  *	Boot mode - this is a snapshot of
420  *	memstats collected before loading the
421  *	init program.  Once collected, these
422  *	stats do not change.  In this mode,
423  *	the snapshot entry_count is always 0.
424  *
425  *	Copy mode - this returns the previous snapshot
426  *      collected by the system. The current snaphshot
427  *	might be only half populated.
428  *
429  * Snapshots are inherently racey between request
430  * for buffer size and actual data compilation.
431  */
432 
433 /* These definitions are required for backwards compatibility */
434 #define MEMORYSTATUS_SNAPSHOT_ON_DEMAND         MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND
435 #define MEMORYSTATUS_SNAPSHOT_AT_BOOT           MEMORYSTATUS_FLAGS_SNAPSHOT_AT_BOOT
436 #define MEMORYSTATUS_SNAPSHOT_COPY              MEMORYSTATUS_FLAGS_SNAPSHOT_COPY
437 
438 /*
439  * For use with memorystatus_control:
440  * MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES
441  */
442 typedef struct memorystatus_priority_properties {
443 	int32_t  priority;
444 	uint64_t user_data;
445 } memorystatus_priority_properties_t;
446 
447 /*
448  * Inform the kernel that setting the priority property is driven by assertions.
449  */
450 #define MEMORYSTATUS_SET_PRIORITY_ASSERTION     0x1
451 
452 /*
453  * For use with memorystatus_control:
454  * MEMORYSTATUS_CMD_SET_MEMLIMIT_PROPERTIES
455  * MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES
456  */
457 typedef struct memorystatus_memlimit_properties {
458 	int32_t memlimit_active;                /* jetsam memory limit (in MB) when process is active */
459 	uint32_t memlimit_active_attr;
460 	int32_t memlimit_inactive;              /* jetsam memory limit (in MB) when process is inactive */
461 	uint32_t memlimit_inactive_attr;
462 } memorystatus_memlimit_properties_t;
463 
464 typedef struct memorystatus_memlimit_properties2 {
465 	memorystatus_memlimit_properties_t v1;
466 	uint32_t memlimit_increase;             /* jetsam memory limit increase (in MB) for active and inactive states */
467 	uint32_t memlimit_increase_bytes;       /* bytes used to determine the jetsam memory limit increase, for active and inactive states */
468 } memorystatus_memlimit_properties2_t;
469 
470 #define MEMORYSTATUS_MEMLIMIT_ATTR_FATAL        0x1     /* if set, exceeding the memlimit is fatal */
471 
472 #ifdef XNU_KERNEL_PRIVATE
473 
474 /*
475  * A process will be killed immediately if it crosses a memory limit marked as fatal.
476  * Fatal limit types are the
477  *	- default system-wide task limit
478  *	- per-task custom memory limit
479  *
480  * A process with a non-fatal memory limit can exceed that limit, but becomes an early
481  * candidate for jetsam when the device is under memory pressure.
482  * Non-fatal limit types are the
483  *	- high-water-mark limit
484  *
485  * Processes that opt into dirty tracking are evaluated
486  * based on clean vs dirty state.
487  *      dirty ==> active
488  *      clean ==> inactive
489  *
490  * Processes that do not opt into dirty tracking are
491  * evalulated based on priority level.
492  *      Foreground or above ==> active
493  *      Below Foreground    ==> inactive
494  */
495 
496 /*
497  * p_memstat_state flag holds
498  *	- in kernel process state and memlimit state
499  */
500 
501 #define P_MEMSTAT_SUSPENDED            0x00000001 /* Process is suspended and likely in the IDLE band */
502 #define P_MEMSTAT_FROZEN               0x00000002 /* Process has some state on disk. It should be suspended */
503 #define P_MEMSTAT_FREEZE_DISABLED      0x00000004 /* Process isn't freeze-eligible and will not be frozen */
504 #define P_MEMSTAT_ERROR                0x00000008 /* Process couldn't be jetsammed for some reason. Transient state so jetsam can skip it next time it sees it */
505 #define P_MEMSTAT_LOCKED               0x00000010 /* Process is being actively worked on behind the proc_list_lock */
506 #define P_MEMSTAT_TERMINATED           0x00000020 /* Process is exiting */
507 #define P_MEMSTAT_FREEZE_IGNORE        0x00000040 /* Process was evaluated by freezer and will be ignored till the next time it goes active and does something */
508 #define P_MEMSTAT_PRIORITYUPDATED      0x00000080 /* Process had its jetsam priority updated */
509 #define P_MEMSTAT_FOREGROUND           0x00000100 /* Process is in the FG jetsam band...unused??? */
510 #define P_MEMSTAT_REFREEZE_ELIGIBLE    0x00000400 /* Process was once thawed i.e. its state was brought back from disk. It is now refreeze eligible.*/
511 #define P_MEMSTAT_MANAGED              0x00000800 /* Process is managed by assertiond i.e. is either application or extension */
512 #define P_MEMSTAT_INTERNAL             0x00001000 /* Process is a system-critical-not-be-jetsammed process i.e. launchd */
513 #define P_MEMSTAT_FATAL_MEMLIMIT                  0x00002000   /* current fatal state of the process's memlimit */
514 #define P_MEMSTAT_MEMLIMIT_ACTIVE_FATAL           0x00004000   /* if set, exceeding limit is fatal when the process is active   */
515 #define P_MEMSTAT_MEMLIMIT_INACTIVE_FATAL         0x00008000   /* if set, exceeding limit is fatal when the process is inactive */
516 #define P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND      0x00010000   /* if set, the process will go into this band & stay there when in the background instead
517 	                                                        *  of the aging bands and/or the IDLE band. */
518 #define P_MEMSTAT_PRIORITY_ASSERTION              0x00020000   /* jetsam priority is being driven by an assertion */
519 #define P_MEMSTAT_FREEZE_CONSIDERED               0x00040000   /* This process has been considered for the freezer. */
520 #define P_MEMSTAT_SKIP                            0x00080000   /* Process is temporarily ineligible for memory pressure kills. Used only on development & debug kernels to make corpses of buggy processes */
521 #define P_MEMSTAT_FROZEN_XPC_SERVICE              0x00100000   /* Process is an XPC service. Only used for freezer telemetry. */
522 #define P_MEMSTAT_FROZEN_FOCAL_THAW               0x00200000 /* Process has been thawed while focal in the current freezer interval. Only used for freezer telemetry. */
523 
524 /*
525  * p_memstat_relaunch_flags holds
526  *      - relaunch behavior when jetsammed
527  */
528 #define P_MEMSTAT_RELAUNCH_UNKNOWN      0x0
529 #define P_MEMSTAT_RELAUNCH_LOW          0x1
530 #define P_MEMSTAT_RELAUNCH_MED          0x2
531 #define P_MEMSTAT_RELAUNCH_HIGH         0x4
532 
533 /*
534  * Checking the p_memstat_state almost always requires the proc_list_lock
535  * because the jetsam thread could be on the other core changing the state.
536  *
537  * App -- almost always managed by a system process. Always have dirty tracking OFF. Can include extensions too.
538  * System Processes -- not managed by anybody. Always have dirty tracking ON. Can include extensions (here) too.
539  */
540 #define isApp(p)            ((p->p_memstat_state & P_MEMSTAT_MANAGED) || ! (p->p_memstat_dirty & P_DIRTY_TRACK))
541 #define isSysProc(p)            ( ! (p->p_memstat_state & P_MEMSTAT_MANAGED) || (p->p_memstat_dirty & P_DIRTY_TRACK))
542 
543 #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
544 
545 typedef struct memstat_bucket {
546 	TAILQ_HEAD(, proc) list;
547 	int count;
548 	int relaunch_high_count;
549 } memstat_bucket_t;
550 
551 extern memstat_bucket_t memstat_bucket[MEMSTAT_BUCKET_COUNT];
552 
553 /*
554  * Table that expresses the probability of a process
555  * being used in the next hour.
556  */
557 typedef struct memorystatus_internal_probabilities {
558 	char proc_name[MAXCOMLEN + 1];
559 	int use_probability;
560 } memorystatus_internal_probabilities_t;
561 
562 extern memorystatus_internal_probabilities_t *memorystatus_global_probabilities_table;
563 extern size_t memorystatus_global_probabilities_size;
564 
565 extern void memorystatus_init(void);
566 
567 extern void memorystatus_init_at_boot_snapshot(void);
568 
569 extern int memorystatus_add(proc_t p, boolean_t locked);
570 extern int memorystatus_update(proc_t p, int priority, uint64_t user_data, boolean_t is_assertion, boolean_t effective,
571     boolean_t update_memlimit, int32_t memlimit_active, boolean_t memlimit_active_is_fatal,
572     int32_t memlimit_inactive, boolean_t memlimit_inactive_is_fatal);
573 
574 /* Remove this process from jetsam bands for killing or freezing.
575  * The proc_list_lock is held by the caller.
576  * @param p: The process to remove.
577  * @return: 0 if successful. EAGAIN if the process can't be removed right now (because it's being frozen) or ESRCH.
578  */
579 extern int memorystatus_remove(proc_t p);
580 
581 int memorystatus_update_inactive_jetsam_priority_band(pid_t pid, uint32_t opflags, int priority, boolean_t effective_now);
582 int memorystatus_relaunch_flags_update(proc_t p, int relaunch_flags);
583 
584 extern int memorystatus_dirty_track(proc_t p, uint32_t pcontrol);
585 extern int memorystatus_dirty_set(proc_t p, boolean_t self, uint32_t pcontrol);
586 extern int memorystatus_dirty_get(proc_t p, boolean_t locked);
587 extern int memorystatus_dirty_clear(proc_t p, uint32_t pcontrol);
588 
589 extern int memorystatus_on_terminate(proc_t p);
590 
591 extern void memorystatus_on_suspend(proc_t p);
592 extern void memorystatus_on_resume(proc_t p);
593 extern void memorystatus_on_inactivity(proc_t p);
594 
595 extern void memorystatus_on_pageout_scan_end(void);
596 
597 /* Memorystatus kevent */
598 
599 void memorystatus_kevent_init(lck_grp_t *grp, lck_attr_t *attr);
600 
601 int memorystatus_knote_register(struct knote *kn);
602 void memorystatus_knote_unregister(struct knote *kn);
603 
604 #if CONFIG_MEMORYSTATUS
605 void memorystatus_log_exception(const int max_footprint_mb, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal);
606 void memorystatus_on_ledger_footprint_exceeded(int warning, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal);
607 void proc_memstat_skip(proc_t p, boolean_t set);
608 void memorystatus_proc_flags_unsafe(void * v, boolean_t *is_dirty, boolean_t *is_dirty_tracked, boolean_t *allow_idle_exit);
609 
610 #if __arm64__
611 void memorystatus_act_on_legacy_footprint_entitlement(proc_t p, boolean_t footprint_increase);
612 void memorystatus_act_on_ios13extended_footprint_entitlement(proc_t p);
613 void memorystatus_act_on_entitled_task_limit(proc_t p);
614 #endif /* __arm64__ */
615 
616 #endif /* CONFIG_MEMORYSTATUS */
617 
618 int memorystatus_get_pressure_status_kdp(void);
619 int  memorystatus_get_proccnt_upto_priority(int32_t max_bucket_index);
620 
621 #if CONFIG_JETSAM
622 
623 typedef enum memorystatus_policy {
624 	kPolicyDefault        = 0x0,
625 	kPolicyMoreFree       = 0x1,
626 } memorystatus_policy_t;
627 
628 boolean_t memorystatus_kill_on_VM_page_shortage(boolean_t async);
629 boolean_t memorystatus_kill_on_FC_thrashing(boolean_t async);
630 boolean_t memorystatus_kill_on_VM_compressor_thrashing(boolean_t async);
631 boolean_t memorystatus_kill_on_vnode_limit(void);
632 boolean_t memorystatus_kill_on_sustained_pressure(boolean_t async);
633 /*
634  * Attempt to kill the specified pid with the given reason.
635  * Consumes a reference on the jetsam_reason.
636  */
637 boolean_t memorystatus_kill_with_jetsam_reason_sync(pid_t pid, os_reason_t jetsam_reason);
638 
639 void jetsam_on_ledger_cpulimit_exceeded(void);
640 void memorystatus_fast_jetsam_override(boolean_t enable_override);
641 
642 #endif /* CONFIG_JETSAM */
643 
644 /* These are very verbose printfs(), enable with
645  * MEMORYSTATUS_DEBUG_LOG
646  */
647 #if MEMORYSTATUS_DEBUG_LOG
648 #define MEMORYSTATUS_DEBUG(cond, format, ...)      \
649 do {                                              \
650 if (cond) { printf(format, ##__VA_ARGS__); } \
651 } while(0)
652 #else
653 #define MEMORYSTATUS_DEBUG(cond, format, ...)
654 #endif
655 
656 boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid);
657 boolean_t memorystatus_kill_on_VM_compressor_space_shortage(boolean_t async);
658 void memorystatus_pages_update(unsigned int pages_avail);
659 boolean_t memorystatus_idle_exit_from_VM(void);
660 proc_t memorystatus_get_first_proc_locked(unsigned int *bucket_index, boolean_t search);
661 proc_t memorystatus_get_next_proc_locked(unsigned int *bucket_index, proc_t p, boolean_t search);
662 void memorystatus_get_task_page_counts(task_t task, uint32_t *footprint, uint32_t *max_footprint_lifetime, uint32_t *purgeable_pages);
663 void memorystatus_invalidate_idle_demotion_locked(proc_t p, boolean_t clean_state);
664 void memorystatus_update_priority_locked(proc_t p, int priority, boolean_t head_insert, boolean_t skip_demotion_check);
665 
666 extern bool memorystatus_task_has_increased_memory_limit_entitlement(task_t task);
667 
668 #if VM_PRESSURE_EVENTS
669 
670 extern kern_return_t memorystatus_update_vm_pressure(boolean_t);
671 
672 #if CONFIG_MEMORYSTATUS
673 /* Flags */
674 extern int memorystatus_low_mem_privileged_listener(uint32_t op_flags);
675 extern int memorystatus_send_pressure_note(int pid);
676 extern boolean_t memorystatus_is_foreground_locked(proc_t p);
677 extern boolean_t memorystatus_bg_pressure_eligible(proc_t p);
678 #endif /* CONFIG_MEMORYSTATUS */
679 
680 #endif /* VM_PRESSURE_EVENTS */
681 
682 #endif /* XNU_KERNEL_PRIVATE */
683 
684 #endif /* SYS_MEMORYSTATUS_H */
685