xref: /xnu-8792.61.2/osfmk/kern/priority.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	priority.c
60  *	Author:	Avadis Tevanian, Jr.
61  *	Date:	1986
62  *
63  *	Priority related scheduler bits.
64  */
65 
66 #include <mach/boolean.h>
67 #include <mach/kern_return.h>
68 #include <mach/machine.h>
69 #include <kern/host.h>
70 #include <kern/mach_param.h>
71 #include <kern/sched.h>
72 #include <sys/kdebug.h>
73 #include <kern/spl.h>
74 #include <kern/thread.h>
75 #include <kern/processor.h>
76 #include <kern/ledger.h>
77 #include <machine/machparam.h>
78 #include <kern/machine.h>
79 #include <kern/policy_internal.h>
80 #include <kern/sched_clutch.h>
81 
82 #ifdef CONFIG_MACH_APPROXIMATE_TIME
83 #include <machine/commpage.h>  /* for commpage_update_mach_approximate_time */
84 #endif
85 
86 #if MONOTONIC
87 #include <kern/monotonic.h>
88 #endif /* MONOTONIC */
89 
90 /*
91  *	thread_quantum_expire:
92  *
93  *	Recalculate the quantum and priority for a thread.
94  *
95  *	Called at splsched.
96  */
97 
98 void
thread_quantum_expire(timer_call_param_t p0,timer_call_param_t p1)99 thread_quantum_expire(
100 	timer_call_param_t      p0,
101 	timer_call_param_t      p1)
102 {
103 	processor_t                     processor = p0;
104 	thread_t                        thread = p1;
105 	ast_t                           preempt;
106 	uint64_t                        ctime;
107 
108 	assert(processor == current_processor());
109 	assert(thread == current_thread());
110 
111 	KDBG_RELEASE(MACHDBG_CODE(
112 		    DBG_MACH_SCHED, MACH_SCHED_QUANTUM_EXPIRED) | DBG_FUNC_START);
113 
114 	SCHED_STATS_INC(quantum_timer_expirations);
115 
116 	/*
117 	 * We bill CPU time to both the individual thread and its task.
118 	 *
119 	 * Because this balance adjustment could potentially attempt to wake this
120 	 * very thread, we must credit the ledger before taking the thread lock.
121 	 * The ledger pointers are only manipulated by the thread itself at the ast
122 	 * boundary.
123 	 *
124 	 * TODO: This fails to account for the time between when the timer was
125 	 * armed and when it fired.  It should be based on the system_timer and
126 	 * running a timer_update operation here.
127 	 */
128 	ledger_credit(thread->t_ledger, task_ledgers.cpu_time, thread->quantum_remaining);
129 	ledger_credit(thread->t_threadledger, thread_ledgers.cpu_time, thread->quantum_remaining);
130 	if (thread->t_bankledger) {
131 		ledger_credit(thread->t_bankledger, bank_ledgers.cpu_time,
132 		    (thread->quantum_remaining - thread->t_deduct_bank_ledger_time));
133 	}
134 	thread->t_deduct_bank_ledger_time = 0;
135 
136 	struct recount_snap snap = { 0 };
137 	recount_snapshot(&snap);
138 	ctime = snap.rsn_time_mach;
139 	check_monotonic_time(ctime);
140 #ifdef CONFIG_MACH_APPROXIMATE_TIME
141 	commpage_update_mach_approximate_time(ctime);
142 #endif /* CONFIG_MACH_APPROXIMATE_TIME */
143 
144 	sched_update_pset_avg_execution_time(processor->processor_set, thread->quantum_remaining, ctime, thread->th_sched_bucket);
145 
146 	recount_switch_thread(&snap, thread, get_threadtask(thread));
147 	recount_log_switch_thread(&snap);
148 
149 	thread_lock(thread);
150 
151 	/*
152 	 * We've run up until our quantum expiration, and will (potentially)
153 	 * continue without re-entering the scheduler, so update this now.
154 	 */
155 	processor->last_dispatch = ctime;
156 	thread->last_run_time = ctime;
157 
158 	/*
159 	 *	Check for fail-safe trip.
160 	 */
161 	if ((thread->sched_mode == TH_MODE_REALTIME || thread->sched_mode == TH_MODE_FIXED) &&
162 	    !(thread->sched_flags & TH_SFLAG_PROMOTED) &&
163 	    !(thread->kern_promotion_schedpri != 0) &&
164 	    !(thread->sched_flags & TH_SFLAG_PROMOTE_REASON_MASK) &&
165 	    !(thread->options & TH_OPT_SYSTEM_CRITICAL)) {
166 		uint64_t new_computation;
167 
168 		new_computation = ctime - thread->computation_epoch;
169 		new_computation += thread->computation_metered;
170 
171 		bool demote = false;
172 		switch (thread->sched_mode) {
173 		case TH_MODE_REALTIME:
174 			if (new_computation > max_unsafe_rt_computation) {
175 				thread->safe_release = ctime + sched_safe_rt_duration;
176 				demote = true;
177 			}
178 			break;
179 		case TH_MODE_FIXED:
180 			if (new_computation > max_unsafe_fixed_computation) {
181 				thread->safe_release = ctime + sched_safe_fixed_duration;
182 				demote = true;
183 			}
184 			break;
185 		default:
186 			panic("unexpected mode: %d", thread->sched_mode);
187 		}
188 
189 		if (demote) {
190 			KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_FAILSAFE) | DBG_FUNC_NONE,
191 			    (uintptr_t)thread->sched_pri, (uintptr_t)thread->sched_mode, 0, 0, 0);
192 			sched_thread_mode_demote(thread, TH_SFLAG_FAILSAFE);
193 		}
194 	}
195 
196 	/*
197 	 *	Recompute scheduled priority if appropriate.
198 	 */
199 	if (SCHED(can_update_priority)(thread)) {
200 		SCHED(update_priority)(thread);
201 	} else {
202 		SCHED(lightweight_update_priority)(thread);
203 	}
204 
205 	if (thread->sched_mode != TH_MODE_REALTIME) {
206 		SCHED(quantum_expire)(thread);
207 	}
208 
209 	/*
210 	 *	This quantum is up, give this thread another.
211 	 */
212 	processor->first_timeslice = FALSE;
213 
214 	thread_quantum_init(thread);
215 
216 	timer_update(&thread->runnable_timer, ctime);
217 
218 	processor->quantum_end = ctime + thread->quantum_remaining;
219 
220 	/*
221 	 * Context switch check
222 	 *
223 	 * non-urgent flags don't affect kernel threads, so upgrade to urgent
224 	 * to ensure that rebalancing and non-recommendation kick in quickly.
225 	 */
226 
227 	ast_t check_reason = AST_QUANTUM;
228 	if (get_threadtask(thread) == kernel_task) {
229 		check_reason |= AST_URGENT;
230 	}
231 
232 	if ((preempt = csw_check(thread, processor, check_reason)) != AST_NONE) {
233 		ast_on(preempt);
234 	}
235 
236 	/*
237 	 * AST_KEVENT does not send an IPI when setting the AST,
238 	 * to avoid waiting for the next context switch to propagate the AST,
239 	 * the AST is propagated here at quantum expiration.
240 	 */
241 	ast_propagate(thread);
242 
243 	thread_unlock(thread);
244 
245 	/* Now that the processor->thread_timer has been updated, evaluate to see if
246 	 * the workqueue quantum expired and set AST_KEVENT if it has */
247 	if (thread_get_tag(thread) & THREAD_TAG_WORKQUEUE) {
248 		thread_evaluate_workqueue_quantum_expiry(thread);
249 	}
250 
251 	running_timer_enter(processor, RUNNING_TIMER_QUANTUM, thread,
252 	    processor->quantum_end, ctime);
253 
254 	/* Tell platform layer that we are still running this thread */
255 	thread_urgency_t urgency = thread_get_urgency(thread, NULL, NULL);
256 	machine_thread_going_on_core(thread, urgency, 0, 0, ctime);
257 	machine_switch_perfcontrol_state_update(QUANTUM_EXPIRY, ctime,
258 	    0, thread);
259 
260 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
261 	sched_timeshare_consider_maintenance(ctime);
262 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
263 
264 #if __arm64__
265 	if (thread->sched_mode == TH_MODE_REALTIME) {
266 		sched_consider_recommended_cores(ctime, thread);
267 	}
268 #endif /* __arm64__ */
269 
270 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_SCHED_QUANTUM_EXPIRED) | DBG_FUNC_END, preempt, 0, 0, 0, 0);
271 }
272 
273 /*
274  *	sched_set_thread_base_priority:
275  *
276  *	Set the base priority of the thread
277  *	and reset its scheduled priority.
278  *
279  *	This is the only path to change base_pri.
280  *
281  *	Called with the thread locked.
282  */
283 void
sched_set_thread_base_priority(thread_t thread,int priority)284 sched_set_thread_base_priority(thread_t thread, int priority)
285 {
286 	assert(priority >= MINPRI);
287 	uint64_t ctime = 0;
288 
289 	if (thread->sched_mode == TH_MODE_REALTIME) {
290 		assert((priority >= BASEPRI_RTQUEUES) && (priority <= MAXPRI));
291 	} else {
292 		assert(priority < BASEPRI_RTQUEUES);
293 	}
294 
295 	int old_base_pri = thread->base_pri;
296 	thread->req_base_pri = (int16_t)priority;
297 	if (thread->sched_flags & TH_SFLAG_BASE_PRI_FROZEN) {
298 		priority = MAX(priority, old_base_pri);
299 	}
300 	thread->base_pri = (int16_t)priority;
301 
302 	if ((thread->state & TH_RUN) == TH_RUN) {
303 		assert(thread->last_made_runnable_time != THREAD_NOT_RUNNABLE);
304 		ctime = mach_approximate_time();
305 		thread->last_basepri_change_time = ctime;
306 	} else {
307 		assert(thread->last_basepri_change_time == THREAD_NOT_RUNNABLE);
308 		assert(thread->last_made_runnable_time == THREAD_NOT_RUNNABLE);
309 	}
310 
311 	/*
312 	 * Currently the perfcontrol_attr depends on the base pri of the
313 	 * thread. Therefore, we use this function as the hook for the
314 	 * perfcontrol callout.
315 	 */
316 	if (thread == current_thread() && old_base_pri != priority) {
317 		if (!ctime) {
318 			ctime = mach_approximate_time();
319 		}
320 		machine_switch_perfcontrol_state_update(PERFCONTROL_ATTR_UPDATE,
321 		    ctime, PERFCONTROL_CALLOUT_WAKE_UNSAFE, thread);
322 	}
323 #if !CONFIG_SCHED_CLUTCH
324 	/* For the clutch scheduler, this operation is done in set_sched_pri() */
325 	SCHED(update_thread_bucket)(thread);
326 #endif /* !CONFIG_SCHED_CLUTCH */
327 
328 	thread_recompute_sched_pri(thread, SETPRI_DEFAULT);
329 }
330 
331 /*
332  *	sched_set_kernel_thread_priority:
333  *
334  *	Set the absolute base priority of the thread
335  *	and reset its scheduled priority.
336  *
337  *	Called with the thread unlocked.
338  */
339 void
sched_set_kernel_thread_priority(thread_t thread,int new_priority)340 sched_set_kernel_thread_priority(thread_t thread, int new_priority)
341 {
342 	spl_t s = splsched();
343 
344 	thread_lock(thread);
345 
346 	assert(thread->sched_mode != TH_MODE_REALTIME);
347 	assert(thread->effective_policy.thep_qos == THREAD_QOS_UNSPECIFIED);
348 
349 	if (new_priority > thread->max_priority) {
350 		new_priority = thread->max_priority;
351 	}
352 #if !defined(XNU_TARGET_OS_OSX)
353 	if (new_priority < MAXPRI_THROTTLE) {
354 		new_priority = MAXPRI_THROTTLE;
355 	}
356 #endif /* !defined(XNU_TARGET_OS_OSX) */
357 
358 	thread->importance = new_priority - thread->task_priority;
359 
360 	sched_set_thread_base_priority(thread, new_priority);
361 
362 	thread_unlock(thread);
363 	splx(s);
364 }
365 
366 /*
367  *	thread_recompute_sched_pri:
368  *
369  *	Reset the scheduled priority of the thread
370  *	according to its base priority if the
371  *	thread has not been promoted or depressed.
372  *
373  *	This is the only way to push base_pri changes into sched_pri,
374  *	or to recalculate the appropriate sched_pri after changing
375  *	a promotion or depression.
376  *
377  *	Called at splsched with the thread locked.
378  *
379  *	TODO: Add an 'update urgency' flag to avoid urgency callouts on every rwlock operation
380  */
381 void
thread_recompute_sched_pri(thread_t thread,set_sched_pri_options_t options)382 thread_recompute_sched_pri(thread_t thread, set_sched_pri_options_t options)
383 {
384 	uint32_t     sched_flags = thread->sched_flags;
385 	sched_mode_t sched_mode  = thread->sched_mode;
386 
387 	int16_t priority = thread->base_pri;
388 
389 	if (sched_mode == TH_MODE_TIMESHARE) {
390 		priority = (int16_t)SCHED(compute_timeshare_priority)(thread);
391 	}
392 
393 	if (sched_flags & TH_SFLAG_DEPRESS) {
394 		/* thread_yield_internal overrides kernel mutex promotion */
395 		priority = DEPRESSPRI;
396 	} else {
397 		/* poll-depress is overridden by mutex promotion and promote-reasons */
398 		if ((sched_flags & TH_SFLAG_POLLDEPRESS)) {
399 			priority = DEPRESSPRI;
400 		}
401 
402 		if (thread->kern_promotion_schedpri > 0) {
403 			priority = MAX(priority, thread->kern_promotion_schedpri);
404 
405 			if (sched_mode != TH_MODE_REALTIME) {
406 				priority = MIN(priority, MAXPRI_PROMOTE);
407 			}
408 		}
409 
410 		if (sched_flags & TH_SFLAG_PROMOTED) {
411 			priority = MAX(priority, thread->promotion_priority);
412 
413 			if (sched_mode != TH_MODE_REALTIME) {
414 				priority = MIN(priority, MAXPRI_PROMOTE);
415 			}
416 		}
417 
418 		if (sched_flags & TH_SFLAG_PROMOTE_REASON_MASK) {
419 			if (sched_flags & TH_SFLAG_RW_PROMOTED) {
420 				priority = MAX(priority, MINPRI_RWLOCK);
421 			}
422 
423 			if (sched_flags & TH_SFLAG_WAITQ_PROMOTED) {
424 				priority = MAX(priority, MINPRI_WAITQ);
425 			}
426 
427 			if (sched_flags & TH_SFLAG_EXEC_PROMOTED) {
428 				priority = MAX(priority, MINPRI_EXEC);
429 			}
430 
431 			if (sched_flags & TH_SFLAG_FLOOR_PROMOTED) {
432 				priority = MAX(priority, MINPRI_FLOOR);
433 			}
434 		}
435 	}
436 
437 	set_sched_pri(thread, priority, options);
438 }
439 
440 void
sched_default_quantum_expire(thread_t thread __unused)441 sched_default_quantum_expire(thread_t thread __unused)
442 {
443 	/*
444 	 * No special behavior when a timeshare, fixed, or realtime thread
445 	 * uses up its entire quantum
446 	 */
447 }
448 
449 int smt_timeshare_enabled = 1;
450 int smt_sched_bonus_16ths = 8;
451 
452 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
453 
454 /*
455  *	lightweight_update_priority:
456  *
457  *	Update the scheduled priority for
458  *	a timesharing thread.
459  *
460  *	Only for use on the current thread.
461  *
462  *	Called with the thread locked.
463  */
464 void
lightweight_update_priority(thread_t thread)465 lightweight_update_priority(thread_t thread)
466 {
467 	assert(thread->runq == PROCESSOR_NULL);
468 	assert(thread == current_thread());
469 
470 	if (thread->sched_mode == TH_MODE_TIMESHARE) {
471 		int priority;
472 		uint32_t delta;
473 
474 		sched_tick_delta(thread, delta);
475 
476 		/*
477 		 *	Accumulate timesharing usage only
478 		 *	during contention for processor
479 		 *	resources.
480 		 */
481 		if (thread->pri_shift < INT8_MAX) {
482 			if (thread_no_smt(thread) && smt_timeshare_enabled) {
483 				thread->sched_usage += (delta + ((delta * smt_sched_bonus_16ths) >> 4));
484 			} else {
485 				thread->sched_usage += delta;
486 			}
487 		}
488 
489 		thread->cpu_delta += delta;
490 
491 #if CONFIG_SCHED_CLUTCH
492 		/*
493 		 * Update the CPU usage for the thread group to which the thread belongs.
494 		 * The implementation assumes that the thread ran for the entire delta
495 		 * as part of the same thread group.
496 		 */
497 		sched_clutch_cpu_usage_update(thread, delta);
498 #endif /* CONFIG_SCHED_CLUTCH */
499 
500 		priority = sched_compute_timeshare_priority(thread);
501 
502 		if (priority != thread->sched_pri) {
503 			thread_recompute_sched_pri(thread, SETPRI_LAZY);
504 		}
505 	}
506 }
507 
508 /*
509  *	Define shifts for simulating (5/8) ** n
510  *
511  *	Shift structures for holding update shifts.  Actual computation
512  *	is  usage = (usage >> shift1) +/- (usage >> abs(shift2))  where the
513  *	+/- is determined by the sign of shift 2.
514  */
515 
516 const struct shift_data        sched_decay_shifts[SCHED_DECAY_TICKS] = {
517 	{ .shift1 = 1, .shift2 = 1 },
518 	{ .shift1 = 1, .shift2 = 3 },
519 	{ .shift1 = 1, .shift2 = -3 },
520 	{ .shift1 = 2, .shift2 = -7 },
521 	{ .shift1 = 3, .shift2 = 5 },
522 	{ .shift1 = 3, .shift2 = -5 },
523 	{ .shift1 = 4, .shift2 = -8 },
524 	{ .shift1 = 5, .shift2 = 7 },
525 	{ .shift1 = 5, .shift2 = -7 },
526 	{ .shift1 = 6, .shift2 = -10 },
527 	{ .shift1 = 7, .shift2 = 10 },
528 	{ .shift1 = 7, .shift2 = -9 },
529 	{ .shift1 = 8, .shift2 = -11 },
530 	{ .shift1 = 9, .shift2 = 12 },
531 	{ .shift1 = 9, .shift2 = -11 },
532 	{ .shift1 = 10, .shift2 = -13 },
533 	{ .shift1 = 11, .shift2 = 14 },
534 	{ .shift1 = 11, .shift2 = -13 },
535 	{ .shift1 = 12, .shift2 = -15 },
536 	{ .shift1 = 13, .shift2 = 17 },
537 	{ .shift1 = 13, .shift2 = -15 },
538 	{ .shift1 = 14, .shift2 = -17 },
539 	{ .shift1 = 15, .shift2 = 19 },
540 	{ .shift1 = 16, .shift2 = 18 },
541 	{ .shift1 = 16, .shift2 = -19 },
542 	{ .shift1 = 17, .shift2 = 22 },
543 	{ .shift1 = 18, .shift2 = 20 },
544 	{ .shift1 = 18, .shift2 = -20 },
545 	{ .shift1 = 19, .shift2 = 26 },
546 	{ .shift1 = 20, .shift2 = 22 },
547 	{ .shift1 = 20, .shift2 = -22 },
548 	{ .shift1 = 21, .shift2 = -27 }
549 };
550 
551 /*
552  *	sched_compute_timeshare_priority:
553  *
554  *	Calculate the timesharing priority based upon usage and load.
555  */
556 extern int sched_pri_decay_band_limit;
557 
558 
559 /* Only use the decay floor logic on non-macOS and non-clutch schedulers */
560 #if !defined(XNU_TARGET_OS_OSX) && !CONFIG_SCHED_CLUTCH
561 
562 int
sched_compute_timeshare_priority(thread_t thread)563 sched_compute_timeshare_priority(thread_t thread)
564 {
565 	int decay_amount;
566 	int decay_limit = sched_pri_decay_band_limit;
567 
568 	if (thread->base_pri > BASEPRI_FOREGROUND) {
569 		decay_limit += (thread->base_pri - BASEPRI_FOREGROUND);
570 	}
571 
572 	if (thread->pri_shift == INT8_MAX) {
573 		decay_amount = 0;
574 	} else {
575 		decay_amount = (thread->sched_usage >> thread->pri_shift);
576 	}
577 
578 	if (decay_amount > decay_limit) {
579 		decay_amount = decay_limit;
580 	}
581 
582 	/* start with base priority */
583 	int priority = thread->base_pri - decay_amount;
584 
585 	if (priority < MAXPRI_THROTTLE) {
586 		if (get_threadtask(thread)->max_priority > MAXPRI_THROTTLE) {
587 			priority = MAXPRI_THROTTLE;
588 		} else if (priority < MINPRI_USER) {
589 			priority = MINPRI_USER;
590 		}
591 	} else if (priority > MAXPRI_KERNEL) {
592 		priority = MAXPRI_KERNEL;
593 	}
594 
595 	return priority;
596 }
597 
598 #else /* !defined(XNU_TARGET_OS_OSX) && !CONFIG_SCHED_CLUTCH */
599 
600 int
sched_compute_timeshare_priority(thread_t thread)601 sched_compute_timeshare_priority(thread_t thread)
602 {
603 	/* start with base priority */
604 	int priority = thread->base_pri;
605 
606 	if (thread->pri_shift != INT8_MAX) {
607 		priority -= (thread->sched_usage >> thread->pri_shift);
608 	}
609 
610 	if (priority < MINPRI_USER) {
611 		priority = MINPRI_USER;
612 	} else if (priority > MAXPRI_KERNEL) {
613 		priority = MAXPRI_KERNEL;
614 	}
615 
616 	return priority;
617 }
618 
619 #endif /* !defined(XNU_TARGET_OS_OSX) && !CONFIG_SCHED_CLUTCH */
620 
621 /*
622  *	can_update_priority
623  *
624  *	Make sure we don't do re-dispatches more frequently than a scheduler tick.
625  *
626  *	Called with the thread locked.
627  */
628 boolean_t
can_update_priority(thread_t thread)629 can_update_priority(
630 	thread_t        thread)
631 {
632 	if (sched_tick == thread->sched_stamp) {
633 		return FALSE;
634 	} else {
635 		return TRUE;
636 	}
637 }
638 
639 /*
640  *	update_priority
641  *
642  *	Perform housekeeping operations driven by scheduler tick.
643  *
644  *	Called with the thread locked.
645  */
646 void
update_priority(thread_t thread)647 update_priority(
648 	thread_t        thread)
649 {
650 	uint32_t ticks, delta;
651 
652 	ticks = sched_tick - thread->sched_stamp;
653 	assert(ticks != 0);
654 
655 	thread->sched_stamp += ticks;
656 
657 	/* If requested, accelerate aging of sched_usage */
658 	if (sched_decay_usage_age_factor > 1) {
659 		ticks *= sched_decay_usage_age_factor;
660 	}
661 
662 	/*
663 	 *	Gather cpu usage data.
664 	 */
665 	sched_tick_delta(thread, delta);
666 	if (ticks < SCHED_DECAY_TICKS) {
667 		/*
668 		 *	Accumulate timesharing usage only during contention for processor
669 		 *	resources. Use the pri_shift from the previous tick window to
670 		 *	determine if the system was in a contended state.
671 		 */
672 		if (thread->pri_shift < INT8_MAX) {
673 			if (thread_no_smt(thread) && smt_timeshare_enabled) {
674 				thread->sched_usage += (delta + ((delta * smt_sched_bonus_16ths) >> 4));
675 			} else {
676 				thread->sched_usage += delta;
677 			}
678 		}
679 
680 		thread->cpu_usage += delta + thread->cpu_delta;
681 		thread->cpu_delta = 0;
682 
683 #if CONFIG_SCHED_CLUTCH
684 		/*
685 		 * Update the CPU usage for the thread group to which the thread belongs.
686 		 * The implementation assumes that the thread ran for the entire delta
687 		 * as part of the same thread group.
688 		 */
689 		sched_clutch_cpu_usage_update(thread, delta);
690 #endif /* CONFIG_SCHED_CLUTCH */
691 
692 		const struct shift_data *shiftp = &sched_decay_shifts[ticks];
693 
694 		if (shiftp->shift2 > 0) {
695 			thread->cpu_usage =   (thread->cpu_usage >> shiftp->shift1) +
696 			    (thread->cpu_usage >> shiftp->shift2);
697 			thread->sched_usage = (thread->sched_usage >> shiftp->shift1) +
698 			    (thread->sched_usage >> shiftp->shift2);
699 		} else {
700 			thread->cpu_usage =   (thread->cpu_usage >>   shiftp->shift1) -
701 			    (thread->cpu_usage >> -(shiftp->shift2));
702 			thread->sched_usage = (thread->sched_usage >>   shiftp->shift1) -
703 			    (thread->sched_usage >> -(shiftp->shift2));
704 		}
705 	} else {
706 		thread->cpu_usage = thread->cpu_delta = 0;
707 		thread->sched_usage = 0;
708 	}
709 
710 	/*
711 	 *	Check for fail-safe release.
712 	 */
713 	if ((thread->sched_flags & TH_SFLAG_FAILSAFE) &&
714 	    mach_absolute_time() >= thread->safe_release) {
715 		sched_thread_mode_undemote(thread, TH_SFLAG_FAILSAFE);
716 	}
717 
718 	/*
719 	 * Now that the thread's CPU usage has been accumulated and aged
720 	 * based on contention of the previous tick window, update the
721 	 * pri_shift of the thread to match the current global load/shift
722 	 * values. The updated pri_shift would be used to calculate the
723 	 * new priority of the thread.
724 	 */
725 #if CONFIG_SCHED_CLUTCH
726 	thread->pri_shift = sched_clutch_thread_pri_shift(thread, thread->th_sched_bucket);
727 #else /* CONFIG_SCHED_CLUTCH */
728 	thread->pri_shift = sched_pri_shifts[thread->th_sched_bucket];
729 #endif /* CONFIG_SCHED_CLUTCH */
730 
731 	/* Recompute scheduled priority if appropriate. */
732 	if (thread->sched_mode == TH_MODE_TIMESHARE) {
733 		thread_recompute_sched_pri(thread, SETPRI_LAZY);
734 	}
735 }
736 
737 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
738 
739 
740 /*
741  * TH_BUCKET_RUN is a count of *all* runnable non-idle threads.
742  * Each other bucket is a count of the runnable non-idle threads
743  * with that property. All updates to these counts should be
744  * performed with os_atomic_* operations.
745  *
746  * For the clutch scheduler, this global bucket is used only for
747  * keeping the total global run count.
748  */
749 uint32_t       sched_run_buckets[TH_BUCKET_MAX];
750 
751 static void
sched_incr_bucket(sched_bucket_t bucket)752 sched_incr_bucket(sched_bucket_t bucket)
753 {
754 	assert(bucket >= TH_BUCKET_FIXPRI &&
755 	    bucket <= TH_BUCKET_SHARE_BG);
756 
757 	os_atomic_inc(&sched_run_buckets[bucket], relaxed);
758 }
759 
760 static void
sched_decr_bucket(sched_bucket_t bucket)761 sched_decr_bucket(sched_bucket_t bucket)
762 {
763 	assert(bucket >= TH_BUCKET_FIXPRI &&
764 	    bucket <= TH_BUCKET_SHARE_BG);
765 
766 	assert(os_atomic_load(&sched_run_buckets[bucket], relaxed) > 0);
767 
768 	os_atomic_dec(&sched_run_buckets[bucket], relaxed);
769 }
770 
771 static void
sched_add_bucket(sched_bucket_t bucket,uint8_t run_weight)772 sched_add_bucket(sched_bucket_t bucket, uint8_t run_weight)
773 {
774 	assert(bucket >= TH_BUCKET_FIXPRI &&
775 	    bucket <= TH_BUCKET_SHARE_BG);
776 
777 	os_atomic_add(&sched_run_buckets[bucket], run_weight, relaxed);
778 }
779 
780 static void
sched_sub_bucket(sched_bucket_t bucket,uint8_t run_weight)781 sched_sub_bucket(sched_bucket_t bucket, uint8_t run_weight)
782 {
783 	assert(bucket >= TH_BUCKET_FIXPRI &&
784 	    bucket <= TH_BUCKET_SHARE_BG);
785 
786 	assert(os_atomic_load(&sched_run_buckets[bucket], relaxed) > 0);
787 
788 	os_atomic_sub(&sched_run_buckets[bucket], run_weight, relaxed);
789 }
790 
791 uint32_t
sched_run_incr(thread_t thread)792 sched_run_incr(thread_t thread)
793 {
794 	assert((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN);
795 
796 	uint32_t new_count = os_atomic_inc(&sched_run_buckets[TH_BUCKET_RUN], relaxed);
797 
798 	sched_incr_bucket(thread->th_sched_bucket);
799 
800 	return new_count;
801 }
802 
803 uint32_t
sched_run_decr(thread_t thread)804 sched_run_decr(thread_t thread)
805 {
806 	assert((thread->state & (TH_RUN | TH_IDLE)) != TH_RUN);
807 
808 	sched_decr_bucket(thread->th_sched_bucket);
809 
810 	uint32_t new_count = os_atomic_dec(&sched_run_buckets[TH_BUCKET_RUN], relaxed);
811 
812 	return new_count;
813 }
814 
815 uint32_t
sched_smt_run_incr(thread_t thread)816 sched_smt_run_incr(thread_t thread)
817 {
818 	assert((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN);
819 
820 	uint8_t run_weight = (thread_no_smt(thread) && smt_timeshare_enabled) ? 2 : 1;
821 	thread->sched_saved_run_weight = run_weight;
822 
823 	uint32_t new_count = os_atomic_add(&sched_run_buckets[TH_BUCKET_RUN], run_weight, relaxed);
824 
825 	sched_add_bucket(thread->th_sched_bucket, run_weight);
826 
827 	return new_count;
828 }
829 
830 uint32_t
sched_smt_run_decr(thread_t thread)831 sched_smt_run_decr(thread_t thread)
832 {
833 	assert((thread->state & (TH_RUN | TH_IDLE)) != TH_RUN);
834 
835 	uint8_t run_weight = thread->sched_saved_run_weight;
836 
837 	sched_sub_bucket(thread->th_sched_bucket, run_weight);
838 
839 	uint32_t new_count = os_atomic_sub(&sched_run_buckets[TH_BUCKET_RUN], run_weight, relaxed);
840 
841 	return new_count;
842 }
843 
844 void
sched_update_thread_bucket(thread_t thread)845 sched_update_thread_bucket(thread_t thread)
846 {
847 	sched_bucket_t old_bucket = thread->th_sched_bucket;
848 	sched_bucket_t new_bucket = TH_BUCKET_RUN;
849 
850 	switch (thread->sched_mode) {
851 	case TH_MODE_FIXED:
852 	case TH_MODE_REALTIME:
853 		new_bucket = TH_BUCKET_FIXPRI;
854 		break;
855 
856 	case TH_MODE_TIMESHARE:
857 		if (thread->base_pri > BASEPRI_DEFAULT) {
858 			new_bucket = TH_BUCKET_SHARE_FG;
859 		} else if (thread->base_pri > BASEPRI_UTILITY) {
860 			new_bucket = TH_BUCKET_SHARE_DF;
861 		} else if (thread->base_pri > MAXPRI_THROTTLE) {
862 			new_bucket = TH_BUCKET_SHARE_UT;
863 		} else {
864 			new_bucket = TH_BUCKET_SHARE_BG;
865 		}
866 		break;
867 
868 	default:
869 		panic("unexpected mode: %d", thread->sched_mode);
870 		break;
871 	}
872 
873 	if (old_bucket != new_bucket) {
874 		thread->th_sched_bucket = new_bucket;
875 		thread->pri_shift = sched_pri_shifts[new_bucket];
876 
877 		if ((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN) {
878 			sched_decr_bucket(old_bucket);
879 			sched_incr_bucket(new_bucket);
880 		}
881 	}
882 }
883 
884 void
sched_smt_update_thread_bucket(thread_t thread)885 sched_smt_update_thread_bucket(thread_t thread)
886 {
887 	sched_bucket_t old_bucket = thread->th_sched_bucket;
888 	sched_bucket_t new_bucket = TH_BUCKET_RUN;
889 
890 	switch (thread->sched_mode) {
891 	case TH_MODE_FIXED:
892 	case TH_MODE_REALTIME:
893 		new_bucket = TH_BUCKET_FIXPRI;
894 		break;
895 
896 	case TH_MODE_TIMESHARE:
897 		if (thread->base_pri > BASEPRI_DEFAULT) {
898 			new_bucket = TH_BUCKET_SHARE_FG;
899 		} else if (thread->base_pri > BASEPRI_UTILITY) {
900 			new_bucket = TH_BUCKET_SHARE_DF;
901 		} else if (thread->base_pri > MAXPRI_THROTTLE) {
902 			new_bucket = TH_BUCKET_SHARE_UT;
903 		} else {
904 			new_bucket = TH_BUCKET_SHARE_BG;
905 		}
906 		break;
907 
908 	default:
909 		panic("unexpected mode: %d", thread->sched_mode);
910 		break;
911 	}
912 
913 	if (old_bucket != new_bucket) {
914 		thread->th_sched_bucket = new_bucket;
915 		thread->pri_shift = sched_pri_shifts[new_bucket];
916 
917 		if ((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN) {
918 			sched_sub_bucket(old_bucket, thread->sched_saved_run_weight);
919 			sched_add_bucket(new_bucket, thread->sched_saved_run_weight);
920 		}
921 	}
922 }
923 
924 static inline void
sched_validate_mode(sched_mode_t mode)925 sched_validate_mode(sched_mode_t mode)
926 {
927 	switch (mode) {
928 	case TH_MODE_FIXED:
929 	case TH_MODE_REALTIME:
930 	case TH_MODE_TIMESHARE:
931 		break;
932 
933 	default:
934 		panic("unexpected mode: %d", mode);
935 		break;
936 	}
937 }
938 
939 /*
940  * Set the thread's true scheduling mode
941  * Called with thread mutex and thread locked
942  * The thread has already been removed from the runqueue.
943  *
944  * (saved_mode is handled before this point)
945  */
946 void
sched_set_thread_mode(thread_t thread,sched_mode_t new_mode)947 sched_set_thread_mode(thread_t thread, sched_mode_t new_mode)
948 {
949 	assert(thread->runq == PROCESSOR_NULL);
950 
951 	sched_validate_mode(new_mode);
952 
953 #if CONFIG_SCHED_AUTO_JOIN
954 	/*
955 	 * Realtime threads might have auto-joined a work interval based on
956 	 * make runnable relationships. If such an RT thread is now being demoted
957 	 * to non-RT, unjoin the thread from the work interval.
958 	 */
959 	if ((thread->sched_flags & TH_SFLAG_THREAD_GROUP_AUTO_JOIN) && (new_mode != TH_MODE_REALTIME)) {
960 		assert((thread->sched_mode == TH_MODE_REALTIME) || (thread->th_work_interval_flags & TH_WORK_INTERVAL_FLAGS_AUTO_JOIN_LEAK));
961 		work_interval_auto_join_demote(thread);
962 	}
963 #endif /* CONFIG_SCHED_AUTO_JOIN */
964 
965 	thread->sched_mode = new_mode;
966 
967 	SCHED(update_thread_bucket)(thread);
968 }
969 
970 /*
971  * TODO: Instead of having saved mode, have 'user mode' and 'true mode'.
972  * That way there's zero confusion over which the user wants
973  * and which the kernel wants.
974  */
975 void
sched_set_thread_mode_user(thread_t thread,sched_mode_t new_mode)976 sched_set_thread_mode_user(thread_t thread, sched_mode_t new_mode)
977 {
978 	assert(thread->runq == PROCESSOR_NULL);
979 
980 	sched_validate_mode(new_mode);
981 
982 	/* If demoted, only modify the saved mode. */
983 	if (thread->sched_flags & TH_SFLAG_DEMOTED_MASK) {
984 		thread->saved_mode = new_mode;
985 	} else {
986 		sched_set_thread_mode(thread, new_mode);
987 	}
988 }
989 
990 /*
991  * Demote the true scheduler mode to timeshare (called with the thread locked)
992  */
993 void
sched_thread_mode_demote(thread_t thread,uint32_t reason)994 sched_thread_mode_demote(thread_t thread, uint32_t reason)
995 {
996 	assert(reason & TH_SFLAG_DEMOTED_MASK);
997 	assert((thread->sched_flags & reason) != reason);
998 
999 	if (thread->policy_reset) {
1000 		return;
1001 	}
1002 
1003 	switch (reason) {
1004 	case TH_SFLAG_THROTTLED:
1005 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_DEMOTE_THROTTLED),
1006 		    thread_tid(thread), thread->sched_flags);
1007 		break;
1008 	case TH_SFLAG_FAILSAFE:
1009 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_DEMOTE_FAILSAFE),
1010 		    thread_tid(thread), thread->sched_flags);
1011 		break;
1012 	case TH_SFLAG_RT_RESTRICTED:
1013 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_DEMOTE_RT_RESTRICTED),
1014 		    thread_tid(thread), thread->sched_flags);
1015 		break;
1016 	}
1017 
1018 	if (thread->sched_flags & TH_SFLAG_DEMOTED_MASK) {
1019 		/* Another demotion reason is already active */
1020 		thread->sched_flags |= reason;
1021 		return;
1022 	}
1023 
1024 	assert(thread->saved_mode == TH_MODE_NONE);
1025 
1026 	boolean_t removed = thread_run_queue_remove(thread);
1027 
1028 	thread->sched_flags |= reason;
1029 
1030 	thread->saved_mode = thread->sched_mode;
1031 
1032 	sched_set_thread_mode(thread, TH_MODE_TIMESHARE);
1033 
1034 	thread_recompute_priority(thread);
1035 
1036 	if (removed) {
1037 		thread_run_queue_reinsert(thread, SCHED_TAILQ);
1038 	}
1039 }
1040 
1041 /*
1042  * Un-demote the true scheduler mode back to the saved mode (called with the thread locked)
1043  */
1044 void
sched_thread_mode_undemote(thread_t thread,uint32_t reason)1045 sched_thread_mode_undemote(thread_t thread, uint32_t reason)
1046 {
1047 	assert(reason & TH_SFLAG_DEMOTED_MASK);
1048 	assert((thread->sched_flags & reason) == reason);
1049 	assert(thread->saved_mode != TH_MODE_NONE);
1050 	assert(thread->sched_mode == TH_MODE_TIMESHARE);
1051 	assert(thread->policy_reset == 0);
1052 
1053 	switch (reason) {
1054 	case TH_SFLAG_THROTTLED:
1055 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_UNDEMOTE_THROTTLED),
1056 		    thread_tid(thread), thread->sched_flags);
1057 		break;
1058 	case TH_SFLAG_FAILSAFE:
1059 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_UNDEMOTE_FAILSAFE),
1060 		    thread_tid(thread), thread->sched_flags);
1061 		break;
1062 	case TH_SFLAG_RT_RESTRICTED:
1063 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_MODE_UNDEMOTE_RT_RESTRICTED),
1064 		    thread_tid(thread), thread->sched_flags);
1065 		break;
1066 	}
1067 
1068 	thread->sched_flags &= ~reason;
1069 
1070 	if (thread->sched_flags & TH_SFLAG_DEMOTED_MASK) {
1071 		/* Another demotion reason is still active */
1072 		return;
1073 	}
1074 
1075 	boolean_t removed = thread_run_queue_remove(thread);
1076 
1077 	sched_set_thread_mode(thread, thread->saved_mode);
1078 
1079 	thread->saved_mode = TH_MODE_NONE;
1080 
1081 	thread_recompute_priority(thread);
1082 
1083 	if (removed) {
1084 		thread_run_queue_reinsert(thread, SCHED_TAILQ);
1085 	}
1086 }
1087 
1088 /*
1089  * Promote thread to have a sched pri floor for a specific reason
1090  *
1091  * Promotion must not last past syscall boundary
1092  * Clients must always pair promote and demote 1:1,
1093  * Handling nesting of the same promote reason is the client's responsibility
1094  *
1095  * Called at splsched with thread locked
1096  */
1097 void
sched_thread_promote_reason(thread_t thread,uint32_t reason,__kdebug_only uintptr_t trace_obj)1098 sched_thread_promote_reason(thread_t    thread,
1099     uint32_t    reason,
1100     __kdebug_only uintptr_t   trace_obj /* already unslid */)
1101 {
1102 	assert(reason & TH_SFLAG_PROMOTE_REASON_MASK);
1103 	assert((thread->sched_flags & reason) != reason);
1104 
1105 	switch (reason) {
1106 	case TH_SFLAG_RW_PROMOTED:
1107 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_RW_PROMOTE),
1108 		    thread_tid(thread), thread->sched_pri,
1109 		    thread->base_pri, trace_obj);
1110 		break;
1111 	case TH_SFLAG_WAITQ_PROMOTED:
1112 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_WAITQ_PROMOTE),
1113 		    thread_tid(thread), thread->sched_pri,
1114 		    thread->base_pri, trace_obj);
1115 		break;
1116 	case TH_SFLAG_EXEC_PROMOTED:
1117 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_EXEC_PROMOTE),
1118 		    thread_tid(thread), thread->sched_pri,
1119 		    thread->base_pri, trace_obj);
1120 		break;
1121 	case TH_SFLAG_FLOOR_PROMOTED:
1122 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_FLOOR_PROMOTE),
1123 		    thread_tid(thread), thread->sched_pri,
1124 		    thread->base_pri, trace_obj);
1125 		break;
1126 	}
1127 
1128 	thread->sched_flags |= reason;
1129 	thread_recompute_sched_pri(thread, SETPRI_DEFAULT);
1130 }
1131 
1132 /*
1133  * End a specific promotion reason
1134  * Demotes a thread back to its expected priority without the promotion in place
1135  *
1136  * Called at splsched with thread locked
1137  */
1138 void
sched_thread_unpromote_reason(thread_t thread,uint32_t reason,__kdebug_only uintptr_t trace_obj)1139 sched_thread_unpromote_reason(thread_t  thread,
1140     uint32_t  reason,
1141     __kdebug_only uintptr_t trace_obj /* already unslid */)
1142 {
1143 	assert(reason & TH_SFLAG_PROMOTE_REASON_MASK);
1144 	assert((thread->sched_flags & reason) == reason);
1145 
1146 	switch (reason) {
1147 	case TH_SFLAG_RW_PROMOTED:
1148 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_RW_DEMOTE),
1149 		    thread_tid(thread), thread->sched_pri,
1150 		    thread->base_pri, trace_obj);
1151 		break;
1152 	case TH_SFLAG_WAITQ_PROMOTED:
1153 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_WAITQ_DEMOTE),
1154 		    thread_tid(thread), thread->sched_pri,
1155 		    thread->base_pri, trace_obj);
1156 		break;
1157 	case TH_SFLAG_EXEC_PROMOTED:
1158 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_EXEC_DEMOTE),
1159 		    thread_tid(thread), thread->sched_pri,
1160 		    thread->base_pri, trace_obj);
1161 		break;
1162 	case TH_SFLAG_FLOOR_PROMOTED:
1163 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_FLOOR_DEMOTE),
1164 		    thread_tid(thread), thread->sched_pri,
1165 		    thread->base_pri, trace_obj);
1166 		break;
1167 	}
1168 
1169 	thread->sched_flags &= ~reason;
1170 
1171 	thread_recompute_sched_pri(thread, SETPRI_DEFAULT);
1172 }
1173