xref: /xnu-8020.121.3/osfmk/kern/task_policy.c (revision fdd8201d7b966f0c3ea610489d29bd841d358941)
1 /*
2  * Copyright (c) 2000-2020 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 #include <kern/policy_internal.h>
30 #include <mach/task_policy.h>
31 #include <mach/task.h>
32 #include <mach/mach_types.h>
33 #include <mach/task_server.h>
34 #include <kern/host.h>                  /* host_priv_self()        */
35 #include <mach/host_priv.h>             /* host_get_special_port() */
36 #include <mach/host_special_ports.h>    /* RESOURCE_NOTIFY_PORT    */
37 #include <kern/sched.h>
38 #include <kern/task.h>
39 #include <mach/thread_policy.h>
40 #include <sys/errno.h>
41 #include <sys/resource.h>
42 #include <machine/limits.h>
43 #include <kern/ledger.h>
44 #include <kern/thread_call.h>
45 #include <kern/sfi.h>
46 #include <kern/coalition.h>
47 #if CONFIG_TELEMETRY
48 #include <kern/telemetry.h>
49 #endif
50 #if !defined(XNU_TARGET_OS_OSX)
51 #include <kern/kalloc.h>
52 #include <sys/errno.h>
53 #endif /* !defined(XNU_TARGET_OS_OSX) */
54 
55 #if IMPORTANCE_INHERITANCE
56 #include <ipc/ipc_importance.h>
57 #if IMPORTANCE_TRACE
58 #include <mach/machine/sdt.h>
59 #endif /* IMPORTANCE_TRACE */
60 #endif /* IMPORTANCE_INHERITACE */
61 
62 #include <sys/kdebug.h>
63 
64 /*
65  *  Task Policy
66  *
67  *  This subsystem manages task and thread IO priority and backgrounding,
68  *  as well as importance inheritance, process suppression, task QoS, and apptype.
69  *  These properties have a suprising number of complex interactions, so they are
70  *  centralized here in one state machine to simplify the implementation of those interactions.
71  *
72  *  Architecture:
73  *  Threads and tasks have two policy fields: requested, effective.
74  *  Requested represents the wishes of each interface that influences task policy.
75  *  Effective represents the distillation of that policy into a set of behaviors.
76  *
77  *  Each thread making a modification in the policy system passes a 'pending' struct,
78  *  which tracks updates that will be applied after dropping the policy engine lock.
79  *
80  *  Each interface that has an input into the task policy state machine controls a field in requested.
81  *  If the interface has a getter, it returns what is in the field in requested, but that is
82  *  not necessarily what is actually in effect.
83  *
84  *  All kernel subsystems that behave differently based on task policy call into
85  *  the proc_get_effective_(task|thread)_policy functions, which return the decision of the task policy state machine
86  *  for that subsystem by querying only the 'effective' field.
87  *
88  *  Policy change operations:
89  *  Here are the steps to change a policy on a task or thread:
90  *  1) Lock task
91  *  2) Change requested field for the relevant policy
92  *  3) Run a task policy update, which recalculates effective based on requested,
93  *     then takes a diff between the old and new versions of requested and calls the relevant
94  *     other subsystems to apply these changes, and updates the pending field.
95  *  4) Unlock task
96  *  5) Run task policy update complete, which looks at the pending field to update
97  *     subsystems which cannot be touched while holding the task lock.
98  *
99  *  To add a new requested policy, add the field in the requested struct, the flavor in task.h,
100  *  the setter and getter in proc_(set|get)_task_policy*,
101  *  then set up the effects of that behavior in task_policy_update*. If the policy manifests
102  *  itself as a distinct effective policy, add it to the effective struct and add it to the
103  *  proc_get_effective_task_policy accessor.
104  *
105  *  Most policies are set via proc_set_task_policy, but policies that don't fit that interface
106  *  roll their own lock/set/update/unlock/complete code inside this file.
107  *
108  *
109  *  Suppression policy
110  *
111  *  These are a set of behaviors that can be requested for a task.  They currently have specific
112  *  implied actions when they're enabled, but they may be made customizable in the future.
113  *
114  *  When the affected task is boosted, we temporarily disable the suppression behaviors
115  *  so that the affected process has a chance to run so it can call the API to permanently
116  *  disable the suppression behaviors.
117  *
118  *  Locking
119  *
120  *  Changing task policy on a task takes the task lock.
121  *  Changing task policy on a thread takes the thread mutex.
122  *  Task policy changes that affect threads will take each thread's mutex to update it if necessary.
123  *
124  *  Querying the effective policy does not take a lock, because callers
125  *  may run in interrupt context or other place where locks are not OK.
126  *
127  *  This means that any notification of state change needs to be externally synchronized.
128  *  We do this by idempotent callouts after the state has changed to ask
129  *  other subsystems to update their view of the world.
130  *
131  * TODO: Move all cpu/wakes/io monitor code into a separate file
132  * TODO: Move all importance code over to importance subsystem
133  * TODO: Move all taskwatch code into a separate file
134  * TODO: Move all VM importance code into a separate file
135  */
136 
137 /* Task policy related helper functions */
138 static void proc_set_task_policy_locked(task_t task, int category, int flavor, int value, int value2);
139 
140 static void task_policy_update_locked(task_t task, task_pend_token_t pend_token);
141 static void task_policy_update_internal_locked(task_t task, bool in_create, task_pend_token_t pend_token);
142 
143 /* For attributes that have two scalars as input/output */
144 static void proc_set_task_policy2(task_t task, int category, int flavor, int value1, int value2);
145 static void proc_get_task_policy2(task_t task, int category, int flavor, int *value1, int *value2);
146 
147 static boolean_t task_policy_update_coalition_focal_tasks(task_t task, int prev_role, int next_role, task_pend_token_t pend_token);
148 
149 static uint64_t task_requested_bitfield(task_t task);
150 static uint64_t task_effective_bitfield(task_t task);
151 
152 /* Convenience functions for munging a policy bitfield into a tracepoint */
153 static uintptr_t trequested_0(task_t task);
154 static uintptr_t trequested_1(task_t task);
155 static uintptr_t teffective_0(task_t task);
156 static uintptr_t teffective_1(task_t task);
157 
158 /* CPU limits helper functions */
159 static int task_set_cpuusage(task_t task, uint8_t percentage, uint64_t interval, uint64_t deadline, int scope, int entitled);
160 static int task_get_cpuusage(task_t task, uint8_t *percentagep, uint64_t *intervalp, uint64_t *deadlinep, int *scope);
161 static int task_enable_cpumon_locked(task_t task);
162 static int task_disable_cpumon(task_t task);
163 static int task_clear_cpuusage_locked(task_t task, int cpumon_entitled);
164 static int task_apply_resource_actions(task_t task, int type);
165 static void task_action_cpuusage(thread_call_param_t param0, thread_call_param_t param1);
166 
167 #ifdef MACH_BSD
168 typedef struct proc *   proc_t;
169 int                     proc_pid(struct proc *proc);
170 extern int              proc_selfpid(void);
171 extern char *           proc_name_address(void *p);
172 extern char *           proc_best_name(proc_t proc);
173 
174 extern int proc_pidpathinfo_internal(proc_t p, uint64_t arg,
175     char *buffer, uint32_t buffersize,
176     int32_t *retval);
177 #endif /* MACH_BSD */
178 
179 
180 #if CONFIG_TASKWATCH
181 /* Taskwatch related helper functions */
182 static void set_thread_appbg(thread_t thread, int setbg, int importance);
183 static void add_taskwatch_locked(task_t task, task_watch_t * twp);
184 static void remove_taskwatch_locked(task_t task, task_watch_t * twp);
185 static void task_watch_lock(void);
186 static void task_watch_unlock(void);
187 static void apply_appstate_watchers(task_t task);
188 
189 typedef struct task_watcher {
190 	queue_chain_t   tw_links;       /* queueing of threads */
191 	task_t          tw_task;        /* task that is being watched */
192 	thread_t        tw_thread;      /* thread that is watching the watch_task */
193 	int             tw_state;       /* the current app state of the thread */
194 	int             tw_importance;  /* importance prior to backgrounding */
195 } task_watch_t;
196 
197 typedef struct thread_watchlist {
198 	thread_t        thread;         /* thread being worked on for taskwatch action */
199 	int             importance;     /* importance to be restored if thread is being made active */
200 } thread_watchlist_t;
201 
202 #endif /* CONFIG_TASKWATCH */
203 
204 extern int memorystatus_update_priority_for_appnap(proc_t p, boolean_t is_appnap);
205 
206 /* Importance Inheritance related helper functions */
207 
208 #if IMPORTANCE_INHERITANCE
209 
210 static void task_importance_mark_live_donor(task_t task, boolean_t donating);
211 static void task_importance_mark_receiver(task_t task, boolean_t receiving);
212 static void task_importance_mark_denap_receiver(task_t task, boolean_t denap);
213 
214 static boolean_t task_is_marked_live_importance_donor(task_t task);
215 static boolean_t task_is_importance_receiver(task_t task);
216 static boolean_t task_is_importance_denap_receiver(task_t task);
217 
218 static int task_importance_hold_internal_assertion(task_t target_task, uint32_t count);
219 
220 static void task_add_importance_watchport(task_t task, mach_port_t port, int *boostp);
221 static void task_importance_update_live_donor(task_t target_task);
222 
223 static void task_set_boost_locked(task_t task, boolean_t boost_active);
224 
225 #endif /* IMPORTANCE_INHERITANCE */
226 
227 #if IMPORTANCE_TRACE
228 #define __imptrace_only
229 #else /* IMPORTANCE_TRACE */
230 #define __imptrace_only __unused
231 #endif /* !IMPORTANCE_TRACE */
232 
233 #if IMPORTANCE_INHERITANCE
234 #define __imp_only
235 #else
236 #define __imp_only __unused
237 #endif
238 
239 /*
240  * Default parameters for certain policies
241  */
242 
243 int proc_standard_daemon_tier = THROTTLE_LEVEL_TIER1;
244 int proc_suppressed_disk_tier = THROTTLE_LEVEL_TIER1;
245 int proc_tal_disk_tier        = THROTTLE_LEVEL_TIER1;
246 
247 int proc_graphics_timer_qos   = (LATENCY_QOS_TIER_0 & 0xFF);
248 
249 const int proc_default_bg_iotier  = THROTTLE_LEVEL_TIER2;
250 
251 /* Latency/throughput QoS fields remain zeroed, i.e. TIER_UNSPECIFIED at creation */
252 const struct task_requested_policy default_task_requested_policy = {
253 	.trp_bg_iotier = proc_default_bg_iotier
254 };
255 const struct task_effective_policy default_task_effective_policy = {};
256 
257 /*
258  * Default parameters for CPU usage monitor.
259  *
260  * Default setting is 50% over 3 minutes.
261  */
262 #define         DEFAULT_CPUMON_PERCENTAGE 50
263 #define         DEFAULT_CPUMON_INTERVAL   (3 * 60)
264 
265 uint8_t         proc_max_cpumon_percentage;
266 uint64_t        proc_max_cpumon_interval;
267 
268 
269 kern_return_t
qos_latency_policy_validate(task_latency_qos_t ltier)270 qos_latency_policy_validate(task_latency_qos_t ltier)
271 {
272 	if ((ltier != LATENCY_QOS_TIER_UNSPECIFIED) &&
273 	    ((ltier > LATENCY_QOS_TIER_5) || (ltier < LATENCY_QOS_TIER_0))) {
274 		return KERN_INVALID_ARGUMENT;
275 	}
276 
277 	return KERN_SUCCESS;
278 }
279 
280 kern_return_t
qos_throughput_policy_validate(task_throughput_qos_t ttier)281 qos_throughput_policy_validate(task_throughput_qos_t ttier)
282 {
283 	if ((ttier != THROUGHPUT_QOS_TIER_UNSPECIFIED) &&
284 	    ((ttier > THROUGHPUT_QOS_TIER_5) || (ttier < THROUGHPUT_QOS_TIER_0))) {
285 		return KERN_INVALID_ARGUMENT;
286 	}
287 
288 	return KERN_SUCCESS;
289 }
290 
291 static kern_return_t
task_qos_policy_validate(task_qos_policy_t qosinfo,mach_msg_type_number_t count)292 task_qos_policy_validate(task_qos_policy_t qosinfo, mach_msg_type_number_t count)
293 {
294 	if (count < TASK_QOS_POLICY_COUNT) {
295 		return KERN_INVALID_ARGUMENT;
296 	}
297 
298 	task_latency_qos_t ltier = qosinfo->task_latency_qos_tier;
299 	task_throughput_qos_t ttier = qosinfo->task_throughput_qos_tier;
300 
301 	kern_return_t kr = qos_latency_policy_validate(ltier);
302 
303 	if (kr != KERN_SUCCESS) {
304 		return kr;
305 	}
306 
307 	kr = qos_throughput_policy_validate(ttier);
308 
309 	return kr;
310 }
311 
312 uint32_t
qos_extract(uint32_t qv)313 qos_extract(uint32_t qv)
314 {
315 	return qv & 0xFF;
316 }
317 
318 uint32_t
qos_latency_policy_package(uint32_t qv)319 qos_latency_policy_package(uint32_t qv)
320 {
321 	return (qv == LATENCY_QOS_TIER_UNSPECIFIED) ? LATENCY_QOS_TIER_UNSPECIFIED : ((0xFF << 16) | qv);
322 }
323 
324 uint32_t
qos_throughput_policy_package(uint32_t qv)325 qos_throughput_policy_package(uint32_t qv)
326 {
327 	return (qv == THROUGHPUT_QOS_TIER_UNSPECIFIED) ? THROUGHPUT_QOS_TIER_UNSPECIFIED : ((0xFE << 16) | qv);
328 }
329 
330 #define TASK_POLICY_SUPPRESSION_DISABLE  0x1
331 #define TASK_POLICY_SUPPRESSION_IOTIER2  0x2
332 #define TASK_POLICY_SUPPRESSION_NONDONOR 0x4
333 /* TEMPORARY boot-arg controlling task_policy suppression (App Nap) */
334 static boolean_t task_policy_suppression_flags = TASK_POLICY_SUPPRESSION_IOTIER2 |
335     TASK_POLICY_SUPPRESSION_NONDONOR;
336 
337 kern_return_t
task_policy_set(task_t task,task_policy_flavor_t flavor,task_policy_t policy_info,mach_msg_type_number_t count)338 task_policy_set(
339 	task_t                                  task,
340 	task_policy_flavor_t    flavor,
341 	task_policy_t                   policy_info,
342 	mach_msg_type_number_t  count)
343 {
344 	kern_return_t           result = KERN_SUCCESS;
345 
346 	if (task == TASK_NULL || task == kernel_task) {
347 		return KERN_INVALID_ARGUMENT;
348 	}
349 
350 	switch (flavor) {
351 	case TASK_CATEGORY_POLICY: {
352 		task_category_policy_t info = (task_category_policy_t)policy_info;
353 
354 		if (count < TASK_CATEGORY_POLICY_COUNT) {
355 			return KERN_INVALID_ARGUMENT;
356 		}
357 
358 #if !defined(XNU_TARGET_OS_OSX)
359 		/* On embedded, you can't modify your own role. */
360 		if (current_task() == task) {
361 			return KERN_INVALID_ARGUMENT;
362 		}
363 #endif
364 
365 		switch (info->role) {
366 		case TASK_FOREGROUND_APPLICATION:
367 		case TASK_BACKGROUND_APPLICATION:
368 		case TASK_DEFAULT_APPLICATION:
369 			proc_set_task_policy(task,
370 			    TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE,
371 			    info->role);
372 			break;
373 
374 		case TASK_CONTROL_APPLICATION:
375 			if (task != current_task() || !task_is_privileged(task)) {
376 				result = KERN_INVALID_ARGUMENT;
377 			} else {
378 				proc_set_task_policy(task,
379 				    TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE,
380 				    info->role);
381 			}
382 			break;
383 
384 		case TASK_GRAPHICS_SERVER:
385 			/* TODO: Restrict this role to FCFS <rdar://problem/12552788> */
386 			if (task != current_task() || !task_is_privileged(task)) {
387 				result = KERN_INVALID_ARGUMENT;
388 			} else {
389 				proc_set_task_policy(task,
390 				    TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE,
391 				    info->role);
392 			}
393 			break;
394 		default:
395 			result = KERN_INVALID_ARGUMENT;
396 			break;
397 		} /* switch (info->role) */
398 
399 		break;
400 	}
401 
402 /* Desired energy-efficiency/performance "quality-of-service" */
403 	case TASK_BASE_QOS_POLICY:
404 	case TASK_OVERRIDE_QOS_POLICY:
405 	{
406 		task_qos_policy_t qosinfo = (task_qos_policy_t)policy_info;
407 		kern_return_t kr = task_qos_policy_validate(qosinfo, count);
408 
409 		if (kr != KERN_SUCCESS) {
410 			return kr;
411 		}
412 
413 
414 		uint32_t lqos = qos_extract(qosinfo->task_latency_qos_tier);
415 		uint32_t tqos = qos_extract(qosinfo->task_throughput_qos_tier);
416 
417 		proc_set_task_policy2(task, TASK_POLICY_ATTRIBUTE,
418 		    flavor == TASK_BASE_QOS_POLICY ? TASK_POLICY_BASE_LATENCY_AND_THROUGHPUT_QOS : TASK_POLICY_OVERRIDE_LATENCY_AND_THROUGHPUT_QOS,
419 		    lqos, tqos);
420 	}
421 	break;
422 
423 	case TASK_BASE_LATENCY_QOS_POLICY:
424 	{
425 		task_qos_policy_t qosinfo = (task_qos_policy_t)policy_info;
426 		kern_return_t kr = task_qos_policy_validate(qosinfo, count);
427 
428 		if (kr != KERN_SUCCESS) {
429 			return kr;
430 		}
431 
432 		uint32_t lqos = qos_extract(qosinfo->task_latency_qos_tier);
433 
434 		proc_set_task_policy(task, TASK_POLICY_ATTRIBUTE, TASK_BASE_LATENCY_QOS_POLICY, lqos);
435 	}
436 	break;
437 
438 	case TASK_BASE_THROUGHPUT_QOS_POLICY:
439 	{
440 		task_qos_policy_t qosinfo = (task_qos_policy_t)policy_info;
441 		kern_return_t kr = task_qos_policy_validate(qosinfo, count);
442 
443 		if (kr != KERN_SUCCESS) {
444 			return kr;
445 		}
446 
447 		uint32_t tqos = qos_extract(qosinfo->task_throughput_qos_tier);
448 
449 		proc_set_task_policy(task, TASK_POLICY_ATTRIBUTE, TASK_BASE_THROUGHPUT_QOS_POLICY, tqos);
450 	}
451 	break;
452 
453 	case TASK_SUPPRESSION_POLICY:
454 	{
455 #if !defined(XNU_TARGET_OS_OSX)
456 		/*
457 		 * Suppression policy is not enabled for embedded
458 		 * because apps aren't marked as denap receivers
459 		 */
460 		result = KERN_INVALID_ARGUMENT;
461 		break;
462 #else /* !defined(XNU_TARGET_OS_OSX) */
463 
464 		task_suppression_policy_t info = (task_suppression_policy_t)policy_info;
465 
466 		if (count < TASK_SUPPRESSION_POLICY_COUNT) {
467 			return KERN_INVALID_ARGUMENT;
468 		}
469 
470 		struct task_qos_policy qosinfo;
471 
472 		qosinfo.task_latency_qos_tier = info->timer_throttle;
473 		qosinfo.task_throughput_qos_tier = info->throughput_qos;
474 
475 		kern_return_t kr = task_qos_policy_validate(&qosinfo, TASK_QOS_POLICY_COUNT);
476 
477 		if (kr != KERN_SUCCESS) {
478 			return kr;
479 		}
480 
481 		/* TEMPORARY disablement of task suppression */
482 		if (info->active &&
483 		    (task_policy_suppression_flags & TASK_POLICY_SUPPRESSION_DISABLE)) {
484 			return KERN_SUCCESS;
485 		}
486 
487 		struct task_pend_token pend_token = {};
488 
489 		task_lock(task);
490 
491 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
492 		    (IMPORTANCE_CODE(IMP_TASK_SUPPRESSION, info->active)) | DBG_FUNC_START,
493 		    proc_selfpid(), task_pid(task), trequested_0(task),
494 		    trequested_1(task), 0);
495 
496 		task->requested_policy.trp_sup_active      = (info->active)         ? 1 : 0;
497 		task->requested_policy.trp_sup_lowpri_cpu  = (info->lowpri_cpu)     ? 1 : 0;
498 		task->requested_policy.trp_sup_timer       = qos_extract(info->timer_throttle);
499 		task->requested_policy.trp_sup_disk        = (info->disk_throttle)  ? 1 : 0;
500 		task->requested_policy.trp_sup_throughput  = qos_extract(info->throughput_qos);
501 		task->requested_policy.trp_sup_cpu         = (info->suppressed_cpu) ? 1 : 0;
502 		task->requested_policy.trp_sup_bg_sockets  = (info->background_sockets) ? 1 : 0;
503 
504 		task_policy_update_locked(task, &pend_token);
505 
506 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
507 		    (IMPORTANCE_CODE(IMP_TASK_SUPPRESSION, info->active)) | DBG_FUNC_END,
508 		    proc_selfpid(), task_pid(task), trequested_0(task),
509 		    trequested_1(task), 0);
510 
511 		task_unlock(task);
512 
513 		task_policy_update_complete_unlocked(task, &pend_token);
514 
515 		break;
516 
517 #endif /* !defined(XNU_TARGET_OS_OSX) */
518 	}
519 
520 	default:
521 		result = KERN_INVALID_ARGUMENT;
522 		break;
523 	}
524 
525 	return result;
526 }
527 
528 /* Sets BSD 'nice' value on the task */
529 kern_return_t
task_importance(task_t task,integer_t importance)530 task_importance(
531 	task_t                          task,
532 	integer_t                       importance)
533 {
534 	if (task == TASK_NULL || task == kernel_task) {
535 		return KERN_INVALID_ARGUMENT;
536 	}
537 
538 	task_lock(task);
539 
540 	if (!task->active) {
541 		task_unlock(task);
542 
543 		return KERN_TERMINATED;
544 	}
545 
546 	if (proc_get_effective_task_policy(task, TASK_POLICY_ROLE) >= TASK_CONTROL_APPLICATION) {
547 		task_unlock(task);
548 
549 		return KERN_INVALID_ARGUMENT;
550 	}
551 
552 	task->importance = importance;
553 
554 	struct task_pend_token pend_token = {};
555 
556 	task_policy_update_locked(task, &pend_token);
557 
558 	task_unlock(task);
559 
560 	task_policy_update_complete_unlocked(task, &pend_token);
561 
562 	return KERN_SUCCESS;
563 }
564 
565 kern_return_t
task_policy_get(task_t task,task_policy_flavor_t flavor,task_policy_t policy_info,mach_msg_type_number_t * count,boolean_t * get_default)566 task_policy_get(
567 	task_t                                  task,
568 	task_policy_flavor_t    flavor,
569 	task_policy_t                   policy_info,
570 	mach_msg_type_number_t  *count,
571 	boolean_t                               *get_default)
572 {
573 	if (task == TASK_NULL || task == kernel_task) {
574 		return KERN_INVALID_ARGUMENT;
575 	}
576 
577 	switch (flavor) {
578 	case TASK_CATEGORY_POLICY:
579 	{
580 		task_category_policy_t          info = (task_category_policy_t)policy_info;
581 
582 		if (*count < TASK_CATEGORY_POLICY_COUNT) {
583 			return KERN_INVALID_ARGUMENT;
584 		}
585 
586 		if (*get_default) {
587 			info->role = TASK_UNSPECIFIED;
588 		} else {
589 			info->role = proc_get_task_policy(task, TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE);
590 		}
591 		break;
592 	}
593 
594 	case TASK_BASE_QOS_POLICY: /* FALLTHRU */
595 	case TASK_OVERRIDE_QOS_POLICY:
596 	{
597 		task_qos_policy_t info = (task_qos_policy_t)policy_info;
598 
599 		if (*count < TASK_QOS_POLICY_COUNT) {
600 			return KERN_INVALID_ARGUMENT;
601 		}
602 
603 		if (*get_default) {
604 			info->task_latency_qos_tier = LATENCY_QOS_TIER_UNSPECIFIED;
605 			info->task_throughput_qos_tier = THROUGHPUT_QOS_TIER_UNSPECIFIED;
606 		} else if (flavor == TASK_BASE_QOS_POLICY) {
607 			int value1, value2;
608 
609 			proc_get_task_policy2(task, TASK_POLICY_ATTRIBUTE, TASK_POLICY_BASE_LATENCY_AND_THROUGHPUT_QOS, &value1, &value2);
610 
611 			info->task_latency_qos_tier = qos_latency_policy_package(value1);
612 			info->task_throughput_qos_tier = qos_throughput_policy_package(value2);
613 		} else if (flavor == TASK_OVERRIDE_QOS_POLICY) {
614 			int value1, value2;
615 
616 			proc_get_task_policy2(task, TASK_POLICY_ATTRIBUTE, TASK_POLICY_OVERRIDE_LATENCY_AND_THROUGHPUT_QOS, &value1, &value2);
617 
618 			info->task_latency_qos_tier = qos_latency_policy_package(value1);
619 			info->task_throughput_qos_tier = qos_throughput_policy_package(value2);
620 		}
621 
622 		break;
623 	}
624 
625 	case TASK_POLICY_STATE:
626 	{
627 		task_policy_state_t info = (task_policy_state_t)policy_info;
628 
629 		if (*count < TASK_POLICY_STATE_COUNT) {
630 			return KERN_INVALID_ARGUMENT;
631 		}
632 
633 		/* Only root can get this info */
634 		if (!task_is_privileged(current_task())) {
635 			return KERN_PROTECTION_FAILURE;
636 		}
637 
638 		if (*get_default) {
639 			info->requested = 0;
640 			info->effective = 0;
641 			info->pending = 0;
642 			info->imp_assertcnt = 0;
643 			info->imp_externcnt = 0;
644 			info->flags = 0;
645 			info->imp_transitions = 0;
646 		} else {
647 			task_lock(task);
648 
649 			info->requested = task_requested_bitfield(task);
650 			info->effective = task_effective_bitfield(task);
651 			info->pending   = 0;
652 
653 			info->tps_requested_policy = *(uint64_t*)(&task->requested_policy);
654 			info->tps_effective_policy = *(uint64_t*)(&task->effective_policy);
655 
656 			info->flags = 0;
657 			if (task->task_imp_base != NULL) {
658 				info->imp_assertcnt = task->task_imp_base->iit_assertcnt;
659 				info->imp_externcnt = IIT_EXTERN(task->task_imp_base);
660 				info->flags |= (task_is_marked_importance_receiver(task) ? TASK_IMP_RECEIVER : 0);
661 				info->flags |= (task_is_marked_importance_denap_receiver(task) ? TASK_DENAP_RECEIVER : 0);
662 				info->flags |= (task_is_marked_importance_donor(task) ? TASK_IMP_DONOR : 0);
663 				info->flags |= (task_is_marked_live_importance_donor(task) ? TASK_IMP_LIVE_DONOR : 0);
664 				info->flags |= (get_task_pidsuspended(task) ? TASK_IS_PIDSUSPENDED : 0);
665 				info->imp_transitions = task->task_imp_base->iit_transitions;
666 			} else {
667 				info->imp_assertcnt = 0;
668 				info->imp_externcnt = 0;
669 				info->imp_transitions = 0;
670 			}
671 			task_unlock(task);
672 		}
673 
674 		break;
675 	}
676 
677 	case TASK_SUPPRESSION_POLICY:
678 	{
679 		task_suppression_policy_t info = (task_suppression_policy_t)policy_info;
680 
681 		if (*count < TASK_SUPPRESSION_POLICY_COUNT) {
682 			return KERN_INVALID_ARGUMENT;
683 		}
684 
685 		task_lock(task);
686 
687 		if (*get_default) {
688 			info->active            = 0;
689 			info->lowpri_cpu        = 0;
690 			info->timer_throttle    = LATENCY_QOS_TIER_UNSPECIFIED;
691 			info->disk_throttle     = 0;
692 			info->cpu_limit         = 0;
693 			info->suspend           = 0;
694 			info->throughput_qos    = 0;
695 			info->suppressed_cpu    = 0;
696 		} else {
697 			info->active            = task->requested_policy.trp_sup_active;
698 			info->lowpri_cpu        = task->requested_policy.trp_sup_lowpri_cpu;
699 			info->timer_throttle    = qos_latency_policy_package(task->requested_policy.trp_sup_timer);
700 			info->disk_throttle     = task->requested_policy.trp_sup_disk;
701 			info->cpu_limit         = 0;
702 			info->suspend           = 0;
703 			info->throughput_qos    = qos_throughput_policy_package(task->requested_policy.trp_sup_throughput);
704 			info->suppressed_cpu    = task->requested_policy.trp_sup_cpu;
705 			info->background_sockets = task->requested_policy.trp_sup_bg_sockets;
706 		}
707 
708 		task_unlock(task);
709 		break;
710 	}
711 
712 	default:
713 		return KERN_INVALID_ARGUMENT;
714 	}
715 
716 	return KERN_SUCCESS;
717 }
718 
719 /*
720  * Called at task creation
721  * We calculate the correct effective but don't apply it to anything yet.
722  * The threads, etc will inherit from the task as they get created.
723  */
724 void
task_policy_create(task_t task,task_t parent_task)725 task_policy_create(task_t task, task_t parent_task)
726 {
727 	task->requested_policy.trp_apptype          = parent_task->requested_policy.trp_apptype;
728 
729 	task->requested_policy.trp_int_darwinbg     = parent_task->requested_policy.trp_int_darwinbg;
730 	task->requested_policy.trp_ext_darwinbg     = parent_task->requested_policy.trp_ext_darwinbg;
731 	task->requested_policy.trp_int_iotier       = parent_task->requested_policy.trp_int_iotier;
732 	task->requested_policy.trp_ext_iotier       = parent_task->requested_policy.trp_ext_iotier;
733 	task->requested_policy.trp_int_iopassive    = parent_task->requested_policy.trp_int_iopassive;
734 	task->requested_policy.trp_ext_iopassive    = parent_task->requested_policy.trp_ext_iopassive;
735 	task->requested_policy.trp_bg_iotier        = parent_task->requested_policy.trp_bg_iotier;
736 	task->requested_policy.trp_terminated       = parent_task->requested_policy.trp_terminated;
737 	task->requested_policy.trp_qos_clamp        = parent_task->requested_policy.trp_qos_clamp;
738 
739 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_DAEMON_ADAPTIVE && !task_is_exec_copy(task)) {
740 		/* Do not update the apptype for exec copy task */
741 		if (parent_task->requested_policy.trp_boosted) {
742 			task->requested_policy.trp_apptype = TASK_APPTYPE_DAEMON_INTERACTIVE;
743 			task_importance_mark_donor(task, TRUE);
744 		} else {
745 			task->requested_policy.trp_apptype = TASK_APPTYPE_DAEMON_BACKGROUND;
746 			task_importance_mark_receiver(task, FALSE);
747 		}
748 	}
749 
750 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
751 	    (IMPORTANCE_CODE(IMP_UPDATE, (IMP_UPDATE_TASK_CREATE | TASK_POLICY_TASK))) | DBG_FUNC_START,
752 	    task_pid(task), teffective_0(task),
753 	    teffective_1(task), task->priority, 0);
754 
755 	task_policy_update_internal_locked(task, true, NULL);
756 
757 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
758 	    (IMPORTANCE_CODE(IMP_UPDATE, (IMP_UPDATE_TASK_CREATE | TASK_POLICY_TASK))) | DBG_FUNC_END,
759 	    task_pid(task), teffective_0(task),
760 	    teffective_1(task), task->priority, 0);
761 
762 	task_importance_update_live_donor(task);
763 }
764 
765 
766 static void
task_policy_update_locked(task_t task,task_pend_token_t pend_token)767 task_policy_update_locked(task_t task, task_pend_token_t pend_token)
768 {
769 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
770 	    (IMPORTANCE_CODE(IMP_UPDATE, TASK_POLICY_TASK) | DBG_FUNC_START),
771 	    task_pid(task), teffective_0(task),
772 	    teffective_1(task), task->priority, 0);
773 
774 	task_policy_update_internal_locked(task, false, pend_token);
775 
776 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
777 	    (IMPORTANCE_CODE(IMP_UPDATE, TASK_POLICY_TASK)) | DBG_FUNC_END,
778 	    task_pid(task), teffective_0(task),
779 	    teffective_1(task), task->priority, 0);
780 }
781 
782 /*
783  * One state update function TO RULE THEM ALL
784  *
785  * This function updates the task or thread effective policy fields
786  * and pushes the results to the relevant subsystems.
787  *
788  * Must call update_complete after unlocking the task,
789  * as some subsystems cannot be updated while holding the task lock.
790  *
791  * Called with task locked, not thread
792  */
793 
794 static void
task_policy_update_internal_locked(task_t task,bool in_create,task_pend_token_t pend_token)795 task_policy_update_internal_locked(task_t task, bool in_create, task_pend_token_t pend_token)
796 {
797 	/*
798 	 * Step 1:
799 	 *  Gather requested policy
800 	 */
801 
802 	struct task_requested_policy requested = task->requested_policy;
803 
804 	/*
805 	 * Step 2:
806 	 *  Calculate new effective policies from requested policy and task state
807 	 *  Rules:
808 	 *      Don't change requested, it won't take effect
809 	 */
810 
811 	struct task_effective_policy next = {};
812 
813 	/* Update task role */
814 	next.tep_role = requested.trp_role;
815 
816 	/* Set task qos clamp and ceiling */
817 	next.tep_qos_clamp = requested.trp_qos_clamp;
818 
819 	if (requested.trp_apptype == TASK_APPTYPE_APP_DEFAULT) {
820 		switch (next.tep_role) {
821 		case TASK_FOREGROUND_APPLICATION:
822 			/* Foreground apps get urgent scheduler priority */
823 			next.tep_qos_ui_is_urgent = 1;
824 			next.tep_qos_ceiling = THREAD_QOS_UNSPECIFIED;
825 			break;
826 
827 		case TASK_BACKGROUND_APPLICATION:
828 			/* This is really 'non-focal but on-screen' */
829 			next.tep_qos_ceiling = THREAD_QOS_UNSPECIFIED;
830 			break;
831 
832 		case TASK_DEFAULT_APPLICATION:
833 			/* This is 'may render UI but we don't know if it's focal/nonfocal' */
834 			next.tep_qos_ceiling = THREAD_QOS_UNSPECIFIED;
835 			break;
836 
837 		case TASK_NONUI_APPLICATION:
838 			/* i.e. 'off-screen' */
839 			next.tep_qos_ceiling = THREAD_QOS_LEGACY;
840 			break;
841 
842 		case TASK_CONTROL_APPLICATION:
843 		case TASK_GRAPHICS_SERVER:
844 			next.tep_qos_ui_is_urgent = 1;
845 			next.tep_qos_ceiling = THREAD_QOS_UNSPECIFIED;
846 			break;
847 
848 		case TASK_THROTTLE_APPLICATION:
849 			/* i.e. 'TAL launch' */
850 			next.tep_qos_ceiling = THREAD_QOS_UTILITY;
851 			break;
852 
853 		case TASK_DARWINBG_APPLICATION:
854 			/* i.e. 'DARWIN_BG throttled background application' */
855 			next.tep_qos_ceiling = THREAD_QOS_BACKGROUND;
856 			break;
857 
858 		case TASK_UNSPECIFIED:
859 		default:
860 			/* Apps that don't have an application role get
861 			 * USER_INTERACTIVE and USER_INITIATED squashed to LEGACY */
862 			next.tep_qos_ceiling = THREAD_QOS_LEGACY;
863 			break;
864 		}
865 	} else {
866 		/* Daemons and dext get USER_INTERACTIVE squashed to USER_INITIATED */
867 		next.tep_qos_ceiling = THREAD_QOS_USER_INITIATED;
868 	}
869 
870 	/* Calculate DARWIN_BG */
871 	bool wants_darwinbg        = false;
872 	bool wants_all_sockets_bg  = false; /* Do I want my existing sockets to be bg */
873 	bool wants_watchersbg      = false; /* Do I want my pidbound threads to be bg */
874 	bool adaptive_bg_only      = false; /* This task is BG only because it's adaptive unboosted */
875 
876 	/* Adaptive daemons are DARWIN_BG unless boosted, and don't get network throttled. */
877 	if (requested.trp_apptype == TASK_APPTYPE_DAEMON_ADAPTIVE &&
878 	    requested.trp_boosted == 0) {
879 		wants_darwinbg = true;
880 		adaptive_bg_only = true;
881 	}
882 
883 	/*
884 	 * If DARWIN_BG has been requested at either level, it's engaged.
885 	 * Only true DARWIN_BG changes cause watchers to transition.
886 	 *
887 	 * Backgrounding due to apptype does.
888 	 */
889 	if (requested.trp_int_darwinbg || requested.trp_ext_darwinbg ||
890 	    next.tep_role == TASK_DARWINBG_APPLICATION) {
891 		wants_watchersbg = wants_all_sockets_bg = wants_darwinbg = true;
892 		adaptive_bg_only = false;
893 	}
894 
895 	/* Application launching in special Transparent App Lifecycle throttle mode */
896 	if (requested.trp_apptype == TASK_APPTYPE_APP_DEFAULT &&
897 	    requested.trp_role == TASK_THROTTLE_APPLICATION) {
898 		next.tep_tal_engaged = 1;
899 	}
900 
901 	/* Background daemons are always DARWIN_BG, no exceptions, and don't get network throttled. */
902 	if (requested.trp_apptype == TASK_APPTYPE_DAEMON_BACKGROUND) {
903 		wants_darwinbg = true;
904 		adaptive_bg_only = false;
905 	}
906 
907 	if (next.tep_qos_clamp == THREAD_QOS_BACKGROUND ||
908 	    next.tep_qos_clamp == THREAD_QOS_MAINTENANCE) {
909 		wants_darwinbg = true;
910 		adaptive_bg_only = false;
911 	}
912 
913 	/* Calculate side effects of DARWIN_BG */
914 
915 	if (wants_darwinbg) {
916 		next.tep_darwinbg = 1;
917 		/* darwinbg tasks always create bg sockets, but we don't always loop over all sockets */
918 		next.tep_new_sockets_bg = 1;
919 		next.tep_lowpri_cpu = 1;
920 	}
921 
922 	if (wants_all_sockets_bg) {
923 		next.tep_all_sockets_bg = 1;
924 	}
925 
926 	if (wants_watchersbg) {
927 		next.tep_watchers_bg = 1;
928 	}
929 
930 	next.tep_adaptive_bg = adaptive_bg_only;
931 
932 	/* Calculate low CPU priority */
933 
934 	boolean_t wants_lowpri_cpu = false;
935 
936 	if (wants_darwinbg) {
937 		wants_lowpri_cpu = true;
938 	}
939 
940 	if (next.tep_tal_engaged) {
941 		wants_lowpri_cpu = true;
942 	}
943 
944 	if (requested.trp_sup_lowpri_cpu && requested.trp_boosted == 0) {
945 		wants_lowpri_cpu = true;
946 	}
947 
948 	if (wants_lowpri_cpu) {
949 		next.tep_lowpri_cpu = 1;
950 	}
951 
952 	/* Calculate IO policy */
953 
954 	/* Update BG IO policy (so we can see if it has changed) */
955 	next.tep_bg_iotier = requested.trp_bg_iotier;
956 
957 	int iopol = THROTTLE_LEVEL_TIER0;
958 
959 	if (wants_darwinbg) {
960 		iopol = MAX(iopol, requested.trp_bg_iotier);
961 	}
962 
963 	if (requested.trp_apptype == TASK_APPTYPE_DAEMON_STANDARD) {
964 		iopol = MAX(iopol, proc_standard_daemon_tier);
965 	}
966 
967 	if (requested.trp_sup_disk && requested.trp_boosted == 0) {
968 		iopol = MAX(iopol, proc_suppressed_disk_tier);
969 	}
970 
971 	if (next.tep_tal_engaged) {
972 		iopol = MAX(iopol, proc_tal_disk_tier);
973 	}
974 
975 	if (next.tep_qos_clamp != THREAD_QOS_UNSPECIFIED) {
976 		iopol = MAX(iopol, thread_qos_policy_params.qos_iotier[next.tep_qos_clamp]);
977 	}
978 
979 	iopol = MAX(iopol, requested.trp_int_iotier);
980 	iopol = MAX(iopol, requested.trp_ext_iotier);
981 
982 	next.tep_io_tier = iopol;
983 
984 	/* Calculate Passive IO policy */
985 
986 	if (requested.trp_ext_iopassive || requested.trp_int_iopassive) {
987 		next.tep_io_passive = 1;
988 	}
989 
990 	/* Calculate suppression-active flag */
991 	boolean_t appnap_transition = false;
992 
993 	if (requested.trp_sup_active && requested.trp_boosted == 0) {
994 		next.tep_sup_active = 1;
995 	}
996 
997 	if (task->effective_policy.tep_sup_active != next.tep_sup_active) {
998 		appnap_transition = true;
999 	}
1000 
1001 	/* Calculate timer QOS */
1002 	int latency_qos = requested.trp_base_latency_qos;
1003 
1004 	if (requested.trp_sup_timer && requested.trp_boosted == 0) {
1005 		latency_qos = requested.trp_sup_timer;
1006 	}
1007 
1008 	if (next.tep_qos_clamp != THREAD_QOS_UNSPECIFIED) {
1009 		latency_qos = MAX(latency_qos, (int)thread_qos_policy_params.qos_latency_qos[next.tep_qos_clamp]);
1010 	}
1011 
1012 	if (requested.trp_over_latency_qos != 0) {
1013 		latency_qos = requested.trp_over_latency_qos;
1014 	}
1015 
1016 	/* Treat the windowserver special */
1017 	if (requested.trp_role == TASK_GRAPHICS_SERVER) {
1018 		latency_qos = proc_graphics_timer_qos;
1019 	}
1020 
1021 	next.tep_latency_qos = latency_qos;
1022 
1023 	/* Calculate throughput QOS */
1024 	int through_qos = requested.trp_base_through_qos;
1025 
1026 	if (requested.trp_sup_throughput && requested.trp_boosted == 0) {
1027 		through_qos = requested.trp_sup_throughput;
1028 	}
1029 
1030 	if (next.tep_qos_clamp != THREAD_QOS_UNSPECIFIED) {
1031 		through_qos = MAX(through_qos, (int)thread_qos_policy_params.qos_through_qos[next.tep_qos_clamp]);
1032 	}
1033 
1034 	if (requested.trp_over_through_qos != 0) {
1035 		through_qos = requested.trp_over_through_qos;
1036 	}
1037 
1038 	next.tep_through_qos = through_qos;
1039 
1040 	/* Calculate suppressed CPU priority */
1041 	if (requested.trp_sup_cpu && requested.trp_boosted == 0) {
1042 		next.tep_suppressed_cpu = 1;
1043 	}
1044 
1045 	/*
1046 	 * Calculate background sockets
1047 	 * Don't take into account boosting to limit transition frequency.
1048 	 */
1049 	if (requested.trp_sup_bg_sockets) {
1050 		next.tep_all_sockets_bg = 1;
1051 		next.tep_new_sockets_bg = 1;
1052 	}
1053 
1054 	/* Apply SFI Managed class bit */
1055 	next.tep_sfi_managed = requested.trp_sfi_managed;
1056 
1057 	/* Calculate 'live donor' status for live importance */
1058 	switch (requested.trp_apptype) {
1059 	case TASK_APPTYPE_APP_TAL:
1060 	case TASK_APPTYPE_APP_DEFAULT:
1061 		if (requested.trp_ext_darwinbg == 1 ||
1062 		    (next.tep_sup_active == 1 &&
1063 		    (task_policy_suppression_flags & TASK_POLICY_SUPPRESSION_NONDONOR)) ||
1064 		    next.tep_role == TASK_DARWINBG_APPLICATION) {
1065 			next.tep_live_donor = 0;
1066 		} else {
1067 			next.tep_live_donor = 1;
1068 		}
1069 		break;
1070 
1071 	case TASK_APPTYPE_DAEMON_INTERACTIVE:
1072 	case TASK_APPTYPE_DAEMON_STANDARD:
1073 	case TASK_APPTYPE_DAEMON_ADAPTIVE:
1074 	case TASK_APPTYPE_DAEMON_BACKGROUND:
1075 	case TASK_APPTYPE_DRIVER:
1076 	default:
1077 		next.tep_live_donor = 0;
1078 		break;
1079 	}
1080 
1081 	if (requested.trp_terminated) {
1082 		/*
1083 		 * Shoot down the throttles that slow down exit or response to SIGTERM
1084 		 * We don't need to shoot down:
1085 		 * passive        (don't want to cause others to throttle)
1086 		 * all_sockets_bg (don't need to iterate FDs on every exit)
1087 		 * new_sockets_bg (doesn't matter for exiting process)
1088 		 * pidsuspend     (jetsam-ed BG process shouldn't run again)
1089 		 * watchers_bg    (watcher threads don't need to be unthrottled)
1090 		 * latency_qos    (affects userspace timers only)
1091 		 */
1092 
1093 		next.tep_terminated     = 1;
1094 		next.tep_darwinbg       = 0;
1095 		next.tep_lowpri_cpu     = 0;
1096 		next.tep_io_tier        = THROTTLE_LEVEL_TIER0;
1097 		next.tep_tal_engaged    = 0;
1098 		next.tep_role           = TASK_UNSPECIFIED;
1099 		next.tep_suppressed_cpu = 0;
1100 	}
1101 
1102 	/*
1103 	 * Step 3:
1104 	 *  Swap out old policy for new policy
1105 	 */
1106 
1107 	struct task_effective_policy prev = task->effective_policy;
1108 
1109 	/* This is the point where the new values become visible to other threads */
1110 	task->effective_policy = next;
1111 
1112 	/* Don't do anything further to a half-formed task */
1113 	if (in_create) {
1114 		return;
1115 	}
1116 
1117 	if (task == kernel_task) {
1118 		panic("Attempting to set task policy on kernel_task");
1119 	}
1120 
1121 	/*
1122 	 * Step 4:
1123 	 *  Pend updates that can't be done while holding the task lock
1124 	 */
1125 
1126 	if (prev.tep_all_sockets_bg != next.tep_all_sockets_bg) {
1127 		pend_token->tpt_update_sockets = 1;
1128 	}
1129 
1130 	/* Only re-scan the timer list if the qos level is getting less strong */
1131 	if (prev.tep_latency_qos > next.tep_latency_qos) {
1132 		pend_token->tpt_update_timers = 1;
1133 	}
1134 
1135 #if CONFIG_TASKWATCH
1136 	if (prev.tep_watchers_bg != next.tep_watchers_bg) {
1137 		pend_token->tpt_update_watchers = 1;
1138 	}
1139 #endif /* CONFIG_TASKWATCH */
1140 
1141 	if (prev.tep_live_donor != next.tep_live_donor) {
1142 		pend_token->tpt_update_live_donor = 1;
1143 	}
1144 
1145 	/*
1146 	 * Step 5:
1147 	 *  Update other subsystems as necessary if something has changed
1148 	 */
1149 
1150 	bool update_threads = false, update_sfi = false;
1151 
1152 	/*
1153 	 * Check for the attributes that thread_policy_update_internal_locked() consults,
1154 	 *  and trigger thread policy re-evaluation.
1155 	 */
1156 	if (prev.tep_io_tier != next.tep_io_tier ||
1157 	    prev.tep_bg_iotier != next.tep_bg_iotier ||
1158 	    prev.tep_io_passive != next.tep_io_passive ||
1159 	    prev.tep_darwinbg != next.tep_darwinbg ||
1160 	    prev.tep_qos_clamp != next.tep_qos_clamp ||
1161 	    prev.tep_qos_ceiling != next.tep_qos_ceiling ||
1162 	    prev.tep_qos_ui_is_urgent != next.tep_qos_ui_is_urgent ||
1163 	    prev.tep_latency_qos != next.tep_latency_qos ||
1164 	    prev.tep_through_qos != next.tep_through_qos ||
1165 	    prev.tep_lowpri_cpu != next.tep_lowpri_cpu ||
1166 	    prev.tep_new_sockets_bg != next.tep_new_sockets_bg ||
1167 	    prev.tep_terminated != next.tep_terminated ||
1168 	    prev.tep_adaptive_bg != next.tep_adaptive_bg) {
1169 		update_threads = true;
1170 	}
1171 
1172 	/*
1173 	 * Check for the attributes that sfi_thread_classify() consults,
1174 	 *  and trigger SFI re-evaluation.
1175 	 */
1176 	if (prev.tep_latency_qos != next.tep_latency_qos ||
1177 	    prev.tep_role != next.tep_role ||
1178 	    prev.tep_sfi_managed != next.tep_sfi_managed) {
1179 		update_sfi = true;
1180 	}
1181 
1182 	/* Reflect task role transitions into the coalition role counters */
1183 	if (prev.tep_role != next.tep_role) {
1184 		if (task_policy_update_coalition_focal_tasks(task, prev.tep_role, next.tep_role, pend_token)) {
1185 			update_sfi = true;
1186 		}
1187 	}
1188 
1189 	bool update_priority = false;
1190 
1191 	int16_t priority     = BASEPRI_DEFAULT;
1192 	int16_t max_priority = MAXPRI_USER;
1193 
1194 	if (next.tep_lowpri_cpu) {
1195 		priority = MAXPRI_THROTTLE;
1196 		max_priority = MAXPRI_THROTTLE;
1197 	} else if (next.tep_suppressed_cpu) {
1198 		priority = MAXPRI_SUPPRESSED;
1199 		max_priority = MAXPRI_SUPPRESSED;
1200 	} else {
1201 		switch (next.tep_role) {
1202 		case TASK_CONTROL_APPLICATION:
1203 			priority = BASEPRI_CONTROL;
1204 			break;
1205 		case TASK_GRAPHICS_SERVER:
1206 			priority = BASEPRI_GRAPHICS;
1207 			max_priority = MAXPRI_RESERVED;
1208 			break;
1209 		default:
1210 			break;
1211 		}
1212 
1213 		/* factor in 'nice' value */
1214 		priority += task->importance;
1215 
1216 		if (task->effective_policy.tep_qos_clamp != THREAD_QOS_UNSPECIFIED) {
1217 			int16_t qos_clamp_priority = thread_qos_policy_params.qos_pri[task->effective_policy.tep_qos_clamp];
1218 
1219 			priority        = MIN(priority, qos_clamp_priority);
1220 			max_priority    = MIN(max_priority, qos_clamp_priority);
1221 		}
1222 
1223 		if (priority > max_priority) {
1224 			priority = max_priority;
1225 		} else if (priority < MINPRI) {
1226 			priority = MINPRI;
1227 		}
1228 	}
1229 
1230 	assert(priority <= max_priority);
1231 
1232 	/* avoid extra work if priority isn't changing */
1233 	if (priority != task->priority ||
1234 	    max_priority != task->max_priority) {
1235 		/* update the scheduling priority for the task */
1236 		task->max_priority  = max_priority;
1237 		task->priority      = priority;
1238 		update_priority     = true;
1239 	}
1240 
1241 	/* Loop over the threads in the task:
1242 	 * only once
1243 	 * only if necessary
1244 	 * with one thread mutex hold per thread
1245 	 */
1246 	if (update_threads || update_priority || update_sfi) {
1247 		thread_t thread;
1248 
1249 		queue_iterate(&task->threads, thread, thread_t, task_threads) {
1250 			struct task_pend_token thread_pend_token = {};
1251 
1252 			if (update_sfi) {
1253 				thread_pend_token.tpt_update_thread_sfi = 1;
1254 			}
1255 
1256 			if (update_priority || update_threads) {
1257 				thread_policy_update_tasklocked(thread,
1258 				    task->priority, task->max_priority,
1259 				    &thread_pend_token);
1260 			}
1261 
1262 			assert(!thread_pend_token.tpt_update_sockets);
1263 
1264 			// Slightly risky, as we still hold the task lock...
1265 			thread_policy_update_complete_unlocked(thread, &thread_pend_token);
1266 		}
1267 	}
1268 
1269 	/*
1270 	 * Use the app-nap transitions to influence the
1271 	 * transition of the process within the jetsam band
1272 	 * [and optionally its live-donor status]
1273 	 * On macOS only.
1274 	 */
1275 	if (appnap_transition) {
1276 		if (task->effective_policy.tep_sup_active == 1) {
1277 			memorystatus_update_priority_for_appnap(((proc_t) task->bsd_info), TRUE);
1278 		} else {
1279 			memorystatus_update_priority_for_appnap(((proc_t) task->bsd_info), FALSE);
1280 		}
1281 	}
1282 }
1283 
1284 
1285 /*
1286  * Yet another layering violation. We reach out and bang on the coalition directly.
1287  */
1288 static boolean_t
task_policy_update_coalition_focal_tasks(task_t task,int prev_role,int next_role,task_pend_token_t pend_token)1289 task_policy_update_coalition_focal_tasks(task_t            task,
1290     int               prev_role,
1291     int               next_role,
1292     task_pend_token_t pend_token)
1293 {
1294 	boolean_t sfi_transition = FALSE;
1295 	uint32_t new_count = 0;
1296 
1297 	/* task moving into/out-of the foreground */
1298 	if (prev_role != TASK_FOREGROUND_APPLICATION && next_role == TASK_FOREGROUND_APPLICATION) {
1299 		if (task_coalition_adjust_focal_count(task, 1, &new_count) && (new_count == 1)) {
1300 			sfi_transition = TRUE;
1301 			pend_token->tpt_update_tg_ui_flag = TRUE;
1302 		}
1303 	} else if (prev_role == TASK_FOREGROUND_APPLICATION && next_role != TASK_FOREGROUND_APPLICATION) {
1304 		if (task_coalition_adjust_focal_count(task, -1, &new_count) && (new_count == 0)) {
1305 			sfi_transition = TRUE;
1306 			pend_token->tpt_update_tg_ui_flag = TRUE;
1307 		}
1308 	}
1309 
1310 	/* task moving into/out-of background */
1311 	if (prev_role != TASK_BACKGROUND_APPLICATION && next_role == TASK_BACKGROUND_APPLICATION) {
1312 		if (task_coalition_adjust_nonfocal_count(task, 1, &new_count) && (new_count == 1)) {
1313 			sfi_transition = TRUE;
1314 		}
1315 	} else if (prev_role == TASK_BACKGROUND_APPLICATION && next_role != TASK_BACKGROUND_APPLICATION) {
1316 		if (task_coalition_adjust_nonfocal_count(task, -1, &new_count) && (new_count == 0)) {
1317 			sfi_transition = TRUE;
1318 		}
1319 	}
1320 
1321 	if (sfi_transition) {
1322 		pend_token->tpt_update_coal_sfi = 1;
1323 	}
1324 	return sfi_transition;
1325 }
1326 
1327 #if CONFIG_SCHED_SFI
1328 
1329 /* coalition object is locked */
1330 static void
task_sfi_reevaluate_cb(coalition_t coal,void * ctx,task_t task)1331 task_sfi_reevaluate_cb(coalition_t coal, void *ctx, task_t task)
1332 {
1333 	thread_t thread;
1334 
1335 	/* unused for now */
1336 	(void)coal;
1337 
1338 	/* skip the task we're re-evaluating on behalf of: it's already updated */
1339 	if (task == (task_t)ctx) {
1340 		return;
1341 	}
1342 
1343 	task_lock(task);
1344 
1345 	queue_iterate(&task->threads, thread, thread_t, task_threads) {
1346 		sfi_reevaluate(thread);
1347 	}
1348 
1349 	task_unlock(task);
1350 }
1351 #endif /* CONFIG_SCHED_SFI */
1352 
1353 /*
1354  * Called with task unlocked to do things that can't be done while holding the task lock
1355  */
1356 void
task_policy_update_complete_unlocked(task_t task,task_pend_token_t pend_token)1357 task_policy_update_complete_unlocked(task_t task, task_pend_token_t pend_token)
1358 {
1359 #ifdef MACH_BSD
1360 	if (pend_token->tpt_update_sockets) {
1361 		proc_apply_task_networkbg(task_pid(task), THREAD_NULL);
1362 	}
1363 #endif /* MACH_BSD */
1364 
1365 	/* The timer throttle has been removed or reduced, we need to look for expired timers and fire them */
1366 	if (pend_token->tpt_update_timers) {
1367 		ml_timer_evaluate();
1368 	}
1369 
1370 #if CONFIG_TASKWATCH
1371 	if (pend_token->tpt_update_watchers) {
1372 		apply_appstate_watchers(task);
1373 	}
1374 #endif /* CONFIG_TASKWATCH */
1375 
1376 	if (pend_token->tpt_update_live_donor) {
1377 		task_importance_update_live_donor(task);
1378 	}
1379 
1380 #if CONFIG_SCHED_SFI
1381 	/* use the resource coalition for SFI re-evaluation */
1382 	if (pend_token->tpt_update_coal_sfi) {
1383 		coalition_for_each_task(task->coalition[COALITION_TYPE_RESOURCE],
1384 		    (void *)task, task_sfi_reevaluate_cb);
1385 	}
1386 #endif /* CONFIG_SCHED_SFI */
1387 
1388 #if CONFIG_THREAD_GROUPS
1389 	if (pend_token->tpt_update_tg_ui_flag) {
1390 		task_coalition_thread_group_focal_update(task);
1391 	}
1392 #endif /* CONFIG_THREAD_GROUPS */
1393 }
1394 
1395 /*
1396  * Initiate a task policy state transition
1397  *
1398  * Everything that modifies requested except functions that need to hold the task lock
1399  * should use this function
1400  *
1401  * Argument validation should be performed before reaching this point.
1402  *
1403  * TODO: Do we need to check task->active?
1404  */
1405 void
proc_set_task_policy(task_t task,int category,int flavor,int value)1406 proc_set_task_policy(task_t     task,
1407     int        category,
1408     int        flavor,
1409     int        value)
1410 {
1411 	struct task_pend_token pend_token = {};
1412 
1413 	task_lock(task);
1414 
1415 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1416 	    (IMPORTANCE_CODE(flavor, (category | TASK_POLICY_TASK))) | DBG_FUNC_START,
1417 	    task_pid(task), trequested_0(task),
1418 	    trequested_1(task), value, 0);
1419 
1420 	proc_set_task_policy_locked(task, category, flavor, value, 0);
1421 
1422 	task_policy_update_locked(task, &pend_token);
1423 
1424 
1425 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1426 	    (IMPORTANCE_CODE(flavor, (category | TASK_POLICY_TASK))) | DBG_FUNC_END,
1427 	    task_pid(task), trequested_0(task),
1428 	    trequested_1(task), tpending(&pend_token), 0);
1429 
1430 	task_unlock(task);
1431 
1432 	task_policy_update_complete_unlocked(task, &pend_token);
1433 }
1434 
1435 /*
1436  * Variant of proc_set_task_policy() that sets two scalars in the requested policy structure.
1437  * Same locking rules apply.
1438  */
1439 void
proc_set_task_policy2(task_t task,int category,int flavor,int value,int value2)1440 proc_set_task_policy2(task_t    task,
1441     int       category,
1442     int       flavor,
1443     int       value,
1444     int       value2)
1445 {
1446 	struct task_pend_token pend_token = {};
1447 
1448 	task_lock(task);
1449 
1450 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1451 	    (IMPORTANCE_CODE(flavor, (category | TASK_POLICY_TASK))) | DBG_FUNC_START,
1452 	    task_pid(task), trequested_0(task),
1453 	    trequested_1(task), value, 0);
1454 
1455 	proc_set_task_policy_locked(task, category, flavor, value, value2);
1456 
1457 	task_policy_update_locked(task, &pend_token);
1458 
1459 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1460 	    (IMPORTANCE_CODE(flavor, (category | TASK_POLICY_TASK))) | DBG_FUNC_END,
1461 	    task_pid(task), trequested_0(task),
1462 	    trequested_1(task), tpending(&pend_token), 0);
1463 
1464 	task_unlock(task);
1465 
1466 	task_policy_update_complete_unlocked(task, &pend_token);
1467 }
1468 
1469 /*
1470  * Set the requested state for a specific flavor to a specific value.
1471  *
1472  *  TODO:
1473  *  Verify that arguments to non iopol things are 1 or 0
1474  */
1475 static void
proc_set_task_policy_locked(task_t task,int category,int flavor,int value,int value2)1476 proc_set_task_policy_locked(task_t      task,
1477     int         category,
1478     int         flavor,
1479     int         value,
1480     int         value2)
1481 {
1482 	int tier, passive;
1483 
1484 	struct task_requested_policy requested = task->requested_policy;
1485 
1486 	switch (flavor) {
1487 	/* Category: EXTERNAL and INTERNAL */
1488 
1489 	case TASK_POLICY_DARWIN_BG:
1490 		if (category == TASK_POLICY_EXTERNAL) {
1491 			requested.trp_ext_darwinbg = value;
1492 		} else {
1493 			requested.trp_int_darwinbg = value;
1494 		}
1495 		break;
1496 
1497 	case TASK_POLICY_IOPOL:
1498 		proc_iopol_to_tier(value, &tier, &passive);
1499 		if (category == TASK_POLICY_EXTERNAL) {
1500 			requested.trp_ext_iotier  = tier;
1501 			requested.trp_ext_iopassive = passive;
1502 		} else {
1503 			requested.trp_int_iotier  = tier;
1504 			requested.trp_int_iopassive = passive;
1505 		}
1506 		break;
1507 
1508 	case TASK_POLICY_IO:
1509 		if (category == TASK_POLICY_EXTERNAL) {
1510 			requested.trp_ext_iotier = value;
1511 		} else {
1512 			requested.trp_int_iotier = value;
1513 		}
1514 		break;
1515 
1516 	case TASK_POLICY_PASSIVE_IO:
1517 		if (category == TASK_POLICY_EXTERNAL) {
1518 			requested.trp_ext_iopassive = value;
1519 		} else {
1520 			requested.trp_int_iopassive = value;
1521 		}
1522 		break;
1523 
1524 	/* Category: INTERNAL */
1525 
1526 	case TASK_POLICY_DARWIN_BG_IOPOL:
1527 		assert(category == TASK_POLICY_INTERNAL);
1528 		proc_iopol_to_tier(value, &tier, &passive);
1529 		requested.trp_bg_iotier = tier;
1530 		break;
1531 
1532 	/* Category: ATTRIBUTE */
1533 
1534 	case TASK_POLICY_BOOST:
1535 		assert(category == TASK_POLICY_ATTRIBUTE);
1536 		requested.trp_boosted = value;
1537 		break;
1538 
1539 	case TASK_POLICY_ROLE:
1540 		assert(category == TASK_POLICY_ATTRIBUTE);
1541 		requested.trp_role = value;
1542 		break;
1543 
1544 	case TASK_POLICY_TERMINATED:
1545 		assert(category == TASK_POLICY_ATTRIBUTE);
1546 		requested.trp_terminated = value;
1547 		break;
1548 
1549 	case TASK_BASE_LATENCY_QOS_POLICY:
1550 		assert(category == TASK_POLICY_ATTRIBUTE);
1551 		requested.trp_base_latency_qos = value;
1552 		break;
1553 
1554 	case TASK_BASE_THROUGHPUT_QOS_POLICY:
1555 		assert(category == TASK_POLICY_ATTRIBUTE);
1556 		requested.trp_base_through_qos = value;
1557 		break;
1558 
1559 	case TASK_POLICY_SFI_MANAGED:
1560 		assert(category == TASK_POLICY_ATTRIBUTE);
1561 		requested.trp_sfi_managed = value;
1562 		break;
1563 
1564 	case TASK_POLICY_BASE_LATENCY_AND_THROUGHPUT_QOS:
1565 		assert(category == TASK_POLICY_ATTRIBUTE);
1566 		requested.trp_base_latency_qos = value;
1567 		requested.trp_base_through_qos = value2;
1568 		break;
1569 
1570 	case TASK_POLICY_OVERRIDE_LATENCY_AND_THROUGHPUT_QOS:
1571 		assert(category == TASK_POLICY_ATTRIBUTE);
1572 		requested.trp_over_latency_qos = value;
1573 		requested.trp_over_through_qos = value2;
1574 		break;
1575 
1576 	default:
1577 		panic("unknown task policy: %d %d %d %d", category, flavor, value, value2);
1578 		break;
1579 	}
1580 
1581 	task->requested_policy = requested;
1582 }
1583 
1584 /*
1585  * Gets what you set. Effective values may be different.
1586  */
1587 int
proc_get_task_policy(task_t task,int category,int flavor)1588 proc_get_task_policy(task_t     task,
1589     int        category,
1590     int        flavor)
1591 {
1592 	int value = 0;
1593 
1594 	task_lock(task);
1595 
1596 	struct task_requested_policy requested = task->requested_policy;
1597 
1598 	switch (flavor) {
1599 	case TASK_POLICY_DARWIN_BG:
1600 		if (category == TASK_POLICY_EXTERNAL) {
1601 			value = requested.trp_ext_darwinbg;
1602 		} else {
1603 			value = requested.trp_int_darwinbg;
1604 		}
1605 		break;
1606 	case TASK_POLICY_IOPOL:
1607 		if (category == TASK_POLICY_EXTERNAL) {
1608 			value = proc_tier_to_iopol(requested.trp_ext_iotier,
1609 			    requested.trp_ext_iopassive);
1610 		} else {
1611 			value = proc_tier_to_iopol(requested.trp_int_iotier,
1612 			    requested.trp_int_iopassive);
1613 		}
1614 		break;
1615 	case TASK_POLICY_IO:
1616 		if (category == TASK_POLICY_EXTERNAL) {
1617 			value = requested.trp_ext_iotier;
1618 		} else {
1619 			value = requested.trp_int_iotier;
1620 		}
1621 		break;
1622 	case TASK_POLICY_PASSIVE_IO:
1623 		if (category == TASK_POLICY_EXTERNAL) {
1624 			value = requested.trp_ext_iopassive;
1625 		} else {
1626 			value = requested.trp_int_iopassive;
1627 		}
1628 		break;
1629 	case TASK_POLICY_DARWIN_BG_IOPOL:
1630 		assert(category == TASK_POLICY_INTERNAL);
1631 		value = proc_tier_to_iopol(requested.trp_bg_iotier, 0);
1632 		break;
1633 	case TASK_POLICY_ROLE:
1634 		assert(category == TASK_POLICY_ATTRIBUTE);
1635 		value = requested.trp_role;
1636 		break;
1637 	case TASK_POLICY_SFI_MANAGED:
1638 		assert(category == TASK_POLICY_ATTRIBUTE);
1639 		value = requested.trp_sfi_managed;
1640 		break;
1641 	default:
1642 		panic("unknown policy_flavor %d", flavor);
1643 		break;
1644 	}
1645 
1646 	task_unlock(task);
1647 
1648 	return value;
1649 }
1650 
1651 /*
1652  * Variant of proc_get_task_policy() that returns two scalar outputs.
1653  */
1654 void
proc_get_task_policy2(task_t task,__assert_only int category,int flavor,int * value1,int * value2)1655 proc_get_task_policy2(task_t task,
1656     __assert_only int category,
1657     int flavor,
1658     int *value1,
1659     int *value2)
1660 {
1661 	task_lock(task);
1662 
1663 	struct task_requested_policy requested = task->requested_policy;
1664 
1665 	switch (flavor) {
1666 	case TASK_POLICY_BASE_LATENCY_AND_THROUGHPUT_QOS:
1667 		assert(category == TASK_POLICY_ATTRIBUTE);
1668 		*value1 = requested.trp_base_latency_qos;
1669 		*value2 = requested.trp_base_through_qos;
1670 		break;
1671 
1672 	case TASK_POLICY_OVERRIDE_LATENCY_AND_THROUGHPUT_QOS:
1673 		assert(category == TASK_POLICY_ATTRIBUTE);
1674 		*value1 = requested.trp_over_latency_qos;
1675 		*value2 = requested.trp_over_through_qos;
1676 		break;
1677 
1678 	default:
1679 		panic("unknown policy_flavor %d", flavor);
1680 		break;
1681 	}
1682 
1683 	task_unlock(task);
1684 }
1685 
1686 /*
1687  * Function for querying effective state for relevant subsystems
1688  * Gets what is actually in effect, for subsystems which pull policy instead of receive updates.
1689  *
1690  * ONLY the relevant subsystem should query this.
1691  * NEVER take a value from the 'effective' function and stuff it into a setter.
1692  *
1693  * NOTE: This accessor does not take the task lock.
1694  * Notifications of state updates need to be externally synchronized with state queries.
1695  * This routine *MUST* remain interrupt safe, as it is potentially invoked
1696  * within the context of a timer interrupt.  It is also called in KDP context for stackshot.
1697  */
1698 int
proc_get_effective_task_policy(task_t task,int flavor)1699 proc_get_effective_task_policy(task_t   task,
1700     int      flavor)
1701 {
1702 	int value = 0;
1703 
1704 	switch (flavor) {
1705 	case TASK_POLICY_DARWIN_BG:
1706 		/*
1707 		 * This backs the KPI call proc_pidbackgrounded to find
1708 		 * out if a pid is backgrounded.
1709 		 * It is used to communicate state to the VM system, as well as
1710 		 * prioritizing requests to the graphics system.
1711 		 * Returns 1 for background mode, 0 for normal mode
1712 		 */
1713 		value = task->effective_policy.tep_darwinbg;
1714 		break;
1715 	case TASK_POLICY_ALL_SOCKETS_BG:
1716 		/*
1717 		 * do_background_socket() calls this to determine what it should do to the proc's sockets
1718 		 * Returns 1 for background mode, 0 for normal mode
1719 		 *
1720 		 * This consults both thread and task so un-DBGing a thread while the task is BG
1721 		 * doesn't get you out of the network throttle.
1722 		 */
1723 		value = task->effective_policy.tep_all_sockets_bg;
1724 		break;
1725 	case TASK_POLICY_SUP_ACTIVE:
1726 		/*
1727 		 * Is the task in AppNap? This is used to determine the urgency
1728 		 * that's passed to the performance management subsystem for threads
1729 		 * that are running at a priority <= MAXPRI_THROTTLE.
1730 		 */
1731 		value = task->effective_policy.tep_sup_active;
1732 		break;
1733 	case TASK_POLICY_LATENCY_QOS:
1734 		/*
1735 		 * timer arming calls into here to find out the timer coalescing level
1736 		 * Returns a QoS tier (0-6)
1737 		 */
1738 		value = task->effective_policy.tep_latency_qos;
1739 		break;
1740 	case TASK_POLICY_THROUGH_QOS:
1741 		/*
1742 		 * This value is passed into the urgency callout from the scheduler
1743 		 * to the performance management subsystem.
1744 		 * Returns a QoS tier (0-6)
1745 		 */
1746 		value = task->effective_policy.tep_through_qos;
1747 		break;
1748 	case TASK_POLICY_ROLE:
1749 		/*
1750 		 * This controls various things that ask whether a process is foreground,
1751 		 * like SFI, VM, access to GPU, etc
1752 		 */
1753 		value = task->effective_policy.tep_role;
1754 		break;
1755 	case TASK_POLICY_WATCHERS_BG:
1756 		/*
1757 		 * This controls whether or not a thread watching this process should be BG.
1758 		 */
1759 		value = task->effective_policy.tep_watchers_bg;
1760 		break;
1761 	case TASK_POLICY_SFI_MANAGED:
1762 		/*
1763 		 * This controls whether or not a process is targeted for specific control by thermald.
1764 		 */
1765 		value = task->effective_policy.tep_sfi_managed;
1766 		break;
1767 	default:
1768 		panic("unknown policy_flavor %d", flavor);
1769 		break;
1770 	}
1771 
1772 	return value;
1773 }
1774 
1775 /*
1776  * Convert from IOPOL_* values to throttle tiers.
1777  *
1778  * TODO: Can this be made more compact, like an array lookup
1779  * Note that it is possible to support e.g. IOPOL_PASSIVE_STANDARD in the future
1780  */
1781 
1782 void
proc_iopol_to_tier(int iopolicy,int * tier,int * passive)1783 proc_iopol_to_tier(int iopolicy, int *tier, int *passive)
1784 {
1785 	*passive = 0;
1786 	*tier = 0;
1787 	switch (iopolicy) {
1788 	case IOPOL_IMPORTANT:
1789 		*tier = THROTTLE_LEVEL_TIER0;
1790 		break;
1791 	case IOPOL_PASSIVE:
1792 		*tier = THROTTLE_LEVEL_TIER0;
1793 		*passive = 1;
1794 		break;
1795 	case IOPOL_STANDARD:
1796 		*tier = THROTTLE_LEVEL_TIER1;
1797 		break;
1798 	case IOPOL_UTILITY:
1799 		*tier = THROTTLE_LEVEL_TIER2;
1800 		break;
1801 	case IOPOL_THROTTLE:
1802 		*tier = THROTTLE_LEVEL_TIER3;
1803 		break;
1804 	default:
1805 		panic("unknown I/O policy %d", iopolicy);
1806 		break;
1807 	}
1808 }
1809 
1810 int
proc_tier_to_iopol(int tier,int passive)1811 proc_tier_to_iopol(int tier, int passive)
1812 {
1813 	if (passive == 1) {
1814 		switch (tier) {
1815 		case THROTTLE_LEVEL_TIER0:
1816 			return IOPOL_PASSIVE;
1817 		default:
1818 			panic("unknown passive tier %d", tier);
1819 			return IOPOL_DEFAULT;
1820 		}
1821 	} else {
1822 		switch (tier) {
1823 		case THROTTLE_LEVEL_NONE:
1824 		case THROTTLE_LEVEL_TIER0:
1825 			return IOPOL_DEFAULT;
1826 		case THROTTLE_LEVEL_TIER1:
1827 			return IOPOL_STANDARD;
1828 		case THROTTLE_LEVEL_TIER2:
1829 			return IOPOL_UTILITY;
1830 		case THROTTLE_LEVEL_TIER3:
1831 			return IOPOL_THROTTLE;
1832 		default:
1833 			panic("unknown tier %d", tier);
1834 			return IOPOL_DEFAULT;
1835 		}
1836 	}
1837 }
1838 
1839 int
proc_darwin_role_to_task_role(int darwin_role,task_role_t * task_role)1840 proc_darwin_role_to_task_role(int darwin_role, task_role_t* task_role)
1841 {
1842 	integer_t role = TASK_UNSPECIFIED;
1843 
1844 	switch (darwin_role) {
1845 	case PRIO_DARWIN_ROLE_DEFAULT:
1846 		role = TASK_UNSPECIFIED;
1847 		break;
1848 	case PRIO_DARWIN_ROLE_UI_FOCAL:
1849 		role = TASK_FOREGROUND_APPLICATION;
1850 		break;
1851 	case PRIO_DARWIN_ROLE_UI:
1852 		role = TASK_DEFAULT_APPLICATION;
1853 		break;
1854 	case PRIO_DARWIN_ROLE_NON_UI:
1855 		role = TASK_NONUI_APPLICATION;
1856 		break;
1857 	case PRIO_DARWIN_ROLE_UI_NON_FOCAL:
1858 		role = TASK_BACKGROUND_APPLICATION;
1859 		break;
1860 	case PRIO_DARWIN_ROLE_TAL_LAUNCH:
1861 		role = TASK_THROTTLE_APPLICATION;
1862 		break;
1863 	case PRIO_DARWIN_ROLE_DARWIN_BG:
1864 		role = TASK_DARWINBG_APPLICATION;
1865 		break;
1866 	default:
1867 		return EINVAL;
1868 	}
1869 
1870 	*task_role = role;
1871 
1872 	return 0;
1873 }
1874 
1875 int
proc_task_role_to_darwin_role(task_role_t task_role)1876 proc_task_role_to_darwin_role(task_role_t task_role)
1877 {
1878 	switch (task_role) {
1879 	case TASK_FOREGROUND_APPLICATION:
1880 		return PRIO_DARWIN_ROLE_UI_FOCAL;
1881 	case TASK_BACKGROUND_APPLICATION:
1882 		return PRIO_DARWIN_ROLE_UI_NON_FOCAL;
1883 	case TASK_NONUI_APPLICATION:
1884 		return PRIO_DARWIN_ROLE_NON_UI;
1885 	case TASK_DEFAULT_APPLICATION:
1886 		return PRIO_DARWIN_ROLE_UI;
1887 	case TASK_THROTTLE_APPLICATION:
1888 		return PRIO_DARWIN_ROLE_TAL_LAUNCH;
1889 	case TASK_DARWINBG_APPLICATION:
1890 		return PRIO_DARWIN_ROLE_DARWIN_BG;
1891 	case TASK_UNSPECIFIED:
1892 	default:
1893 		return PRIO_DARWIN_ROLE_DEFAULT;
1894 	}
1895 }
1896 
1897 
1898 /* TODO: remove this variable when interactive daemon audit period is over */
1899 static TUNABLE(bool, ipc_importance_interactive_receiver,
1900     "imp_interactive_receiver", false);
1901 
1902 /*
1903  * Called at process exec to initialize the apptype, qos clamp, and qos seed of a process
1904  *
1905  * TODO: Make this function more table-driven instead of ad-hoc
1906  */
1907 void
proc_set_task_spawnpolicy(task_t task,thread_t thread,int apptype,int qos_clamp,task_role_t role,ipc_port_t * portwatch_ports,uint32_t portwatch_count)1908 proc_set_task_spawnpolicy(task_t task, thread_t thread, int apptype, int qos_clamp, task_role_t role,
1909     ipc_port_t * portwatch_ports, uint32_t portwatch_count)
1910 {
1911 	struct task_pend_token pend_token = {};
1912 
1913 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1914 	    (IMPORTANCE_CODE(IMP_TASK_APPTYPE, apptype)) | DBG_FUNC_START,
1915 	    task_pid(task), trequested_0(task), trequested_1(task),
1916 	    apptype, 0);
1917 
1918 	if (apptype != TASK_APPTYPE_NONE) {
1919 		/*
1920 		 * Reset the receiver and denap state inherited from the
1921 		 * task's parent, but only if we are going to reset it via the
1922 		 * provided apptype.
1923 		 */
1924 		if (task_is_importance_receiver(task)) {
1925 			task_importance_mark_receiver(task, FALSE);
1926 		}
1927 		if (task_is_importance_denap_receiver(task)) {
1928 			task_importance_mark_denap_receiver(task, FALSE);
1929 		}
1930 	}
1931 
1932 	switch (apptype) {
1933 	case TASK_APPTYPE_APP_DEFAULT:
1934 		/* Apps become donors via the 'live-donor' flag instead of the static donor flag */
1935 		task_importance_mark_donor(task, FALSE);
1936 		task_importance_mark_live_donor(task, TRUE);
1937 		// importance_receiver == FALSE
1938 #if defined(XNU_TARGET_OS_OSX)
1939 		/* Apps are de-nap recievers on macOS for suppression behaviors */
1940 		task_importance_mark_denap_receiver(task, TRUE);
1941 #endif /* !defined(XNU_TARGET_OS_OSX) */
1942 		break;
1943 
1944 	case TASK_APPTYPE_DAEMON_INTERACTIVE:
1945 		task_importance_mark_donor(task, TRUE);
1946 		task_importance_mark_live_donor(task, FALSE);
1947 		// importance_denap_receiver == FALSE
1948 
1949 		/*
1950 		 * A boot arg controls whether interactive daemons are importance receivers.
1951 		 * Normally, they are not.  But for testing their behavior as an adaptive
1952 		 * daemon, the boot-arg can be set.
1953 		 *
1954 		 * TODO: remove this when the interactive daemon audit period is over.
1955 		 */
1956 		task_importance_mark_receiver(task, /* FALSE */ ipc_importance_interactive_receiver);
1957 		break;
1958 
1959 	case TASK_APPTYPE_DAEMON_STANDARD:
1960 		task_importance_mark_donor(task, TRUE);
1961 		task_importance_mark_live_donor(task, FALSE);
1962 		// importance_denap_receiver == FALSE
1963 		// importance_receiver == FALSE
1964 		break;
1965 
1966 	case TASK_APPTYPE_DAEMON_ADAPTIVE:
1967 		task_importance_mark_donor(task, FALSE);
1968 		task_importance_mark_live_donor(task, FALSE);
1969 		task_importance_mark_receiver(task, TRUE);
1970 		// importance_denap_receiver == FALSE
1971 		break;
1972 
1973 	case TASK_APPTYPE_DAEMON_BACKGROUND:
1974 		task_importance_mark_donor(task, FALSE);
1975 		task_importance_mark_live_donor(task, FALSE);
1976 		// importance_denap_receiver == FALSE
1977 		// importance_receiver == FALSE
1978 		break;
1979 
1980 	case TASK_APPTYPE_DRIVER:
1981 		task_importance_mark_donor(task, FALSE);
1982 		task_importance_mark_live_donor(task, FALSE);
1983 		// importance_denap_receiver == FALSE
1984 		// importance_receiver == FALSE
1985 		break;
1986 
1987 	case TASK_APPTYPE_NONE:
1988 		break;
1989 	}
1990 
1991 	if (portwatch_ports != NULL && apptype == TASK_APPTYPE_DAEMON_ADAPTIVE) {
1992 		int portwatch_boosts = 0;
1993 
1994 		for (uint32_t i = 0; i < portwatch_count; i++) {
1995 			ipc_port_t port = NULL;
1996 
1997 			if (IP_VALID(port = portwatch_ports[i])) {
1998 				int boost = 0;
1999 				task_add_importance_watchport(task, port, &boost);
2000 				portwatch_boosts += boost;
2001 			}
2002 		}
2003 
2004 		if (portwatch_boosts > 0) {
2005 			task_importance_hold_internal_assertion(task, portwatch_boosts);
2006 		}
2007 	}
2008 
2009 	/* Redirect the turnstile push of watchports to task */
2010 	if (portwatch_count && portwatch_ports != NULL) {
2011 		task_add_turnstile_watchports(task, thread, portwatch_ports, portwatch_count);
2012 	}
2013 
2014 	task_lock(task);
2015 
2016 	if (apptype != TASK_APPTYPE_NONE) {
2017 		task->requested_policy.trp_apptype = apptype;
2018 	}
2019 
2020 #if !defined(XNU_TARGET_OS_OSX)
2021 	/* Remove this after launchd starts setting it properly */
2022 	if (apptype == TASK_APPTYPE_APP_DEFAULT && role == TASK_UNSPECIFIED) {
2023 		task->requested_policy.trp_role = TASK_FOREGROUND_APPLICATION;
2024 	} else
2025 #endif
2026 	if (role != TASK_UNSPECIFIED) {
2027 		task->requested_policy.trp_role = (uint32_t)role;
2028 	}
2029 
2030 	if (qos_clamp != THREAD_QOS_UNSPECIFIED) {
2031 		task->requested_policy.trp_qos_clamp = qos_clamp;
2032 	}
2033 
2034 	task_policy_update_locked(task, &pend_token);
2035 
2036 	task_unlock(task);
2037 
2038 	/* Ensure the donor bit is updated to be in sync with the new live donor status */
2039 	pend_token.tpt_update_live_donor = 1;
2040 
2041 	task_policy_update_complete_unlocked(task, &pend_token);
2042 
2043 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
2044 	    (IMPORTANCE_CODE(IMP_TASK_APPTYPE, apptype)) | DBG_FUNC_END,
2045 	    task_pid(task), trequested_0(task), trequested_1(task),
2046 	    task_is_importance_receiver(task), 0);
2047 }
2048 
2049 /*
2050  * Inherit task role across exec
2051  */
2052 void
proc_inherit_task_role(task_t new_task,task_t old_task)2053 proc_inherit_task_role(task_t new_task,
2054     task_t old_task)
2055 {
2056 	int role;
2057 
2058 	/* inherit the role from old task to new task */
2059 	role = proc_get_task_policy(old_task, TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE);
2060 	proc_set_task_policy(new_task, TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE, role);
2061 }
2062 
2063 extern void * XNU_PTRAUTH_SIGNED_PTR("initproc") initproc;
2064 
2065 /*
2066  * Compute the default main thread qos for a task
2067  */
2068 thread_qos_t
task_compute_main_thread_qos(task_t task)2069 task_compute_main_thread_qos(task_t task)
2070 {
2071 	thread_qos_t primordial_qos = THREAD_QOS_UNSPECIFIED;
2072 
2073 	thread_qos_t qos_clamp = task->requested_policy.trp_qos_clamp;
2074 
2075 	switch (task->requested_policy.trp_apptype) {
2076 	case TASK_APPTYPE_APP_TAL:
2077 	case TASK_APPTYPE_APP_DEFAULT:
2078 		primordial_qos = THREAD_QOS_USER_INTERACTIVE;
2079 		break;
2080 
2081 	case TASK_APPTYPE_DAEMON_INTERACTIVE:
2082 	case TASK_APPTYPE_DAEMON_STANDARD:
2083 	case TASK_APPTYPE_DAEMON_ADAPTIVE:
2084 	case TASK_APPTYPE_DRIVER:
2085 		primordial_qos = THREAD_QOS_LEGACY;
2086 		break;
2087 
2088 	case TASK_APPTYPE_DAEMON_BACKGROUND:
2089 		primordial_qos = THREAD_QOS_BACKGROUND;
2090 		break;
2091 	}
2092 
2093 	if (task->bsd_info == initproc) {
2094 		/* PID 1 gets a special case */
2095 		primordial_qos = MAX(primordial_qos, THREAD_QOS_USER_INITIATED);
2096 	}
2097 
2098 	if (qos_clamp != THREAD_QOS_UNSPECIFIED) {
2099 		if (primordial_qos != THREAD_QOS_UNSPECIFIED) {
2100 			primordial_qos = MIN(qos_clamp, primordial_qos);
2101 		} else {
2102 			primordial_qos = qos_clamp;
2103 		}
2104 	}
2105 
2106 	return primordial_qos;
2107 }
2108 
2109 
2110 /* for process_policy to check before attempting to set */
2111 boolean_t
proc_task_is_tal(task_t task)2112 proc_task_is_tal(task_t task)
2113 {
2114 	return (task->requested_policy.trp_apptype == TASK_APPTYPE_APP_TAL) ? TRUE : FALSE;
2115 }
2116 
2117 int
task_get_apptype(task_t task)2118 task_get_apptype(task_t task)
2119 {
2120 	return task->requested_policy.trp_apptype;
2121 }
2122 
2123 boolean_t
task_is_daemon(task_t task)2124 task_is_daemon(task_t task)
2125 {
2126 	switch (task->requested_policy.trp_apptype) {
2127 	case TASK_APPTYPE_DAEMON_INTERACTIVE:
2128 	case TASK_APPTYPE_DAEMON_STANDARD:
2129 	case TASK_APPTYPE_DAEMON_ADAPTIVE:
2130 	case TASK_APPTYPE_DAEMON_BACKGROUND:
2131 		return TRUE;
2132 	default:
2133 		return FALSE;
2134 	}
2135 }
2136 
2137 bool
task_is_driver(task_t task)2138 task_is_driver(task_t task)
2139 {
2140 	if (!task) {
2141 		return FALSE;
2142 	}
2143 	return task->requested_policy.trp_apptype == TASK_APPTYPE_DRIVER;
2144 }
2145 
2146 boolean_t
task_is_app(task_t task)2147 task_is_app(task_t task)
2148 {
2149 	switch (task->requested_policy.trp_apptype) {
2150 	case TASK_APPTYPE_APP_DEFAULT:
2151 	case TASK_APPTYPE_APP_TAL:
2152 		return TRUE;
2153 	default:
2154 		return FALSE;
2155 	}
2156 }
2157 
2158 /* for telemetry */
2159 integer_t
task_grab_latency_qos(task_t task)2160 task_grab_latency_qos(task_t task)
2161 {
2162 	return qos_latency_policy_package(proc_get_effective_task_policy(task, TASK_POLICY_LATENCY_QOS));
2163 }
2164 
2165 /* update the darwin background action state in the flags field for libproc */
2166 int
proc_get_darwinbgstate(task_t task,uint32_t * flagsp)2167 proc_get_darwinbgstate(task_t task, uint32_t * flagsp)
2168 {
2169 	if (task->requested_policy.trp_ext_darwinbg) {
2170 		*flagsp |= PROC_FLAG_EXT_DARWINBG;
2171 	}
2172 
2173 	if (task->requested_policy.trp_int_darwinbg) {
2174 		*flagsp |= PROC_FLAG_DARWINBG;
2175 	}
2176 
2177 #if !defined(XNU_TARGET_OS_OSX)
2178 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_DAEMON_BACKGROUND) {
2179 		*flagsp |= PROC_FLAG_IOS_APPLEDAEMON;
2180 	}
2181 
2182 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_DAEMON_ADAPTIVE) {
2183 		*flagsp |= PROC_FLAG_IOS_IMPPROMOTION;
2184 	}
2185 #endif /* !defined(XNU_TARGET_OS_OSX) */
2186 
2187 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_APP_DEFAULT ||
2188 	    task->requested_policy.trp_apptype == TASK_APPTYPE_APP_TAL) {
2189 		*flagsp |= PROC_FLAG_APPLICATION;
2190 	}
2191 
2192 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_DAEMON_ADAPTIVE) {
2193 		*flagsp |= PROC_FLAG_ADAPTIVE;
2194 	}
2195 
2196 	if (task->requested_policy.trp_apptype == TASK_APPTYPE_DAEMON_ADAPTIVE &&
2197 	    task->requested_policy.trp_boosted == 1) {
2198 		*flagsp |= PROC_FLAG_ADAPTIVE_IMPORTANT;
2199 	}
2200 
2201 	if (task_is_importance_donor(task)) {
2202 		*flagsp |= PROC_FLAG_IMPORTANCE_DONOR;
2203 	}
2204 
2205 	if (task->effective_policy.tep_sup_active) {
2206 		*flagsp |= PROC_FLAG_SUPPRESSED;
2207 	}
2208 
2209 	return 0;
2210 }
2211 
2212 /*
2213  * Tracepoint data... Reading the tracepoint data can be somewhat complicated.
2214  * The current scheme packs as much data into a single tracepoint as it can.
2215  *
2216  * Each task/thread requested/effective structure is 64 bits in size. Any
2217  * given tracepoint will emit either requested or effective data, but not both.
2218  *
2219  * A tracepoint may emit any of task, thread, or task & thread data.
2220  *
2221  * The type of data emitted varies with pointer size. Where possible, both
2222  * task and thread data are emitted. In LP32 systems, the first and second
2223  * halves of either the task or thread data is emitted.
2224  *
2225  * The code uses uintptr_t array indexes instead of high/low to avoid
2226  * confusion WRT big vs little endian.
2227  *
2228  * The truth table for the tracepoint data functions is below, and has the
2229  * following invariants:
2230  *
2231  * 1) task and thread are uintptr_t*
2232  * 2) task may never be NULL
2233  *
2234  *
2235  *                                     LP32            LP64
2236  * trequested_0(task, NULL)            task[0]         task[0]
2237  * trequested_1(task, NULL)            task[1]         NULL
2238  * trequested_0(task, thread)          thread[0]       task[0]
2239  * trequested_1(task, thread)          thread[1]       thread[0]
2240  *
2241  * Basically, you get a full task or thread on LP32, and both on LP64.
2242  *
2243  * The uintptr_t munging here is squicky enough to deserve a comment.
2244  *
2245  * The variables we are accessing are laid out in memory like this:
2246  *
2247  * [            LP64 uintptr_t  0          ]
2248  * [ LP32 uintptr_t 0 ] [ LP32 uintptr_t 1 ]
2249  *
2250  *      1   2   3   4     5   6   7   8
2251  *
2252  */
2253 
2254 static uintptr_t
trequested_0(task_t task)2255 trequested_0(task_t task)
2256 {
2257 	static_assert(sizeof(struct task_requested_policy) == sizeof(uint64_t), "size invariant violated");
2258 
2259 	uintptr_t* raw = (uintptr_t*)&task->requested_policy;
2260 
2261 	return raw[0];
2262 }
2263 
2264 static uintptr_t
trequested_1(task_t task)2265 trequested_1(task_t task)
2266 {
2267 #if defined __LP64__
2268 	(void)task;
2269 	return 0;
2270 #else
2271 	uintptr_t* raw = (uintptr_t*)(&task->requested_policy);
2272 	return raw[1];
2273 #endif
2274 }
2275 
2276 static uintptr_t
teffective_0(task_t task)2277 teffective_0(task_t task)
2278 {
2279 	uintptr_t* raw = (uintptr_t*)&task->effective_policy;
2280 
2281 	return raw[0];
2282 }
2283 
2284 static uintptr_t
teffective_1(task_t task)2285 teffective_1(task_t task)
2286 {
2287 #if defined __LP64__
2288 	(void)task;
2289 	return 0;
2290 #else
2291 	uintptr_t* raw = (uintptr_t*)(&task->effective_policy);
2292 	return raw[1];
2293 #endif
2294 }
2295 
2296 /* dump pending for tracepoint */
2297 uint32_t
tpending(task_pend_token_t pend_token)2298 tpending(task_pend_token_t pend_token)
2299 {
2300 	return *(uint32_t*)(void*)(pend_token);
2301 }
2302 
2303 uint64_t
task_requested_bitfield(task_t task)2304 task_requested_bitfield(task_t task)
2305 {
2306 	uint64_t bits = 0;
2307 	struct task_requested_policy requested = task->requested_policy;
2308 
2309 	bits |= (requested.trp_int_darwinbg     ? POLICY_REQ_INT_DARWIN_BG  : 0);
2310 	bits |= (requested.trp_ext_darwinbg     ? POLICY_REQ_EXT_DARWIN_BG  : 0);
2311 	bits |= (requested.trp_int_iotier       ? (((uint64_t)requested.trp_int_iotier) << POLICY_REQ_INT_IO_TIER_SHIFT) : 0);
2312 	bits |= (requested.trp_ext_iotier       ? (((uint64_t)requested.trp_ext_iotier) << POLICY_REQ_EXT_IO_TIER_SHIFT) : 0);
2313 	bits |= (requested.trp_int_iopassive    ? POLICY_REQ_INT_PASSIVE_IO : 0);
2314 	bits |= (requested.trp_ext_iopassive    ? POLICY_REQ_EXT_PASSIVE_IO : 0);
2315 	bits |= (requested.trp_bg_iotier        ? (((uint64_t)requested.trp_bg_iotier) << POLICY_REQ_BG_IOTIER_SHIFT)   : 0);
2316 	bits |= (requested.trp_terminated       ? POLICY_REQ_TERMINATED     : 0);
2317 
2318 	bits |= (requested.trp_boosted          ? POLICY_REQ_BOOSTED        : 0);
2319 	bits |= (requested.trp_tal_enabled      ? POLICY_REQ_TAL_ENABLED    : 0);
2320 	bits |= (requested.trp_apptype          ? (((uint64_t)requested.trp_apptype) << POLICY_REQ_APPTYPE_SHIFT)  : 0);
2321 	bits |= (requested.trp_role             ? (((uint64_t)requested.trp_role) << POLICY_REQ_ROLE_SHIFT)     : 0);
2322 
2323 	bits |= (requested.trp_sup_active       ? POLICY_REQ_SUP_ACTIVE         : 0);
2324 	bits |= (requested.trp_sup_lowpri_cpu   ? POLICY_REQ_SUP_LOWPRI_CPU     : 0);
2325 	bits |= (requested.trp_sup_cpu          ? POLICY_REQ_SUP_CPU            : 0);
2326 	bits |= (requested.trp_sup_timer        ? (((uint64_t)requested.trp_sup_timer) << POLICY_REQ_SUP_TIMER_THROTTLE_SHIFT) : 0);
2327 	bits |= (requested.trp_sup_throughput   ? (((uint64_t)requested.trp_sup_throughput) << POLICY_REQ_SUP_THROUGHPUT_SHIFT)     : 0);
2328 	bits |= (requested.trp_sup_disk         ? POLICY_REQ_SUP_DISK_THROTTLE  : 0);
2329 	bits |= (requested.trp_sup_bg_sockets   ? POLICY_REQ_SUP_BG_SOCKETS     : 0);
2330 
2331 	bits |= (requested.trp_base_latency_qos ? (((uint64_t)requested.trp_base_latency_qos) << POLICY_REQ_BASE_LATENCY_QOS_SHIFT) : 0);
2332 	bits |= (requested.trp_over_latency_qos ? (((uint64_t)requested.trp_over_latency_qos) << POLICY_REQ_OVER_LATENCY_QOS_SHIFT) : 0);
2333 	bits |= (requested.trp_base_through_qos ? (((uint64_t)requested.trp_base_through_qos) << POLICY_REQ_BASE_THROUGH_QOS_SHIFT) : 0);
2334 	bits |= (requested.trp_over_through_qos ? (((uint64_t)requested.trp_over_through_qos) << POLICY_REQ_OVER_THROUGH_QOS_SHIFT) : 0);
2335 	bits |= (requested.trp_sfi_managed      ? POLICY_REQ_SFI_MANAGED        : 0);
2336 	bits |= (requested.trp_qos_clamp        ? (((uint64_t)requested.trp_qos_clamp) << POLICY_REQ_QOS_CLAMP_SHIFT)        : 0);
2337 
2338 	return bits;
2339 }
2340 
2341 uint64_t
task_effective_bitfield(task_t task)2342 task_effective_bitfield(task_t task)
2343 {
2344 	uint64_t bits = 0;
2345 	struct task_effective_policy effective = task->effective_policy;
2346 
2347 	bits |= (effective.tep_io_tier          ? (((uint64_t)effective.tep_io_tier) << POLICY_EFF_IO_TIER_SHIFT) : 0);
2348 	bits |= (effective.tep_io_passive       ? POLICY_EFF_IO_PASSIVE     : 0);
2349 	bits |= (effective.tep_darwinbg         ? POLICY_EFF_DARWIN_BG      : 0);
2350 	bits |= (effective.tep_lowpri_cpu       ? POLICY_EFF_LOWPRI_CPU     : 0);
2351 	bits |= (effective.tep_terminated       ? POLICY_EFF_TERMINATED     : 0);
2352 	bits |= (effective.tep_all_sockets_bg   ? POLICY_EFF_ALL_SOCKETS_BG : 0);
2353 	bits |= (effective.tep_new_sockets_bg   ? POLICY_EFF_NEW_SOCKETS_BG : 0);
2354 	bits |= (effective.tep_bg_iotier        ? (((uint64_t)effective.tep_bg_iotier) << POLICY_EFF_BG_IOTIER_SHIFT) : 0);
2355 	bits |= (effective.tep_qos_ui_is_urgent ? POLICY_EFF_QOS_UI_IS_URGENT : 0);
2356 
2357 	bits |= (effective.tep_tal_engaged      ? POLICY_EFF_TAL_ENGAGED    : 0);
2358 	bits |= (effective.tep_watchers_bg      ? POLICY_EFF_WATCHERS_BG    : 0);
2359 	bits |= (effective.tep_sup_active       ? POLICY_EFF_SUP_ACTIVE     : 0);
2360 	bits |= (effective.tep_suppressed_cpu   ? POLICY_EFF_SUP_CPU        : 0);
2361 	bits |= (effective.tep_role             ? (((uint64_t)effective.tep_role) << POLICY_EFF_ROLE_SHIFT)        : 0);
2362 	bits |= (effective.tep_latency_qos      ? (((uint64_t)effective.tep_latency_qos) << POLICY_EFF_LATENCY_QOS_SHIFT) : 0);
2363 	bits |= (effective.tep_through_qos      ? (((uint64_t)effective.tep_through_qos) << POLICY_EFF_THROUGH_QOS_SHIFT) : 0);
2364 	bits |= (effective.tep_sfi_managed      ? POLICY_EFF_SFI_MANAGED    : 0);
2365 	bits |= (effective.tep_qos_ceiling      ? (((uint64_t)effective.tep_qos_ceiling) << POLICY_EFF_QOS_CEILING_SHIFT) : 0);
2366 
2367 	return bits;
2368 }
2369 
2370 
2371 /*
2372  * Resource usage and CPU related routines
2373  */
2374 
2375 int
proc_get_task_ruse_cpu(task_t task,uint32_t * policyp,uint8_t * percentagep,uint64_t * intervalp,uint64_t * deadlinep)2376 proc_get_task_ruse_cpu(task_t task, uint32_t *policyp, uint8_t *percentagep, uint64_t *intervalp, uint64_t *deadlinep)
2377 {
2378 	int error = 0;
2379 	int scope;
2380 
2381 	task_lock(task);
2382 
2383 
2384 	error = task_get_cpuusage(task, percentagep, intervalp, deadlinep, &scope);
2385 	task_unlock(task);
2386 
2387 	/*
2388 	 * Reverse-map from CPU resource limit scopes back to policies (see comment below).
2389 	 */
2390 	if (scope == TASK_RUSECPU_FLAGS_PERTHR_LIMIT) {
2391 		*policyp = TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC;
2392 	} else if (scope == TASK_RUSECPU_FLAGS_PROC_LIMIT) {
2393 		*policyp = TASK_POLICY_RESOURCE_ATTRIBUTE_THROTTLE;
2394 	} else if (scope == TASK_RUSECPU_FLAGS_DEADLINE) {
2395 		*policyp = TASK_POLICY_RESOURCE_ATTRIBUTE_NONE;
2396 	}
2397 
2398 	return error;
2399 }
2400 
2401 /*
2402  * Configure the default CPU usage monitor parameters.
2403  *
2404  * For tasks which have this mechanism activated: if any thread in the
2405  * process consumes more CPU than this, an EXC_RESOURCE exception will be generated.
2406  */
2407 void
proc_init_cpumon_params(void)2408 proc_init_cpumon_params(void)
2409 {
2410 	/*
2411 	 * The max CPU percentage can be configured via the boot-args and
2412 	 * a key in the device tree. The boot-args are honored first, then the
2413 	 * device tree.
2414 	 */
2415 	if (!PE_parse_boot_argn("max_cpumon_percentage", &proc_max_cpumon_percentage,
2416 	    sizeof(proc_max_cpumon_percentage))) {
2417 		uint64_t max_percentage = 0ULL;
2418 
2419 		if (!PE_get_default("kern.max_cpumon_percentage", &max_percentage,
2420 		    sizeof(max_percentage))) {
2421 			max_percentage = DEFAULT_CPUMON_PERCENTAGE;
2422 		}
2423 
2424 		assert(max_percentage <= UINT8_MAX);
2425 		proc_max_cpumon_percentage = (uint8_t) max_percentage;
2426 	}
2427 
2428 	if (proc_max_cpumon_percentage > 100) {
2429 		proc_max_cpumon_percentage = 100;
2430 	}
2431 
2432 	/*
2433 	 * The interval should be specified in seconds.
2434 	 *
2435 	 * Like the max CPU percentage, the max CPU interval can be configured
2436 	 * via boot-args and the device tree.
2437 	 */
2438 	if (!PE_parse_boot_argn("max_cpumon_interval", &proc_max_cpumon_interval,
2439 	    sizeof(proc_max_cpumon_interval))) {
2440 		if (!PE_get_default("kern.max_cpumon_interval", &proc_max_cpumon_interval,
2441 		    sizeof(proc_max_cpumon_interval))) {
2442 			proc_max_cpumon_interval = DEFAULT_CPUMON_INTERVAL;
2443 		}
2444 	}
2445 
2446 	proc_max_cpumon_interval *= NSEC_PER_SEC;
2447 
2448 	/* TEMPORARY boot arg to control App suppression */
2449 	PE_parse_boot_argn("task_policy_suppression_flags",
2450 	    &task_policy_suppression_flags,
2451 	    sizeof(task_policy_suppression_flags));
2452 
2453 	/* adjust suppression disk policy if called for in boot arg */
2454 	if (task_policy_suppression_flags & TASK_POLICY_SUPPRESSION_IOTIER2) {
2455 		proc_suppressed_disk_tier = THROTTLE_LEVEL_TIER2;
2456 	}
2457 }
2458 
2459 /*
2460  * Currently supported configurations for CPU limits.
2461  *
2462  * Policy				| Deadline-based CPU limit | Percentage-based CPU limit
2463  * -------------------------------------+--------------------------+------------------------------
2464  * PROC_POLICY_RSRCACT_THROTTLE		| ENOTSUP		   | Task-wide scope only
2465  * PROC_POLICY_RSRCACT_SUSPEND		| Task-wide scope only	   | ENOTSUP
2466  * PROC_POLICY_RSRCACT_TERMINATE	| Task-wide scope only	   | ENOTSUP
2467  * PROC_POLICY_RSRCACT_NOTIFY_KQ	| Task-wide scope only	   | ENOTSUP
2468  * PROC_POLICY_RSRCACT_NOTIFY_EXC	| ENOTSUP		   | Per-thread scope only
2469  *
2470  * A deadline-based CPU limit is actually a simple wallclock timer - the requested action is performed
2471  * after the specified amount of wallclock time has elapsed.
2472  *
2473  * A percentage-based CPU limit performs the requested action after the specified amount of actual CPU time
2474  * has been consumed -- regardless of how much wallclock time has elapsed -- by either the task as an
2475  * aggregate entity (so-called "Task-wide" or "Proc-wide" scope, whereby the CPU time consumed by all threads
2476  * in the task are added together), or by any one thread in the task (so-called "per-thread" scope).
2477  *
2478  * We support either deadline != 0 OR percentage != 0, but not both. The original intention in having them
2479  * share an API was to use actual CPU time as the basis of the deadline-based limit (as in: perform an action
2480  * after I have used some amount of CPU time; this is different than the recurring percentage/interval model)
2481  * but the potential consumer of the API at the time was insisting on wallclock time instead.
2482  *
2483  * Currently, requesting notification via an exception is the only way to get per-thread scope for a
2484  * CPU limit. All other types of notifications force task-wide scope for the limit.
2485  */
2486 int
proc_set_task_ruse_cpu(task_t task,uint16_t policy,uint8_t percentage,uint64_t interval,uint64_t deadline,int cpumon_entitled)2487 proc_set_task_ruse_cpu(task_t task, uint16_t policy, uint8_t percentage, uint64_t interval, uint64_t deadline,
2488     int cpumon_entitled)
2489 {
2490 	int error = 0;
2491 	int scope;
2492 
2493 	/*
2494 	 * Enforce the matrix of supported configurations for policy, percentage, and deadline.
2495 	 */
2496 	switch (policy) {
2497 	// If no policy is explicitly given, the default is to throttle.
2498 	case TASK_POLICY_RESOURCE_ATTRIBUTE_NONE:
2499 	case TASK_POLICY_RESOURCE_ATTRIBUTE_THROTTLE:
2500 		if (deadline != 0) {
2501 			return ENOTSUP;
2502 		}
2503 		scope = TASK_RUSECPU_FLAGS_PROC_LIMIT;
2504 		break;
2505 	case TASK_POLICY_RESOURCE_ATTRIBUTE_SUSPEND:
2506 	case TASK_POLICY_RESOURCE_ATTRIBUTE_TERMINATE:
2507 	case TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_KQ:
2508 		if (percentage != 0) {
2509 			return ENOTSUP;
2510 		}
2511 		scope = TASK_RUSECPU_FLAGS_DEADLINE;
2512 		break;
2513 	case TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC:
2514 		if (deadline != 0) {
2515 			return ENOTSUP;
2516 		}
2517 		scope = TASK_RUSECPU_FLAGS_PERTHR_LIMIT;
2518 #ifdef CONFIG_NOMONITORS
2519 		return error;
2520 #endif /* CONFIG_NOMONITORS */
2521 		break;
2522 	default:
2523 		return EINVAL;
2524 	}
2525 
2526 	task_lock(task);
2527 	if (task != current_task()) {
2528 		task->policy_ru_cpu_ext = policy;
2529 	} else {
2530 		task->policy_ru_cpu = policy;
2531 	}
2532 	error = task_set_cpuusage(task, percentage, interval, deadline, scope, cpumon_entitled);
2533 	task_unlock(task);
2534 	return error;
2535 }
2536 
2537 /* TODO: get rid of these */
2538 #define TASK_POLICY_CPU_RESOURCE_USAGE          0
2539 #define TASK_POLICY_WIREDMEM_RESOURCE_USAGE     1
2540 #define TASK_POLICY_VIRTUALMEM_RESOURCE_USAGE   2
2541 #define TASK_POLICY_DISK_RESOURCE_USAGE         3
2542 #define TASK_POLICY_NETWORK_RESOURCE_USAGE      4
2543 #define TASK_POLICY_POWER_RESOURCE_USAGE        5
2544 
2545 #define TASK_POLICY_RESOURCE_USAGE_COUNT        6
2546 
2547 int
proc_clear_task_ruse_cpu(task_t task,int cpumon_entitled)2548 proc_clear_task_ruse_cpu(task_t task, int cpumon_entitled)
2549 {
2550 	int error = 0;
2551 	int action;
2552 	void * bsdinfo = NULL;
2553 
2554 	task_lock(task);
2555 	if (task != current_task()) {
2556 		task->policy_ru_cpu_ext = TASK_POLICY_RESOURCE_ATTRIBUTE_DEFAULT;
2557 	} else {
2558 		task->policy_ru_cpu = TASK_POLICY_RESOURCE_ATTRIBUTE_DEFAULT;
2559 	}
2560 
2561 	error = task_clear_cpuusage_locked(task, cpumon_entitled);
2562 	if (error != 0) {
2563 		goto out;
2564 	}
2565 
2566 	action = task->applied_ru_cpu;
2567 	if (task->applied_ru_cpu_ext != TASK_POLICY_RESOURCE_ATTRIBUTE_NONE) {
2568 		/* reset action */
2569 		task->applied_ru_cpu_ext = TASK_POLICY_RESOURCE_ATTRIBUTE_NONE;
2570 	}
2571 	if (action != TASK_POLICY_RESOURCE_ATTRIBUTE_NONE) {
2572 		bsdinfo = task->bsd_info;
2573 		task_unlock(task);
2574 		proc_restore_resource_actions(bsdinfo, TASK_POLICY_CPU_RESOURCE_USAGE, action);
2575 		goto out1;
2576 	}
2577 
2578 out:
2579 	task_unlock(task);
2580 out1:
2581 	return error;
2582 }
2583 
2584 /* used to apply resource limit related actions */
2585 static int
task_apply_resource_actions(task_t task,int type)2586 task_apply_resource_actions(task_t task, int type)
2587 {
2588 	int action = TASK_POLICY_RESOURCE_ATTRIBUTE_NONE;
2589 	void * bsdinfo = NULL;
2590 
2591 	switch (type) {
2592 	case TASK_POLICY_CPU_RESOURCE_USAGE:
2593 		break;
2594 	case TASK_POLICY_WIREDMEM_RESOURCE_USAGE:
2595 	case TASK_POLICY_VIRTUALMEM_RESOURCE_USAGE:
2596 	case TASK_POLICY_DISK_RESOURCE_USAGE:
2597 	case TASK_POLICY_NETWORK_RESOURCE_USAGE:
2598 	case TASK_POLICY_POWER_RESOURCE_USAGE:
2599 		return 0;
2600 
2601 	default:
2602 		return 1;
2603 	}
2604 	;
2605 
2606 	/* only cpu actions for now */
2607 	task_lock(task);
2608 
2609 	if (task->applied_ru_cpu_ext == TASK_POLICY_RESOURCE_ATTRIBUTE_NONE) {
2610 		/* apply action */
2611 		task->applied_ru_cpu_ext = task->policy_ru_cpu_ext;
2612 		action = task->applied_ru_cpu_ext;
2613 	} else {
2614 		action = task->applied_ru_cpu_ext;
2615 	}
2616 
2617 	if (action != TASK_POLICY_RESOURCE_ATTRIBUTE_NONE) {
2618 		bsdinfo = task->bsd_info;
2619 		task_unlock(task);
2620 		proc_apply_resource_actions(bsdinfo, TASK_POLICY_CPU_RESOURCE_USAGE, action);
2621 	} else {
2622 		task_unlock(task);
2623 	}
2624 
2625 	return 0;
2626 }
2627 
2628 /*
2629  * XXX This API is somewhat broken; we support multiple simultaneous CPU limits, but the get/set API
2630  * only allows for one at a time. This means that if there is a per-thread limit active, the other
2631  * "scopes" will not be accessible via this API. We could change it to pass in the scope of interest
2632  * to the caller, and prefer that, but there's no need for that at the moment.
2633  */
2634 static int
task_get_cpuusage(task_t task,uint8_t * percentagep,uint64_t * intervalp,uint64_t * deadlinep,int * scope)2635 task_get_cpuusage(task_t task, uint8_t *percentagep, uint64_t *intervalp, uint64_t *deadlinep, int *scope)
2636 {
2637 	*percentagep = 0;
2638 	*intervalp = 0;
2639 	*deadlinep = 0;
2640 
2641 	if ((task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) != 0) {
2642 		*scope = TASK_RUSECPU_FLAGS_PERTHR_LIMIT;
2643 		*percentagep = task->rusage_cpu_perthr_percentage;
2644 		*intervalp = task->rusage_cpu_perthr_interval;
2645 	} else if ((task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PROC_LIMIT) != 0) {
2646 		*scope = TASK_RUSECPU_FLAGS_PROC_LIMIT;
2647 		*percentagep = task->rusage_cpu_percentage;
2648 		*intervalp = task->rusage_cpu_interval;
2649 	} else if ((task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_DEADLINE) != 0) {
2650 		*scope = TASK_RUSECPU_FLAGS_DEADLINE;
2651 		*deadlinep = task->rusage_cpu_deadline;
2652 	} else {
2653 		*scope = 0;
2654 	}
2655 
2656 	return 0;
2657 }
2658 
2659 /*
2660  * Suspend the CPU usage monitor for the task.  Return value indicates
2661  * if the mechanism was actually enabled.
2662  */
2663 int
task_suspend_cpumon(task_t task)2664 task_suspend_cpumon(task_t task)
2665 {
2666 	thread_t thread;
2667 
2668 	task_lock_assert_owned(task);
2669 
2670 	if ((task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) == 0) {
2671 		return KERN_INVALID_ARGUMENT;
2672 	}
2673 
2674 #if CONFIG_TELEMETRY
2675 	/*
2676 	 * Disable task-wide telemetry if it was ever enabled by the CPU usage
2677 	 * monitor's warning zone.
2678 	 */
2679 	telemetry_task_ctl_locked(task, TF_CPUMON_WARNING, 0);
2680 #endif
2681 
2682 	/*
2683 	 * Suspend monitoring for the task, and propagate that change to each thread.
2684 	 */
2685 	task->rusage_cpu_flags &= ~(TASK_RUSECPU_FLAGS_PERTHR_LIMIT | TASK_RUSECPU_FLAGS_FATAL_CPUMON);
2686 	queue_iterate(&task->threads, thread, thread_t, task_threads) {
2687 		act_set_astledger(thread);
2688 	}
2689 
2690 	return KERN_SUCCESS;
2691 }
2692 
2693 /*
2694  * Remove all traces of the CPU monitor.
2695  */
2696 int
task_disable_cpumon(task_t task)2697 task_disable_cpumon(task_t task)
2698 {
2699 	int kret;
2700 
2701 	task_lock_assert_owned(task);
2702 
2703 	kret = task_suspend_cpumon(task);
2704 	if (kret) {
2705 		return kret;
2706 	}
2707 
2708 	/* Once we clear these values, the monitor can't be resumed */
2709 	task->rusage_cpu_perthr_percentage = 0;
2710 	task->rusage_cpu_perthr_interval = 0;
2711 
2712 	return KERN_SUCCESS;
2713 }
2714 
2715 
2716 static int
task_enable_cpumon_locked(task_t task)2717 task_enable_cpumon_locked(task_t task)
2718 {
2719 	thread_t thread;
2720 	task_lock_assert_owned(task);
2721 
2722 	if (task->rusage_cpu_perthr_percentage == 0 ||
2723 	    task->rusage_cpu_perthr_interval == 0) {
2724 		return KERN_INVALID_ARGUMENT;
2725 	}
2726 
2727 	task->rusage_cpu_flags |= TASK_RUSECPU_FLAGS_PERTHR_LIMIT;
2728 	queue_iterate(&task->threads, thread, thread_t, task_threads) {
2729 		act_set_astledger(thread);
2730 	}
2731 
2732 	return KERN_SUCCESS;
2733 }
2734 
2735 int
task_resume_cpumon(task_t task)2736 task_resume_cpumon(task_t task)
2737 {
2738 	kern_return_t kret;
2739 
2740 	if (!task) {
2741 		return EINVAL;
2742 	}
2743 
2744 	task_lock(task);
2745 	kret = task_enable_cpumon_locked(task);
2746 	task_unlock(task);
2747 
2748 	return kret;
2749 }
2750 
2751 
2752 /* duplicate values from bsd/sys/process_policy.h */
2753 #define PROC_POLICY_CPUMON_DISABLE      0xFF
2754 #define PROC_POLICY_CPUMON_DEFAULTS     0xFE
2755 
2756 static int
task_set_cpuusage(task_t task,uint8_t percentage,uint64_t interval,uint64_t deadline,int scope,int cpumon_entitled)2757 task_set_cpuusage(task_t task, uint8_t percentage, uint64_t interval, uint64_t deadline, int scope, int cpumon_entitled)
2758 {
2759 	uint64_t abstime = 0;
2760 	uint64_t limittime = 0;
2761 
2762 	lck_mtx_assert(&task->lock, LCK_MTX_ASSERT_OWNED);
2763 
2764 	/* By default, refill once per second */
2765 	if (interval == 0) {
2766 		interval = NSEC_PER_SEC;
2767 	}
2768 
2769 	if (percentage != 0) {
2770 		if (scope == TASK_RUSECPU_FLAGS_PERTHR_LIMIT) {
2771 			boolean_t warn = FALSE;
2772 
2773 			/*
2774 			 * A per-thread CPU limit on a task generates an exception
2775 			 * (LEDGER_ACTION_EXCEPTION) if any one thread in the task
2776 			 * exceeds the limit.
2777 			 */
2778 
2779 			if (percentage == PROC_POLICY_CPUMON_DISABLE) {
2780 				if (cpumon_entitled) {
2781 					/* 25095698 - task_disable_cpumon() should be reliable */
2782 					task_disable_cpumon(task);
2783 					return 0;
2784 				}
2785 
2786 				/*
2787 				 * This task wishes to disable the CPU usage monitor, but it's
2788 				 * missing the required entitlement:
2789 				 *     com.apple.private.kernel.override-cpumon
2790 				 *
2791 				 * Instead, treat this as a request to reset its params
2792 				 * back to the defaults.
2793 				 */
2794 				warn = TRUE;
2795 				percentage = PROC_POLICY_CPUMON_DEFAULTS;
2796 			}
2797 
2798 			if (percentage == PROC_POLICY_CPUMON_DEFAULTS) {
2799 				percentage = proc_max_cpumon_percentage;
2800 				interval   = proc_max_cpumon_interval;
2801 			}
2802 
2803 			if (percentage > 100) {
2804 				percentage = 100;
2805 			}
2806 
2807 			/*
2808 			 * Passing in an interval of -1 means either:
2809 			 * - Leave the interval as-is, if there's already a per-thread
2810 			 *   limit configured
2811 			 * - Use the system default.
2812 			 */
2813 			if (interval == -1ULL) {
2814 				if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) {
2815 					interval = task->rusage_cpu_perthr_interval;
2816 				} else {
2817 					interval = proc_max_cpumon_interval;
2818 				}
2819 			}
2820 
2821 			/*
2822 			 * Enforce global caps on CPU usage monitor here if the process is not
2823 			 * entitled to escape the global caps.
2824 			 */
2825 			if ((percentage > proc_max_cpumon_percentage) && (cpumon_entitled == 0)) {
2826 				warn = TRUE;
2827 				percentage = proc_max_cpumon_percentage;
2828 			}
2829 
2830 			if ((interval > proc_max_cpumon_interval) && (cpumon_entitled == 0)) {
2831 				warn = TRUE;
2832 				interval = proc_max_cpumon_interval;
2833 			}
2834 
2835 			if (warn) {
2836 				int       pid = 0;
2837 				const char *procname = "unknown";
2838 
2839 #ifdef MACH_BSD
2840 				pid = proc_selfpid();
2841 				if (current_task()->bsd_info != NULL) {
2842 					procname = proc_name_address(current_task()->bsd_info);
2843 				}
2844 #endif
2845 
2846 				printf("process %s[%d] denied attempt to escape CPU monitor"
2847 				    " (missing required entitlement).\n", procname, pid);
2848 			}
2849 
2850 			/* configure the limit values */
2851 			task->rusage_cpu_perthr_percentage = percentage;
2852 			task->rusage_cpu_perthr_interval = interval;
2853 
2854 			/* and enable the CPU monitor */
2855 			(void)task_enable_cpumon_locked(task);
2856 		} else if (scope == TASK_RUSECPU_FLAGS_PROC_LIMIT) {
2857 			/*
2858 			 * Currently, a proc-wide CPU limit always blocks if the limit is
2859 			 * exceeded (LEDGER_ACTION_BLOCK).
2860 			 */
2861 			task->rusage_cpu_flags |= TASK_RUSECPU_FLAGS_PROC_LIMIT;
2862 			task->rusage_cpu_percentage = percentage;
2863 			task->rusage_cpu_interval = interval;
2864 
2865 			limittime = (interval * percentage) / 100;
2866 			nanoseconds_to_absolutetime(limittime, &abstime);
2867 
2868 			ledger_set_limit(task->ledger, task_ledgers.cpu_time, abstime, 0);
2869 			ledger_set_period(task->ledger, task_ledgers.cpu_time, interval);
2870 			ledger_set_action(task->ledger, task_ledgers.cpu_time, LEDGER_ACTION_BLOCK);
2871 		}
2872 	}
2873 
2874 	if (deadline != 0) {
2875 		assert(scope == TASK_RUSECPU_FLAGS_DEADLINE);
2876 
2877 		/* if already in use, cancel and wait for it to cleanout */
2878 		if (task->rusage_cpu_callt != NULL) {
2879 			task_unlock(task);
2880 			thread_call_cancel_wait(task->rusage_cpu_callt);
2881 			task_lock(task);
2882 		}
2883 		if (task->rusage_cpu_callt == NULL) {
2884 			task->rusage_cpu_callt = thread_call_allocate_with_priority(task_action_cpuusage, (thread_call_param_t)task, THREAD_CALL_PRIORITY_KERNEL);
2885 		}
2886 		/* setup callout */
2887 		if (task->rusage_cpu_callt != 0) {
2888 			uint64_t save_abstime = 0;
2889 
2890 			task->rusage_cpu_flags |= TASK_RUSECPU_FLAGS_DEADLINE;
2891 			task->rusage_cpu_deadline = deadline;
2892 
2893 			nanoseconds_to_absolutetime(deadline, &abstime);
2894 			save_abstime = abstime;
2895 			clock_absolutetime_interval_to_deadline(save_abstime, &abstime);
2896 			thread_call_enter_delayed(task->rusage_cpu_callt, abstime);
2897 		}
2898 	}
2899 
2900 	return 0;
2901 }
2902 
2903 int
task_clear_cpuusage(task_t task,int cpumon_entitled)2904 task_clear_cpuusage(task_t task, int cpumon_entitled)
2905 {
2906 	int retval = 0;
2907 
2908 	task_lock(task);
2909 	retval = task_clear_cpuusage_locked(task, cpumon_entitled);
2910 	task_unlock(task);
2911 
2912 	return retval;
2913 }
2914 
2915 static int
task_clear_cpuusage_locked(task_t task,int cpumon_entitled)2916 task_clear_cpuusage_locked(task_t task, int cpumon_entitled)
2917 {
2918 	thread_call_t savecallt;
2919 
2920 	/* cancel percentage handling if set */
2921 	if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PROC_LIMIT) {
2922 		task->rusage_cpu_flags &= ~TASK_RUSECPU_FLAGS_PROC_LIMIT;
2923 		ledger_set_limit(task->ledger, task_ledgers.cpu_time, LEDGER_LIMIT_INFINITY, 0);
2924 		task->rusage_cpu_percentage = 0;
2925 		task->rusage_cpu_interval = 0;
2926 	}
2927 
2928 	/*
2929 	 * Disable the CPU usage monitor.
2930 	 */
2931 	if (cpumon_entitled) {
2932 		task_disable_cpumon(task);
2933 	}
2934 
2935 	/* cancel deadline handling if set */
2936 	if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_DEADLINE) {
2937 		task->rusage_cpu_flags &= ~TASK_RUSECPU_FLAGS_DEADLINE;
2938 		if (task->rusage_cpu_callt != 0) {
2939 			savecallt = task->rusage_cpu_callt;
2940 			task->rusage_cpu_callt = NULL;
2941 			task->rusage_cpu_deadline = 0;
2942 			task_unlock(task);
2943 			thread_call_cancel_wait(savecallt);
2944 			thread_call_free(savecallt);
2945 			task_lock(task);
2946 		}
2947 	}
2948 	return 0;
2949 }
2950 
2951 /* called by ledger unit to enforce action due to resource usage criteria being met */
2952 static void
task_action_cpuusage(thread_call_param_t param0,__unused thread_call_param_t param1)2953 task_action_cpuusage(thread_call_param_t param0, __unused thread_call_param_t param1)
2954 {
2955 	task_t task = (task_t)param0;
2956 	(void)task_apply_resource_actions(task, TASK_POLICY_CPU_RESOURCE_USAGE);
2957 	return;
2958 }
2959 
2960 
2961 /*
2962  * Routines for taskwatch and pidbind
2963  */
2964 
2965 #if CONFIG_TASKWATCH
2966 
2967 LCK_MTX_DECLARE_ATTR(task_watch_mtx, &task_lck_grp, &task_lck_attr);
2968 
2969 static void
task_watch_lock(void)2970 task_watch_lock(void)
2971 {
2972 	lck_mtx_lock(&task_watch_mtx);
2973 }
2974 
2975 static void
task_watch_unlock(void)2976 task_watch_unlock(void)
2977 {
2978 	lck_mtx_unlock(&task_watch_mtx);
2979 }
2980 
2981 static void
add_taskwatch_locked(task_t task,task_watch_t * twp)2982 add_taskwatch_locked(task_t task, task_watch_t * twp)
2983 {
2984 	queue_enter(&task->task_watchers, twp, task_watch_t *, tw_links);
2985 	task->num_taskwatchers++;
2986 }
2987 
2988 static void
remove_taskwatch_locked(task_t task,task_watch_t * twp)2989 remove_taskwatch_locked(task_t task, task_watch_t * twp)
2990 {
2991 	queue_remove(&task->task_watchers, twp, task_watch_t *, tw_links);
2992 	task->num_taskwatchers--;
2993 }
2994 
2995 
2996 int
proc_lf_pidbind(task_t curtask,uint64_t tid,task_t target_task,int bind)2997 proc_lf_pidbind(task_t curtask, uint64_t tid, task_t target_task, int bind)
2998 {
2999 	thread_t target_thread = NULL;
3000 	int ret = 0, setbg = 0;
3001 	task_watch_t *twp = NULL;
3002 	task_t task = TASK_NULL;
3003 
3004 	target_thread = task_findtid(curtask, tid);
3005 	if (target_thread == NULL) {
3006 		return ESRCH;
3007 	}
3008 	/* holds thread reference */
3009 
3010 	if (bind != 0) {
3011 		/* task is still active ? */
3012 		task_lock(target_task);
3013 		if (target_task->active == 0) {
3014 			task_unlock(target_task);
3015 			ret = ESRCH;
3016 			goto out;
3017 		}
3018 		task_unlock(target_task);
3019 
3020 		twp = kalloc_type(task_watch_t, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3021 
3022 		task_watch_lock();
3023 
3024 		if (target_thread->taskwatch != NULL) {
3025 			/* already bound to another task */
3026 			task_watch_unlock();
3027 
3028 			kfree_type(task_watch_t, twp);
3029 			ret = EBUSY;
3030 			goto out;
3031 		}
3032 
3033 		task_reference(target_task);
3034 
3035 		setbg = proc_get_effective_task_policy(target_task, TASK_POLICY_WATCHERS_BG);
3036 
3037 		twp->tw_task = target_task;             /* holds the task reference */
3038 		twp->tw_thread = target_thread;         /* holds the thread reference */
3039 		twp->tw_state = setbg;
3040 		twp->tw_importance = target_thread->importance;
3041 
3042 		add_taskwatch_locked(target_task, twp);
3043 
3044 		target_thread->taskwatch = twp;
3045 
3046 		task_watch_unlock();
3047 
3048 		if (setbg) {
3049 			set_thread_appbg(target_thread, setbg, INT_MIN);
3050 		}
3051 
3052 		/* retain the thread reference as it is in twp */
3053 		target_thread = NULL;
3054 	} else {
3055 		/* unbind */
3056 		task_watch_lock();
3057 		if ((twp = target_thread->taskwatch) != NULL) {
3058 			task = twp->tw_task;
3059 			target_thread->taskwatch = NULL;
3060 			remove_taskwatch_locked(task, twp);
3061 
3062 			task_watch_unlock();
3063 
3064 			task_deallocate(task);                  /* drop task ref in twp */
3065 			set_thread_appbg(target_thread, 0, twp->tw_importance);
3066 			thread_deallocate(target_thread);       /* drop thread ref in twp */
3067 			kfree_type(task_watch_t, twp);
3068 		} else {
3069 			task_watch_unlock();
3070 			ret = 0;                /* return success if it not alredy bound */
3071 			goto out;
3072 		}
3073 	}
3074 out:
3075 	thread_deallocate(target_thread);       /* drop thread ref acquired in this routine */
3076 	return ret;
3077 }
3078 
3079 static void
set_thread_appbg(thread_t thread,int setbg,__unused int importance)3080 set_thread_appbg(thread_t thread, int setbg, __unused int importance)
3081 {
3082 	int enable = (setbg ? TASK_POLICY_ENABLE : TASK_POLICY_DISABLE);
3083 
3084 	proc_set_thread_policy(thread, TASK_POLICY_ATTRIBUTE, TASK_POLICY_PIDBIND_BG, enable);
3085 }
3086 
3087 static void
apply_appstate_watchers(task_t task)3088 apply_appstate_watchers(task_t task)
3089 {
3090 	int numwatchers = 0, i, j, setbg;
3091 	thread_watchlist_t * threadlist;
3092 	task_watch_t * twp;
3093 
3094 retry:
3095 	/* if no watchers on the list return */
3096 	if ((numwatchers = task->num_taskwatchers) == 0) {
3097 		return;
3098 	}
3099 
3100 	threadlist = kalloc_type(thread_watchlist_t, numwatchers, Z_WAITOK | Z_ZERO);
3101 	if (threadlist == NULL) {
3102 		return;
3103 	}
3104 
3105 	task_watch_lock();
3106 	/*serialize application of app state changes */
3107 
3108 	if (task->watchapplying != 0) {
3109 		lck_mtx_sleep(&task_watch_mtx, LCK_SLEEP_DEFAULT, &task->watchapplying, THREAD_UNINT);
3110 		task_watch_unlock();
3111 		kfree_type(thread_watchlist_t, numwatchers, threadlist);
3112 		goto retry;
3113 	}
3114 
3115 	if (numwatchers != task->num_taskwatchers) {
3116 		task_watch_unlock();
3117 		kfree_type(thread_watchlist_t, numwatchers, threadlist);
3118 		goto retry;
3119 	}
3120 
3121 	setbg = proc_get_effective_task_policy(task, TASK_POLICY_WATCHERS_BG);
3122 
3123 	task->watchapplying = 1;
3124 	i = 0;
3125 	queue_iterate(&task->task_watchers, twp, task_watch_t *, tw_links) {
3126 		threadlist[i].thread = twp->tw_thread;
3127 		thread_reference(threadlist[i].thread);
3128 		if (setbg != 0) {
3129 			twp->tw_importance = twp->tw_thread->importance;
3130 			threadlist[i].importance = INT_MIN;
3131 		} else {
3132 			threadlist[i].importance = twp->tw_importance;
3133 		}
3134 		i++;
3135 		if (i > numwatchers) {
3136 			break;
3137 		}
3138 	}
3139 
3140 	task_watch_unlock();
3141 
3142 	for (j = 0; j < i; j++) {
3143 		set_thread_appbg(threadlist[j].thread, setbg, threadlist[j].importance);
3144 		thread_deallocate(threadlist[j].thread);
3145 	}
3146 	kfree_type(thread_watchlist_t, numwatchers, threadlist);
3147 
3148 
3149 	task_watch_lock();
3150 	task->watchapplying = 0;
3151 	thread_wakeup_one(&task->watchapplying);
3152 	task_watch_unlock();
3153 }
3154 
3155 void
thead_remove_taskwatch(thread_t thread)3156 thead_remove_taskwatch(thread_t thread)
3157 {
3158 	task_watch_t * twp;
3159 	int importance = 0;
3160 
3161 	task_watch_lock();
3162 	if ((twp = thread->taskwatch) != NULL) {
3163 		thread->taskwatch = NULL;
3164 		remove_taskwatch_locked(twp->tw_task, twp);
3165 	}
3166 	task_watch_unlock();
3167 	if (twp != NULL) {
3168 		thread_deallocate(twp->tw_thread);
3169 		task_deallocate(twp->tw_task);
3170 		importance = twp->tw_importance;
3171 		kfree_type(task_watch_t, twp);
3172 		/* remove the thread and networkbg */
3173 		set_thread_appbg(thread, 0, importance);
3174 	}
3175 }
3176 
3177 void
task_removewatchers(task_t task)3178 task_removewatchers(task_t task)
3179 {
3180 	queue_head_t queue;
3181 	task_watch_t *twp;
3182 
3183 	task_watch_lock();
3184 	queue_new_head(&task->task_watchers, &queue, task_watch_t *, tw_links);
3185 	queue_init(&task->task_watchers);
3186 
3187 	queue_iterate(&queue, twp, task_watch_t *, tw_links) {
3188 		/*
3189 		 * Since the linkage is removed and thead state cleanup is already set up,
3190 		 * remove the refernce from the thread.
3191 		 */
3192 		twp->tw_thread->taskwatch = NULL;       /* removed linkage, clear thread holding ref */
3193 	}
3194 
3195 	task->num_taskwatchers = 0;
3196 	task_watch_unlock();
3197 
3198 	while (!queue_empty(&queue)) {
3199 		queue_remove_first(&queue, twp, task_watch_t *, tw_links);
3200 		/* remove thread and network bg */
3201 		set_thread_appbg(twp->tw_thread, 0, twp->tw_importance);
3202 		thread_deallocate(twp->tw_thread);
3203 		task_deallocate(twp->tw_task);
3204 		kfree_type(task_watch_t, twp);
3205 	}
3206 }
3207 #endif /* CONFIG_TASKWATCH */
3208 
3209 /*
3210  * Routines for importance donation/inheritance/boosting
3211  */
3212 
3213 static void
task_importance_update_live_donor(task_t target_task)3214 task_importance_update_live_donor(task_t target_task)
3215 {
3216 #if IMPORTANCE_INHERITANCE
3217 
3218 	ipc_importance_task_t task_imp;
3219 
3220 	task_imp = ipc_importance_for_task(target_task, FALSE);
3221 	if (IIT_NULL != task_imp) {
3222 		ipc_importance_task_update_live_donor(task_imp);
3223 		ipc_importance_task_release(task_imp);
3224 	}
3225 #endif /* IMPORTANCE_INHERITANCE */
3226 }
3227 
3228 void
task_importance_mark_donor(task_t task,boolean_t donating)3229 task_importance_mark_donor(task_t task, boolean_t donating)
3230 {
3231 #if IMPORTANCE_INHERITANCE
3232 	ipc_importance_task_t task_imp;
3233 
3234 	task_imp = ipc_importance_for_task(task, FALSE);
3235 	if (IIT_NULL != task_imp) {
3236 		ipc_importance_task_mark_donor(task_imp, donating);
3237 		ipc_importance_task_release(task_imp);
3238 	}
3239 #endif /* IMPORTANCE_INHERITANCE */
3240 }
3241 
3242 void
task_importance_mark_live_donor(task_t task,boolean_t live_donating)3243 task_importance_mark_live_donor(task_t task, boolean_t live_donating)
3244 {
3245 #if IMPORTANCE_INHERITANCE
3246 	ipc_importance_task_t task_imp;
3247 
3248 	task_imp = ipc_importance_for_task(task, FALSE);
3249 	if (IIT_NULL != task_imp) {
3250 		ipc_importance_task_mark_live_donor(task_imp, live_donating);
3251 		ipc_importance_task_release(task_imp);
3252 	}
3253 #endif /* IMPORTANCE_INHERITANCE */
3254 }
3255 
3256 void
task_importance_mark_receiver(task_t task,boolean_t receiving)3257 task_importance_mark_receiver(task_t task, boolean_t receiving)
3258 {
3259 #if IMPORTANCE_INHERITANCE
3260 	ipc_importance_task_t task_imp;
3261 
3262 	task_imp = ipc_importance_for_task(task, FALSE);
3263 	if (IIT_NULL != task_imp) {
3264 		ipc_importance_task_mark_receiver(task_imp, receiving);
3265 		ipc_importance_task_release(task_imp);
3266 	}
3267 #endif /* IMPORTANCE_INHERITANCE */
3268 }
3269 
3270 void
task_importance_mark_denap_receiver(task_t task,boolean_t denap)3271 task_importance_mark_denap_receiver(task_t task, boolean_t denap)
3272 {
3273 #if IMPORTANCE_INHERITANCE
3274 	ipc_importance_task_t task_imp;
3275 
3276 	task_imp = ipc_importance_for_task(task, FALSE);
3277 	if (IIT_NULL != task_imp) {
3278 		ipc_importance_task_mark_denap_receiver(task_imp, denap);
3279 		ipc_importance_task_release(task_imp);
3280 	}
3281 #endif /* IMPORTANCE_INHERITANCE */
3282 }
3283 
3284 void
task_importance_reset(__imp_only task_t task)3285 task_importance_reset(__imp_only task_t task)
3286 {
3287 #if IMPORTANCE_INHERITANCE
3288 	ipc_importance_task_t task_imp;
3289 
3290 	/* TODO: Lower importance downstream before disconnect */
3291 	task_imp = task->task_imp_base;
3292 	ipc_importance_reset(task_imp, FALSE);
3293 	task_importance_update_live_donor(task);
3294 #endif /* IMPORTANCE_INHERITANCE */
3295 }
3296 
3297 void
task_importance_init_from_parent(__imp_only task_t new_task,__imp_only task_t parent_task)3298 task_importance_init_from_parent(__imp_only task_t new_task, __imp_only task_t parent_task)
3299 {
3300 #if IMPORTANCE_INHERITANCE
3301 	ipc_importance_task_t new_task_imp = IIT_NULL;
3302 
3303 	new_task->task_imp_base = NULL;
3304 	if (!parent_task) {
3305 		return;
3306 	}
3307 
3308 	if (task_is_marked_importance_donor(parent_task)) {
3309 		new_task_imp = ipc_importance_for_task(new_task, FALSE);
3310 		assert(IIT_NULL != new_task_imp);
3311 		ipc_importance_task_mark_donor(new_task_imp, TRUE);
3312 	}
3313 	if (task_is_marked_live_importance_donor(parent_task)) {
3314 		if (IIT_NULL == new_task_imp) {
3315 			new_task_imp = ipc_importance_for_task(new_task, FALSE);
3316 		}
3317 		assert(IIT_NULL != new_task_imp);
3318 		ipc_importance_task_mark_live_donor(new_task_imp, TRUE);
3319 	}
3320 	/* Do not inherit 'receiver' on fork, vfexec or true spawn */
3321 	if (task_is_exec_copy(new_task) &&
3322 	    task_is_marked_importance_receiver(parent_task)) {
3323 		if (IIT_NULL == new_task_imp) {
3324 			new_task_imp = ipc_importance_for_task(new_task, FALSE);
3325 		}
3326 		assert(IIT_NULL != new_task_imp);
3327 		ipc_importance_task_mark_receiver(new_task_imp, TRUE);
3328 	}
3329 	if (task_is_marked_importance_denap_receiver(parent_task)) {
3330 		if (IIT_NULL == new_task_imp) {
3331 			new_task_imp = ipc_importance_for_task(new_task, FALSE);
3332 		}
3333 		assert(IIT_NULL != new_task_imp);
3334 		ipc_importance_task_mark_denap_receiver(new_task_imp, TRUE);
3335 	}
3336 	if (IIT_NULL != new_task_imp) {
3337 		assert(new_task->task_imp_base == new_task_imp);
3338 		ipc_importance_task_release(new_task_imp);
3339 	}
3340 #endif /* IMPORTANCE_INHERITANCE */
3341 }
3342 
3343 #if IMPORTANCE_INHERITANCE
3344 /*
3345  * Sets the task boost bit to the provided value.  Does NOT run the update function.
3346  *
3347  * Task lock must be held.
3348  */
3349 static void
task_set_boost_locked(task_t task,boolean_t boost_active)3350 task_set_boost_locked(task_t task, boolean_t boost_active)
3351 {
3352 #if IMPORTANCE_TRACE
3353 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, (IMPORTANCE_CODE(IMP_BOOST, (boost_active ? IMP_BOOSTED : IMP_UNBOOSTED)) | DBG_FUNC_START),
3354 	    proc_selfpid(), task_pid(task), trequested_0(task), trequested_1(task), 0);
3355 #endif /* IMPORTANCE_TRACE */
3356 
3357 	task->requested_policy.trp_boosted = boost_active;
3358 
3359 #if IMPORTANCE_TRACE
3360 	if (boost_active == TRUE) {
3361 		DTRACE_BOOST2(boost, task_t, task, int, task_pid(task));
3362 	} else {
3363 		DTRACE_BOOST2(unboost, task_t, task, int, task_pid(task));
3364 	}
3365 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, (IMPORTANCE_CODE(IMP_BOOST, (boost_active ? IMP_BOOSTED : IMP_UNBOOSTED)) | DBG_FUNC_END),
3366 	    proc_selfpid(), task_pid(task),
3367 	    trequested_0(task), trequested_1(task), 0);
3368 #endif /* IMPORTANCE_TRACE */
3369 }
3370 
3371 /*
3372  * Sets the task boost bit to the provided value and applies the update.
3373  *
3374  * Task lock must be held.  Must call update complete after unlocking the task.
3375  */
3376 void
task_update_boost_locked(task_t task,boolean_t boost_active,task_pend_token_t pend_token)3377 task_update_boost_locked(task_t task, boolean_t boost_active, task_pend_token_t pend_token)
3378 {
3379 	task_set_boost_locked(task, boost_active);
3380 
3381 	task_policy_update_locked(task, pend_token);
3382 }
3383 
3384 /*
3385  * Check if this task should donate importance.
3386  *
3387  * May be called without taking the task lock. In that case, donor status can change
3388  * so you must check only once for each donation event.
3389  */
3390 boolean_t
task_is_importance_donor(task_t task)3391 task_is_importance_donor(task_t task)
3392 {
3393 	if (task->task_imp_base == IIT_NULL) {
3394 		return FALSE;
3395 	}
3396 	return ipc_importance_task_is_donor(task->task_imp_base);
3397 }
3398 
3399 /*
3400  * Query the status of the task's donor mark.
3401  */
3402 boolean_t
task_is_marked_importance_donor(task_t task)3403 task_is_marked_importance_donor(task_t task)
3404 {
3405 	if (task->task_imp_base == IIT_NULL) {
3406 		return FALSE;
3407 	}
3408 	return ipc_importance_task_is_marked_donor(task->task_imp_base);
3409 }
3410 
3411 /*
3412  * Query the status of the task's live donor and donor mark.
3413  */
3414 boolean_t
task_is_marked_live_importance_donor(task_t task)3415 task_is_marked_live_importance_donor(task_t task)
3416 {
3417 	if (task->task_imp_base == IIT_NULL) {
3418 		return FALSE;
3419 	}
3420 	return ipc_importance_task_is_marked_live_donor(task->task_imp_base);
3421 }
3422 
3423 
3424 /*
3425  * This routine may be called without holding task lock
3426  * since the value of imp_receiver can never be unset.
3427  */
3428 boolean_t
task_is_importance_receiver(task_t task)3429 task_is_importance_receiver(task_t task)
3430 {
3431 	if (task->task_imp_base == IIT_NULL) {
3432 		return FALSE;
3433 	}
3434 	return ipc_importance_task_is_marked_receiver(task->task_imp_base);
3435 }
3436 
3437 /*
3438  * Query the task's receiver mark.
3439  */
3440 boolean_t
task_is_marked_importance_receiver(task_t task)3441 task_is_marked_importance_receiver(task_t task)
3442 {
3443 	if (task->task_imp_base == IIT_NULL) {
3444 		return FALSE;
3445 	}
3446 	return ipc_importance_task_is_marked_receiver(task->task_imp_base);
3447 }
3448 
3449 /*
3450  * This routine may be called without holding task lock
3451  * since the value of de-nap receiver can never be unset.
3452  */
3453 boolean_t
task_is_importance_denap_receiver(task_t task)3454 task_is_importance_denap_receiver(task_t task)
3455 {
3456 	if (task->task_imp_base == IIT_NULL) {
3457 		return FALSE;
3458 	}
3459 	return ipc_importance_task_is_denap_receiver(task->task_imp_base);
3460 }
3461 
3462 /*
3463  * Query the task's de-nap receiver mark.
3464  */
3465 boolean_t
task_is_marked_importance_denap_receiver(task_t task)3466 task_is_marked_importance_denap_receiver(task_t task)
3467 {
3468 	if (task->task_imp_base == IIT_NULL) {
3469 		return FALSE;
3470 	}
3471 	return ipc_importance_task_is_marked_denap_receiver(task->task_imp_base);
3472 }
3473 
3474 /*
3475  * This routine may be called without holding task lock
3476  * since the value of imp_receiver can never be unset.
3477  */
3478 boolean_t
task_is_importance_receiver_type(task_t task)3479 task_is_importance_receiver_type(task_t task)
3480 {
3481 	if (task->task_imp_base == IIT_NULL) {
3482 		return FALSE;
3483 	}
3484 	return task_is_importance_receiver(task) ||
3485 	       task_is_importance_denap_receiver(task);
3486 }
3487 
3488 /*
3489  * External importance assertions are managed by the process in userspace
3490  * Internal importance assertions are the responsibility of the kernel
3491  * Assertions are changed from internal to external via task_importance_externalize_assertion
3492  */
3493 
3494 int
task_importance_hold_internal_assertion(task_t target_task,uint32_t count)3495 task_importance_hold_internal_assertion(task_t target_task, uint32_t count)
3496 {
3497 	ipc_importance_task_t task_imp;
3498 	kern_return_t ret;
3499 
3500 	/* may be first time, so allow for possible importance setup */
3501 	task_imp = ipc_importance_for_task(target_task, FALSE);
3502 	if (IIT_NULL == task_imp) {
3503 		return EOVERFLOW;
3504 	}
3505 	ret = ipc_importance_task_hold_internal_assertion(task_imp, count);
3506 	ipc_importance_task_release(task_imp);
3507 
3508 	return (KERN_SUCCESS != ret) ? ENOTSUP : 0;
3509 }
3510 
3511 int
task_importance_hold_file_lock_assertion(task_t target_task,uint32_t count)3512 task_importance_hold_file_lock_assertion(task_t target_task, uint32_t count)
3513 {
3514 	ipc_importance_task_t task_imp;
3515 	kern_return_t ret;
3516 
3517 	/* may be first time, so allow for possible importance setup */
3518 	task_imp = ipc_importance_for_task(target_task, FALSE);
3519 	if (IIT_NULL == task_imp) {
3520 		return EOVERFLOW;
3521 	}
3522 	ret = ipc_importance_task_hold_file_lock_assertion(task_imp, count);
3523 	ipc_importance_task_release(task_imp);
3524 
3525 	return (KERN_SUCCESS != ret) ? ENOTSUP : 0;
3526 }
3527 
3528 int
task_importance_hold_legacy_external_assertion(task_t target_task,uint32_t count)3529 task_importance_hold_legacy_external_assertion(task_t target_task, uint32_t count)
3530 {
3531 	ipc_importance_task_t task_imp;
3532 	kern_return_t ret;
3533 
3534 	/* must already have set up an importance */
3535 	task_imp = target_task->task_imp_base;
3536 	if (IIT_NULL == task_imp) {
3537 		return EOVERFLOW;
3538 	}
3539 	ret = ipc_importance_task_hold_legacy_external_assertion(task_imp, count);
3540 	return (KERN_SUCCESS != ret) ? ENOTSUP : 0;
3541 }
3542 
3543 int
task_importance_drop_file_lock_assertion(task_t target_task,uint32_t count)3544 task_importance_drop_file_lock_assertion(task_t target_task, uint32_t count)
3545 {
3546 	ipc_importance_task_t task_imp;
3547 	kern_return_t ret;
3548 
3549 	/* must already have set up an importance */
3550 	task_imp = target_task->task_imp_base;
3551 	if (IIT_NULL == task_imp) {
3552 		return EOVERFLOW;
3553 	}
3554 	ret = ipc_importance_task_drop_file_lock_assertion(target_task->task_imp_base, count);
3555 	return (KERN_SUCCESS != ret) ? EOVERFLOW : 0;
3556 }
3557 
3558 int
task_importance_drop_legacy_external_assertion(task_t target_task,uint32_t count)3559 task_importance_drop_legacy_external_assertion(task_t target_task, uint32_t count)
3560 {
3561 	ipc_importance_task_t task_imp;
3562 	kern_return_t ret;
3563 
3564 	/* must already have set up an importance */
3565 	task_imp = target_task->task_imp_base;
3566 	if (IIT_NULL == task_imp) {
3567 		return EOVERFLOW;
3568 	}
3569 	ret = ipc_importance_task_drop_legacy_external_assertion(task_imp, count);
3570 	return (KERN_SUCCESS != ret) ? EOVERFLOW : 0;
3571 }
3572 
3573 static void
task_add_importance_watchport(task_t task,mach_port_t port,int * boostp)3574 task_add_importance_watchport(task_t task, mach_port_t port, int *boostp)
3575 {
3576 	int boost = 0;
3577 
3578 	__imptrace_only int released_pid = 0;
3579 	__imptrace_only int pid = task_pid(task);
3580 
3581 	ipc_importance_task_t release_imp_task = IIT_NULL;
3582 
3583 	if (IP_VALID(port) != 0) {
3584 		ipc_importance_task_t new_imp_task = ipc_importance_for_task(task, FALSE);
3585 
3586 		ip_mq_lock(port);
3587 
3588 		/*
3589 		 * The port must have been marked tempowner already.
3590 		 * This also filters out ports whose receive rights
3591 		 * are already enqueued in a message, as you can't
3592 		 * change the right's destination once it's already
3593 		 * on its way.
3594 		 */
3595 		if (port->ip_tempowner != 0) {
3596 			assert(port->ip_impdonation != 0);
3597 
3598 			boost = port->ip_impcount;
3599 			if (IIT_NULL != ip_get_imp_task(port)) {
3600 				/*
3601 				 * if this port is already bound to a task,
3602 				 * release the task reference and drop any
3603 				 * watchport-forwarded boosts
3604 				 */
3605 				release_imp_task = ip_get_imp_task(port);
3606 				port->ip_imp_task = IIT_NULL;
3607 			}
3608 
3609 			/* mark the port is watching another task (reference held in port->ip_imp_task) */
3610 			if (ipc_importance_task_is_marked_receiver(new_imp_task)) {
3611 				port->ip_imp_task = new_imp_task;
3612 				new_imp_task = IIT_NULL;
3613 			}
3614 		}
3615 		ip_mq_unlock(port);
3616 
3617 		if (IIT_NULL != new_imp_task) {
3618 			ipc_importance_task_release(new_imp_task);
3619 		}
3620 
3621 		if (IIT_NULL != release_imp_task) {
3622 			if (boost > 0) {
3623 				ipc_importance_task_drop_internal_assertion(release_imp_task, boost);
3624 			}
3625 
3626 			// released_pid = task_pid(release_imp_task); /* TODO: Need ref-safe way to get pid */
3627 			ipc_importance_task_release(release_imp_task);
3628 		}
3629 #if IMPORTANCE_TRACE
3630 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, (IMPORTANCE_CODE(IMP_WATCHPORT, 0)) | DBG_FUNC_NONE,
3631 		    proc_selfpid(), pid, boost, released_pid, 0);
3632 #endif /* IMPORTANCE_TRACE */
3633 	}
3634 
3635 	*boostp = boost;
3636 	return;
3637 }
3638 
3639 #endif /* IMPORTANCE_INHERITANCE */
3640 
3641 /*
3642  * Routines for VM to query task importance
3643  */
3644 
3645 
3646 /*
3647  * Order to be considered while estimating importance
3648  * for low memory notification and purging purgeable memory.
3649  */
3650 #define TASK_IMPORTANCE_FOREGROUND     4
3651 #define TASK_IMPORTANCE_NOTDARWINBG    1
3652 
3653 
3654 /*
3655  * (Un)Mark the task as a privileged listener for memory notifications.
3656  * if marked, this task will be among the first to be notified amongst
3657  * the bulk of all other tasks when the system enters a pressure level
3658  * of interest to this task.
3659  */
3660 int
task_low_mem_privileged_listener(task_t task,boolean_t new_value,boolean_t * old_value)3661 task_low_mem_privileged_listener(task_t task, boolean_t new_value, boolean_t *old_value)
3662 {
3663 	if (old_value != NULL) {
3664 		*old_value = (boolean_t)task->low_mem_privileged_listener;
3665 	} else {
3666 		task_lock(task);
3667 		task->low_mem_privileged_listener = (uint32_t)new_value;
3668 		task_unlock(task);
3669 	}
3670 
3671 	return 0;
3672 }
3673 
3674 /*
3675  * Checks if the task is already notified.
3676  *
3677  * Condition: task lock should be held while calling this function.
3678  */
3679 boolean_t
task_has_been_notified(task_t task,int pressurelevel)3680 task_has_been_notified(task_t task, int pressurelevel)
3681 {
3682 	if (task == NULL) {
3683 		return FALSE;
3684 	}
3685 
3686 	if (pressurelevel == kVMPressureWarning) {
3687 		return task->low_mem_notified_warn ? TRUE : FALSE;
3688 	} else if (pressurelevel == kVMPressureCritical) {
3689 		return task->low_mem_notified_critical ? TRUE : FALSE;
3690 	} else {
3691 		return TRUE;
3692 	}
3693 }
3694 
3695 
3696 /*
3697  * Checks if the task is used for purging.
3698  *
3699  * Condition: task lock should be held while calling this function.
3700  */
3701 boolean_t
task_used_for_purging(task_t task,int pressurelevel)3702 task_used_for_purging(task_t task, int pressurelevel)
3703 {
3704 	if (task == NULL) {
3705 		return FALSE;
3706 	}
3707 
3708 	if (pressurelevel == kVMPressureWarning) {
3709 		return task->purged_memory_warn ? TRUE : FALSE;
3710 	} else if (pressurelevel == kVMPressureCritical) {
3711 		return task->purged_memory_critical ? TRUE : FALSE;
3712 	} else {
3713 		return TRUE;
3714 	}
3715 }
3716 
3717 
3718 /*
3719  * Mark the task as notified with memory notification.
3720  *
3721  * Condition: task lock should be held while calling this function.
3722  */
3723 void
task_mark_has_been_notified(task_t task,int pressurelevel)3724 task_mark_has_been_notified(task_t task, int pressurelevel)
3725 {
3726 	if (task == NULL) {
3727 		return;
3728 	}
3729 
3730 	if (pressurelevel == kVMPressureWarning) {
3731 		task->low_mem_notified_warn = 1;
3732 	} else if (pressurelevel == kVMPressureCritical) {
3733 		task->low_mem_notified_critical = 1;
3734 	}
3735 }
3736 
3737 
3738 /*
3739  * Mark the task as purged.
3740  *
3741  * Condition: task lock should be held while calling this function.
3742  */
3743 void
task_mark_used_for_purging(task_t task,int pressurelevel)3744 task_mark_used_for_purging(task_t task, int pressurelevel)
3745 {
3746 	if (task == NULL) {
3747 		return;
3748 	}
3749 
3750 	if (pressurelevel == kVMPressureWarning) {
3751 		task->purged_memory_warn = 1;
3752 	} else if (pressurelevel == kVMPressureCritical) {
3753 		task->purged_memory_critical = 1;
3754 	}
3755 }
3756 
3757 
3758 /*
3759  * Mark the task eligible for low memory notification.
3760  *
3761  * Condition: task lock should be held while calling this function.
3762  */
3763 void
task_clear_has_been_notified(task_t task,int pressurelevel)3764 task_clear_has_been_notified(task_t task, int pressurelevel)
3765 {
3766 	if (task == NULL) {
3767 		return;
3768 	}
3769 
3770 	if (pressurelevel == kVMPressureWarning) {
3771 		task->low_mem_notified_warn = 0;
3772 	} else if (pressurelevel == kVMPressureCritical) {
3773 		task->low_mem_notified_critical = 0;
3774 	}
3775 }
3776 
3777 
3778 /*
3779  * Mark the task eligible for purging its purgeable memory.
3780  *
3781  * Condition: task lock should be held while calling this function.
3782  */
3783 void
task_clear_used_for_purging(task_t task)3784 task_clear_used_for_purging(task_t task)
3785 {
3786 	if (task == NULL) {
3787 		return;
3788 	}
3789 
3790 	task->purged_memory_warn = 0;
3791 	task->purged_memory_critical = 0;
3792 }
3793 
3794 
3795 /*
3796  * Estimate task importance for purging its purgeable memory
3797  * and low memory notification.
3798  *
3799  * Importance is calculated in the following order of criteria:
3800  * -Task role : Background vs Foreground
3801  * -Boost status: Not boosted vs Boosted
3802  * -Darwin BG status.
3803  *
3804  * Returns: Estimated task importance. Less important task will have lower
3805  *          estimated importance.
3806  */
3807 int
task_importance_estimate(task_t task)3808 task_importance_estimate(task_t task)
3809 {
3810 	int task_importance = 0;
3811 
3812 	if (task == NULL) {
3813 		return 0;
3814 	}
3815 
3816 	if (proc_get_effective_task_policy(task, TASK_POLICY_ROLE) == TASK_FOREGROUND_APPLICATION) {
3817 		task_importance += TASK_IMPORTANCE_FOREGROUND;
3818 	}
3819 
3820 	if (proc_get_effective_task_policy(task, TASK_POLICY_DARWIN_BG) == 0) {
3821 		task_importance += TASK_IMPORTANCE_NOTDARWINBG;
3822 	}
3823 
3824 	return task_importance;
3825 }
3826 
3827 boolean_t
task_has_assertions(task_t task)3828 task_has_assertions(task_t task)
3829 {
3830 	return task->task_imp_base->iit_assertcnt? TRUE : FALSE;
3831 }
3832 
3833 
3834 kern_return_t
send_resource_violation(typeof(send_cpu_usage_violation) sendfunc,task_t violator,struct ledger_entry_info * linfo,resource_notify_flags_t flags)3835 send_resource_violation(typeof(send_cpu_usage_violation) sendfunc,
3836     task_t violator,
3837     struct ledger_entry_info *linfo,
3838     resource_notify_flags_t flags)
3839 {
3840 #ifndef MACH_BSD
3841 	return KERN_NOT_SUPPORTED;
3842 #else
3843 	kern_return_t   kr = KERN_SUCCESS;
3844 	proc_t          proc = NULL;
3845 	posix_path_t    proc_path = "";
3846 	proc_name_t     procname = "<unknown>";
3847 	int             pid = -1;
3848 	clock_sec_t     secs;
3849 	clock_nsec_t    nsecs;
3850 	mach_timespec_t timestamp;
3851 	thread_t        curthread = current_thread();
3852 	ipc_port_t      dstport = MACH_PORT_NULL;
3853 
3854 	if (!violator) {
3855 		kr = KERN_INVALID_ARGUMENT; goto finish;
3856 	}
3857 
3858 	/* extract violator information */
3859 	task_lock(violator);
3860 	if (!(proc = get_bsdtask_info(violator))) {
3861 		task_unlock(violator);
3862 		kr = KERN_INVALID_ARGUMENT; goto finish;
3863 	}
3864 	(void)mig_strncpy(procname, proc_best_name(proc), sizeof(procname));
3865 	pid = task_pid(violator);
3866 	if (flags & kRNFatalLimitFlag) {
3867 		kr = proc_pidpathinfo_internal(proc, 0, proc_path,
3868 		    sizeof(proc_path), NULL);
3869 	}
3870 	task_unlock(violator);
3871 	if (kr) {
3872 		goto finish;
3873 	}
3874 
3875 	/* violation time ~ now */
3876 	clock_get_calendar_nanotime(&secs, &nsecs);
3877 	timestamp.tv_sec = (int32_t)secs;
3878 	timestamp.tv_nsec = (int32_t)nsecs;
3879 	/* 25567702 tracks widening mach_timespec_t */
3880 
3881 	/* send message */
3882 	kr = host_get_special_port(host_priv_self(), HOST_LOCAL_NODE,
3883 	    HOST_RESOURCE_NOTIFY_PORT, &dstport);
3884 	if (kr) {
3885 		goto finish;
3886 	}
3887 
3888 	thread_set_honor_qlimit(curthread);
3889 	kr = sendfunc(dstport,
3890 	    procname, pid, proc_path, timestamp,
3891 	    linfo->lei_balance, linfo->lei_last_refill,
3892 	    linfo->lei_limit, linfo->lei_refill_period,
3893 	    flags);
3894 	thread_clear_honor_qlimit(curthread);
3895 
3896 	ipc_port_release_send(dstport);
3897 
3898 finish:
3899 	return kr;
3900 #endif      /* MACH_BSD */
3901 }
3902 
3903 kern_return_t
send_resource_violation_with_fatal_port(typeof(send_port_space_violation) sendfunc,task_t violator,int64_t current_size,int64_t limit,mach_port_t fatal_port,resource_notify_flags_t flags)3904 send_resource_violation_with_fatal_port(typeof(send_port_space_violation) sendfunc,
3905     task_t violator,
3906     int64_t current_size,
3907     int64_t limit,
3908     mach_port_t fatal_port,
3909     resource_notify_flags_t flags)
3910 {
3911 #ifndef MACH_BSD
3912 	kr = KERN_NOT_SUPPORTED; goto finish;
3913 #else
3914 	kern_return_t   kr = KERN_SUCCESS;
3915 	proc_t          proc = NULL;
3916 	proc_name_t     procname = "<unknown>";
3917 	int             pid = -1;
3918 	clock_sec_t     secs;
3919 	clock_nsec_t    nsecs;
3920 	mach_timespec_t timestamp;
3921 	thread_t        curthread = current_thread();
3922 	ipc_port_t      dstport = MACH_PORT_NULL;
3923 
3924 	if (!violator) {
3925 		kr = KERN_INVALID_ARGUMENT; goto finish;
3926 	}
3927 
3928 	/* extract violator information; no need to acquire task lock */
3929 	assert(violator == current_task());
3930 	if (!(proc = get_bsdtask_info(violator))) {
3931 		kr = KERN_INVALID_ARGUMENT; goto finish;
3932 	}
3933 	(void)mig_strncpy(procname, proc_best_name(proc), sizeof(procname));
3934 	pid = task_pid(violator);
3935 
3936 	/* violation time ~ now */
3937 	clock_get_calendar_nanotime(&secs, &nsecs);
3938 	timestamp.tv_sec = (int32_t)secs;
3939 	timestamp.tv_nsec = (int32_t)nsecs;
3940 	/* 25567702 tracks widening mach_timespec_t */
3941 
3942 	/* send message */
3943 	kr = task_get_special_port(current_task(), TASK_RESOURCE_NOTIFY_PORT, &dstport);
3944 	if (dstport == MACH_PORT_NULL) {
3945 		kr = host_get_special_port(host_priv_self(), HOST_LOCAL_NODE,
3946 		    HOST_RESOURCE_NOTIFY_PORT, &dstport);
3947 		if (kr) {
3948 			goto finish;
3949 		}
3950 	}
3951 
3952 	thread_set_honor_qlimit(curthread);
3953 	kr = sendfunc(dstport,
3954 	    procname, pid, timestamp,
3955 	    current_size, limit, fatal_port,
3956 	    flags);
3957 	thread_clear_honor_qlimit(curthread);
3958 
3959 	ipc_port_release_send(dstport);
3960 
3961 #endif /* MACH_BSD */
3962 finish:
3963 	return kr;
3964 }
3965 
3966 /*
3967  * Resource violations trace four 64-bit integers.  For K32, two additional
3968  * codes are allocated, the first with the low nibble doubled.  So if the K64
3969  * code is 0x042, the K32 codes would be 0x044 and 0x45.
3970  */
3971 #ifdef __LP64__
3972 void
trace_resource_violation(uint16_t code,struct ledger_entry_info * linfo)3973 trace_resource_violation(uint16_t code,
3974     struct ledger_entry_info *linfo)
3975 {
3976 	KERNEL_DBG_IST_SANE(KDBG_CODE(DBG_MACH, DBG_MACH_RESOURCE, code),
3977 	    linfo->lei_balance, linfo->lei_last_refill,
3978 	    linfo->lei_limit, linfo->lei_refill_period);
3979 }
3980 #else /* K32 */
3981 /* TODO: create/find a trace_two_LLs() for K32 systems */
3982 #define MASK32 0xffffffff
3983 void
trace_resource_violation(uint16_t code,struct ledger_entry_info * linfo)3984 trace_resource_violation(uint16_t code,
3985     struct ledger_entry_info *linfo)
3986 {
3987 	int8_t lownibble = (code & 0x3) * 2;
3988 	int16_t codeA = (code & 0xffc) | lownibble;
3989 	int16_t codeB = codeA + 1;
3990 
3991 	int32_t balance_high = (linfo->lei_balance >> 32) & MASK32;
3992 	int32_t balance_low = linfo->lei_balance & MASK32;
3993 	int32_t last_refill_high = (linfo->lei_last_refill >> 32) & MASK32;
3994 	int32_t last_refill_low = linfo->lei_last_refill & MASK32;
3995 
3996 	int32_t limit_high = (linfo->lei_limit >> 32) & MASK32;
3997 	int32_t limit_low = linfo->lei_limit & MASK32;
3998 	int32_t refill_period_high = (linfo->lei_refill_period >> 32) & MASK32;
3999 	int32_t refill_period_low = linfo->lei_refill_period & MASK32;
4000 
4001 	KERNEL_DBG_IST_SANE(KDBG_CODE(DBG_MACH, DBG_MACH_RESOURCE, codeA),
4002 	    balance_high, balance_low,
4003 	    last_refill_high, last_refill_low);
4004 	KERNEL_DBG_IST_SANE(KDBG_CODE(DBG_MACH, DBG_MACH_RESOURCE, codeB),
4005 	    limit_high, limit_low,
4006 	    refill_period_high, refill_period_low);
4007 }
4008 #endif /* K64/K32 */
4009