xref: /linux/kernel/sched/deadline.c (revision 8449d3252c2603a51ffc7c36cb5bd94874378b7d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Deadline Scheduling Class (SCHED_DEADLINE)
4  *
5  * Earliest Deadline First (EDF) + Constant Bandwidth Server (CBS).
6  *
7  * Tasks that periodically executes their instances for less than their
8  * runtime won't miss any of their deadlines.
9  * Tasks that are not periodic or sporadic or that tries to execute more
10  * than their reserved bandwidth will be slowed down (and may potentially
11  * miss some of their deadlines), and won't affect any other task.
12  *
13  * Copyright (C) 2012 Dario Faggioli <raistlin@linux.it>,
14  *                    Juri Lelli <juri.lelli@gmail.com>,
15  *                    Michael Trimarchi <michael@amarulasolutions.com>,
16  *                    Fabio Checconi <fchecconi@gmail.com>
17  */
18 
19 #include <linux/cpuset.h>
20 #include <linux/sched/clock.h>
21 #include <uapi/linux/sched/types.h>
22 #include "sched.h"
23 #include "pelt.h"
24 
25 /*
26  * Default limits for DL period; on the top end we guard against small util
27  * tasks still getting ridiculously long effective runtimes, on the bottom end we
28  * guard against timer DoS.
29  */
30 static unsigned int sysctl_sched_dl_period_max = 1 << 22; /* ~4 seconds */
31 static unsigned int sysctl_sched_dl_period_min = 100;     /* 100 us */
32 #ifdef CONFIG_SYSCTL
33 static const struct ctl_table sched_dl_sysctls[] = {
34 	{
35 		.procname       = "sched_deadline_period_max_us",
36 		.data           = &sysctl_sched_dl_period_max,
37 		.maxlen         = sizeof(unsigned int),
38 		.mode           = 0644,
39 		.proc_handler   = proc_douintvec_minmax,
40 		.extra1         = (void *)&sysctl_sched_dl_period_min,
41 	},
42 	{
43 		.procname       = "sched_deadline_period_min_us",
44 		.data           = &sysctl_sched_dl_period_min,
45 		.maxlen         = sizeof(unsigned int),
46 		.mode           = 0644,
47 		.proc_handler   = proc_douintvec_minmax,
48 		.extra2         = (void *)&sysctl_sched_dl_period_max,
49 	},
50 };
51 
sched_dl_sysctl_init(void)52 static int __init sched_dl_sysctl_init(void)
53 {
54 	register_sysctl_init("kernel", sched_dl_sysctls);
55 	return 0;
56 }
57 late_initcall(sched_dl_sysctl_init);
58 #endif /* CONFIG_SYSCTL */
59 
dl_server(struct sched_dl_entity * dl_se)60 static bool dl_server(struct sched_dl_entity *dl_se)
61 {
62 	return dl_se->dl_server;
63 }
64 
dl_task_of(struct sched_dl_entity * dl_se)65 static inline struct task_struct *dl_task_of(struct sched_dl_entity *dl_se)
66 {
67 	BUG_ON(dl_server(dl_se));
68 	return container_of(dl_se, struct task_struct, dl);
69 }
70 
rq_of_dl_rq(struct dl_rq * dl_rq)71 static inline struct rq *rq_of_dl_rq(struct dl_rq *dl_rq)
72 {
73 	return container_of(dl_rq, struct rq, dl);
74 }
75 
rq_of_dl_se(struct sched_dl_entity * dl_se)76 static inline struct rq *rq_of_dl_se(struct sched_dl_entity *dl_se)
77 {
78 	struct rq *rq = dl_se->rq;
79 
80 	if (!dl_server(dl_se))
81 		rq = task_rq(dl_task_of(dl_se));
82 
83 	return rq;
84 }
85 
dl_rq_of_se(struct sched_dl_entity * dl_se)86 static inline struct dl_rq *dl_rq_of_se(struct sched_dl_entity *dl_se)
87 {
88 	return &rq_of_dl_se(dl_se)->dl;
89 }
90 
on_dl_rq(struct sched_dl_entity * dl_se)91 static inline int on_dl_rq(struct sched_dl_entity *dl_se)
92 {
93 	return !RB_EMPTY_NODE(&dl_se->rb_node);
94 }
95 
96 #ifdef CONFIG_RT_MUTEXES
pi_of(struct sched_dl_entity * dl_se)97 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
98 {
99 	return dl_se->pi_se;
100 }
101 
is_dl_boosted(struct sched_dl_entity * dl_se)102 static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
103 {
104 	return pi_of(dl_se) != dl_se;
105 }
106 #else /* !CONFIG_RT_MUTEXES: */
pi_of(struct sched_dl_entity * dl_se)107 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
108 {
109 	return dl_se;
110 }
111 
is_dl_boosted(struct sched_dl_entity * dl_se)112 static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
113 {
114 	return false;
115 }
116 #endif /* !CONFIG_RT_MUTEXES */
117 
dl_bw_of(int i)118 static inline struct dl_bw *dl_bw_of(int i)
119 {
120 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
121 			 "sched RCU must be held");
122 	return &cpu_rq(i)->rd->dl_bw;
123 }
124 
dl_bw_cpus(int i)125 static inline int dl_bw_cpus(int i)
126 {
127 	struct root_domain *rd = cpu_rq(i)->rd;
128 
129 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
130 			 "sched RCU must be held");
131 
132 	return cpumask_weight_and(rd->span, cpu_active_mask);
133 }
134 
__dl_bw_capacity(const struct cpumask * mask)135 static inline unsigned long __dl_bw_capacity(const struct cpumask *mask)
136 {
137 	unsigned long cap = 0;
138 	int i;
139 
140 	for_each_cpu_and(i, mask, cpu_active_mask)
141 		cap += arch_scale_cpu_capacity(i);
142 
143 	return cap;
144 }
145 
146 /*
147  * XXX Fix: If 'rq->rd == def_root_domain' perform AC against capacity
148  * of the CPU the task is running on rather rd's \Sum CPU capacity.
149  */
dl_bw_capacity(int i)150 static inline unsigned long dl_bw_capacity(int i)
151 {
152 	if (!sched_asym_cpucap_active() &&
153 	    arch_scale_cpu_capacity(i) == SCHED_CAPACITY_SCALE) {
154 		return dl_bw_cpus(i) << SCHED_CAPACITY_SHIFT;
155 	} else {
156 		RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
157 				 "sched RCU must be held");
158 
159 		return __dl_bw_capacity(cpu_rq(i)->rd->span);
160 	}
161 }
162 
dl_bw_visited(int cpu,u64 cookie)163 bool dl_bw_visited(int cpu, u64 cookie)
164 {
165 	struct root_domain *rd = cpu_rq(cpu)->rd;
166 
167 	if (rd->visit_cookie == cookie)
168 		return true;
169 
170 	rd->visit_cookie = cookie;
171 	return false;
172 }
173 
174 static inline
__dl_update(struct dl_bw * dl_b,s64 bw)175 void __dl_update(struct dl_bw *dl_b, s64 bw)
176 {
177 	struct root_domain *rd = container_of(dl_b, struct root_domain, dl_bw);
178 	int i;
179 
180 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
181 			 "sched RCU must be held");
182 	for_each_cpu_and(i, rd->span, cpu_active_mask) {
183 		struct rq *rq = cpu_rq(i);
184 
185 		rq->dl.extra_bw += bw;
186 	}
187 }
188 
189 static inline
__dl_sub(struct dl_bw * dl_b,u64 tsk_bw,int cpus)190 void __dl_sub(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
191 {
192 	dl_b->total_bw -= tsk_bw;
193 	__dl_update(dl_b, (s32)tsk_bw / cpus);
194 }
195 
196 static inline
__dl_add(struct dl_bw * dl_b,u64 tsk_bw,int cpus)197 void __dl_add(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
198 {
199 	dl_b->total_bw += tsk_bw;
200 	__dl_update(dl_b, -((s32)tsk_bw / cpus));
201 }
202 
203 static inline bool
__dl_overflow(struct dl_bw * dl_b,unsigned long cap,u64 old_bw,u64 new_bw)204 __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
205 {
206 	return dl_b->bw != -1 &&
207 	       cap_scale(dl_b->bw, cap) < dl_b->total_bw - old_bw + new_bw;
208 }
209 
210 static inline
__add_running_bw(u64 dl_bw,struct dl_rq * dl_rq)211 void __add_running_bw(u64 dl_bw, struct dl_rq *dl_rq)
212 {
213 	u64 old = dl_rq->running_bw;
214 
215 	lockdep_assert_rq_held(rq_of_dl_rq(dl_rq));
216 	dl_rq->running_bw += dl_bw;
217 	WARN_ON_ONCE(dl_rq->running_bw < old); /* overflow */
218 	WARN_ON_ONCE(dl_rq->running_bw > dl_rq->this_bw);
219 	/* kick cpufreq (see the comment in kernel/sched/sched.h). */
220 	cpufreq_update_util(rq_of_dl_rq(dl_rq), 0);
221 }
222 
223 static inline
__sub_running_bw(u64 dl_bw,struct dl_rq * dl_rq)224 void __sub_running_bw(u64 dl_bw, struct dl_rq *dl_rq)
225 {
226 	u64 old = dl_rq->running_bw;
227 
228 	lockdep_assert_rq_held(rq_of_dl_rq(dl_rq));
229 	dl_rq->running_bw -= dl_bw;
230 	WARN_ON_ONCE(dl_rq->running_bw > old); /* underflow */
231 	if (dl_rq->running_bw > old)
232 		dl_rq->running_bw = 0;
233 	/* kick cpufreq (see the comment in kernel/sched/sched.h). */
234 	cpufreq_update_util(rq_of_dl_rq(dl_rq), 0);
235 }
236 
237 static inline
__add_rq_bw(u64 dl_bw,struct dl_rq * dl_rq)238 void __add_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)
239 {
240 	u64 old = dl_rq->this_bw;
241 
242 	lockdep_assert_rq_held(rq_of_dl_rq(dl_rq));
243 	dl_rq->this_bw += dl_bw;
244 	WARN_ON_ONCE(dl_rq->this_bw < old); /* overflow */
245 }
246 
247 static inline
__sub_rq_bw(u64 dl_bw,struct dl_rq * dl_rq)248 void __sub_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)
249 {
250 	u64 old = dl_rq->this_bw;
251 
252 	lockdep_assert_rq_held(rq_of_dl_rq(dl_rq));
253 	dl_rq->this_bw -= dl_bw;
254 	WARN_ON_ONCE(dl_rq->this_bw > old); /* underflow */
255 	if (dl_rq->this_bw > old)
256 		dl_rq->this_bw = 0;
257 	WARN_ON_ONCE(dl_rq->running_bw > dl_rq->this_bw);
258 }
259 
260 static inline
add_rq_bw(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)261 void add_rq_bw(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
262 {
263 	if (!dl_entity_is_special(dl_se))
264 		__add_rq_bw(dl_se->dl_bw, dl_rq);
265 }
266 
267 static inline
sub_rq_bw(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)268 void sub_rq_bw(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
269 {
270 	if (!dl_entity_is_special(dl_se))
271 		__sub_rq_bw(dl_se->dl_bw, dl_rq);
272 }
273 
274 static inline
add_running_bw(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)275 void add_running_bw(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
276 {
277 	if (!dl_entity_is_special(dl_se))
278 		__add_running_bw(dl_se->dl_bw, dl_rq);
279 }
280 
281 static inline
sub_running_bw(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)282 void sub_running_bw(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
283 {
284 	if (!dl_entity_is_special(dl_se))
285 		__sub_running_bw(dl_se->dl_bw, dl_rq);
286 }
287 
dl_rq_change_utilization(struct rq * rq,struct sched_dl_entity * dl_se,u64 new_bw)288 static void dl_rq_change_utilization(struct rq *rq, struct sched_dl_entity *dl_se, u64 new_bw)
289 {
290 	if (dl_se->dl_non_contending) {
291 		sub_running_bw(dl_se, &rq->dl);
292 		dl_se->dl_non_contending = 0;
293 
294 		/*
295 		 * If the timer handler is currently running and the
296 		 * timer cannot be canceled, inactive_task_timer()
297 		 * will see that dl_not_contending is not set, and
298 		 * will not touch the rq's active utilization,
299 		 * so we are still safe.
300 		 */
301 		if (hrtimer_try_to_cancel(&dl_se->inactive_timer) == 1) {
302 			if (!dl_server(dl_se))
303 				put_task_struct(dl_task_of(dl_se));
304 		}
305 	}
306 	__sub_rq_bw(dl_se->dl_bw, &rq->dl);
307 	__add_rq_bw(new_bw, &rq->dl);
308 }
309 
310 static __always_inline
cancel_dl_timer(struct sched_dl_entity * dl_se,struct hrtimer * timer)311 void cancel_dl_timer(struct sched_dl_entity *dl_se, struct hrtimer *timer)
312 {
313 	/*
314 	 * If the timer callback was running (hrtimer_try_to_cancel == -1),
315 	 * it will eventually call put_task_struct().
316 	 */
317 	if (hrtimer_try_to_cancel(timer) == 1 && !dl_server(dl_se))
318 		put_task_struct(dl_task_of(dl_se));
319 }
320 
321 static __always_inline
cancel_replenish_timer(struct sched_dl_entity * dl_se)322 void cancel_replenish_timer(struct sched_dl_entity *dl_se)
323 {
324 	cancel_dl_timer(dl_se, &dl_se->dl_timer);
325 }
326 
327 static __always_inline
cancel_inactive_timer(struct sched_dl_entity * dl_se)328 void cancel_inactive_timer(struct sched_dl_entity *dl_se)
329 {
330 	cancel_dl_timer(dl_se, &dl_se->inactive_timer);
331 }
332 
dl_change_utilization(struct task_struct * p,u64 new_bw)333 static void dl_change_utilization(struct task_struct *p, u64 new_bw)
334 {
335 	WARN_ON_ONCE(p->dl.flags & SCHED_FLAG_SUGOV);
336 
337 	if (task_on_rq_queued(p))
338 		return;
339 
340 	dl_rq_change_utilization(task_rq(p), &p->dl, new_bw);
341 }
342 
343 static void __dl_clear_params(struct sched_dl_entity *dl_se);
344 
345 /*
346  * The utilization of a task cannot be immediately removed from
347  * the rq active utilization (running_bw) when the task blocks.
348  * Instead, we have to wait for the so called "0-lag time".
349  *
350  * If a task blocks before the "0-lag time", a timer (the inactive
351  * timer) is armed, and running_bw is decreased when the timer
352  * fires.
353  *
354  * If the task wakes up again before the inactive timer fires,
355  * the timer is canceled, whereas if the task wakes up after the
356  * inactive timer fired (and running_bw has been decreased) the
357  * task's utilization has to be added to running_bw again.
358  * A flag in the deadline scheduling entity (dl_non_contending)
359  * is used to avoid race conditions between the inactive timer handler
360  * and task wakeups.
361  *
362  * The following diagram shows how running_bw is updated. A task is
363  * "ACTIVE" when its utilization contributes to running_bw; an
364  * "ACTIVE contending" task is in the TASK_RUNNING state, while an
365  * "ACTIVE non contending" task is a blocked task for which the "0-lag time"
366  * has not passed yet. An "INACTIVE" task is a task for which the "0-lag"
367  * time already passed, which does not contribute to running_bw anymore.
368  *                              +------------------+
369  *             wakeup           |    ACTIVE        |
370  *          +------------------>+   contending     |
371  *          | add_running_bw    |                  |
372  *          |                   +----+------+------+
373  *          |                        |      ^
374  *          |                dequeue |      |
375  * +--------+-------+                |      |
376  * |                |   t >= 0-lag   |      | wakeup
377  * |    INACTIVE    |<---------------+      |
378  * |                | sub_running_bw |      |
379  * +--------+-------+                |      |
380  *          ^                        |      |
381  *          |              t < 0-lag |      |
382  *          |                        |      |
383  *          |                        V      |
384  *          |                   +----+------+------+
385  *          | sub_running_bw    |    ACTIVE        |
386  *          +-------------------+                  |
387  *            inactive timer    |  non contending  |
388  *            fired             +------------------+
389  *
390  * The task_non_contending() function is invoked when a task
391  * blocks, and checks if the 0-lag time already passed or
392  * not (in the first case, it directly updates running_bw;
393  * in the second case, it arms the inactive timer).
394  *
395  * The task_contending() function is invoked when a task wakes
396  * up, and checks if the task is still in the "ACTIVE non contending"
397  * state or not (in the second case, it updates running_bw).
398  */
task_non_contending(struct sched_dl_entity * dl_se,bool dl_task)399 static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
400 {
401 	struct hrtimer *timer = &dl_se->inactive_timer;
402 	struct rq *rq = rq_of_dl_se(dl_se);
403 	struct dl_rq *dl_rq = &rq->dl;
404 	s64 zerolag_time;
405 
406 	/*
407 	 * If this is a non-deadline task that has been boosted,
408 	 * do nothing
409 	 */
410 	if (dl_se->dl_runtime == 0)
411 		return;
412 
413 	if (dl_entity_is_special(dl_se))
414 		return;
415 
416 	WARN_ON(dl_se->dl_non_contending);
417 
418 	zerolag_time = dl_se->deadline -
419 		 div64_long((dl_se->runtime * dl_se->dl_period),
420 			dl_se->dl_runtime);
421 
422 	/*
423 	 * Using relative times instead of the absolute "0-lag time"
424 	 * allows to simplify the code
425 	 */
426 	zerolag_time -= rq_clock(rq);
427 
428 	/*
429 	 * If the "0-lag time" already passed, decrease the active
430 	 * utilization now, instead of starting a timer
431 	 */
432 	if ((zerolag_time < 0) || hrtimer_active(&dl_se->inactive_timer)) {
433 		if (dl_server(dl_se)) {
434 			sub_running_bw(dl_se, dl_rq);
435 		} else {
436 			struct task_struct *p = dl_task_of(dl_se);
437 
438 			if (dl_task)
439 				sub_running_bw(dl_se, dl_rq);
440 
441 			if (!dl_task || READ_ONCE(p->__state) == TASK_DEAD) {
442 				struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
443 
444 				if (READ_ONCE(p->__state) == TASK_DEAD)
445 					sub_rq_bw(dl_se, &rq->dl);
446 				raw_spin_lock(&dl_b->lock);
447 				__dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(task_cpu(p)));
448 				raw_spin_unlock(&dl_b->lock);
449 				__dl_clear_params(dl_se);
450 			}
451 		}
452 
453 		return;
454 	}
455 
456 	dl_se->dl_non_contending = 1;
457 	if (!dl_server(dl_se))
458 		get_task_struct(dl_task_of(dl_se));
459 
460 	hrtimer_start(timer, ns_to_ktime(zerolag_time), HRTIMER_MODE_REL_HARD);
461 }
462 
task_contending(struct sched_dl_entity * dl_se,int flags)463 static void task_contending(struct sched_dl_entity *dl_se, int flags)
464 {
465 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
466 
467 	/*
468 	 * If this is a non-deadline task that has been boosted,
469 	 * do nothing
470 	 */
471 	if (dl_se->dl_runtime == 0)
472 		return;
473 
474 	if (flags & ENQUEUE_MIGRATED)
475 		add_rq_bw(dl_se, dl_rq);
476 
477 	if (dl_se->dl_non_contending) {
478 		dl_se->dl_non_contending = 0;
479 		/*
480 		 * If the timer handler is currently running and the
481 		 * timer cannot be canceled, inactive_task_timer()
482 		 * will see that dl_not_contending is not set, and
483 		 * will not touch the rq's active utilization,
484 		 * so we are still safe.
485 		 */
486 		cancel_inactive_timer(dl_se);
487 	} else {
488 		/*
489 		 * Since "dl_non_contending" is not set, the
490 		 * task's utilization has already been removed from
491 		 * active utilization (either when the task blocked,
492 		 * when the "inactive timer" fired).
493 		 * So, add it back.
494 		 */
495 		add_running_bw(dl_se, dl_rq);
496 	}
497 }
498 
is_leftmost(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)499 static inline int is_leftmost(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
500 {
501 	return rb_first_cached(&dl_rq->root) == &dl_se->rb_node;
502 }
503 
504 static void init_dl_rq_bw_ratio(struct dl_rq *dl_rq);
505 
init_dl_bw(struct dl_bw * dl_b)506 void init_dl_bw(struct dl_bw *dl_b)
507 {
508 	raw_spin_lock_init(&dl_b->lock);
509 	if (global_rt_runtime() == RUNTIME_INF)
510 		dl_b->bw = -1;
511 	else
512 		dl_b->bw = to_ratio(global_rt_period(), global_rt_runtime());
513 	dl_b->total_bw = 0;
514 }
515 
init_dl_rq(struct dl_rq * dl_rq)516 void init_dl_rq(struct dl_rq *dl_rq)
517 {
518 	dl_rq->root = RB_ROOT_CACHED;
519 
520 	/* zero means no -deadline tasks */
521 	dl_rq->earliest_dl.curr = dl_rq->earliest_dl.next = 0;
522 
523 	dl_rq->overloaded = 0;
524 	dl_rq->pushable_dl_tasks_root = RB_ROOT_CACHED;
525 
526 	dl_rq->running_bw = 0;
527 	dl_rq->this_bw = 0;
528 	init_dl_rq_bw_ratio(dl_rq);
529 }
530 
dl_overloaded(struct rq * rq)531 static inline int dl_overloaded(struct rq *rq)
532 {
533 	return atomic_read(&rq->rd->dlo_count);
534 }
535 
dl_set_overload(struct rq * rq)536 static inline void dl_set_overload(struct rq *rq)
537 {
538 	if (!rq->online)
539 		return;
540 
541 	cpumask_set_cpu(rq->cpu, rq->rd->dlo_mask);
542 	/*
543 	 * Must be visible before the overload count is
544 	 * set (as in sched_rt.c).
545 	 *
546 	 * Matched by the barrier in pull_dl_task().
547 	 */
548 	smp_wmb();
549 	atomic_inc(&rq->rd->dlo_count);
550 }
551 
dl_clear_overload(struct rq * rq)552 static inline void dl_clear_overload(struct rq *rq)
553 {
554 	if (!rq->online)
555 		return;
556 
557 	atomic_dec(&rq->rd->dlo_count);
558 	cpumask_clear_cpu(rq->cpu, rq->rd->dlo_mask);
559 }
560 
561 #define __node_2_pdl(node) \
562 	rb_entry((node), struct task_struct, pushable_dl_tasks)
563 
__pushable_less(struct rb_node * a,const struct rb_node * b)564 static inline bool __pushable_less(struct rb_node *a, const struct rb_node *b)
565 {
566 	return dl_entity_preempt(&__node_2_pdl(a)->dl, &__node_2_pdl(b)->dl);
567 }
568 
has_pushable_dl_tasks(struct rq * rq)569 static inline int has_pushable_dl_tasks(struct rq *rq)
570 {
571 	return !RB_EMPTY_ROOT(&rq->dl.pushable_dl_tasks_root.rb_root);
572 }
573 
574 /*
575  * The list of pushable -deadline task is not a plist, like in
576  * sched_rt.c, it is an rb-tree with tasks ordered by deadline.
577  */
enqueue_pushable_dl_task(struct rq * rq,struct task_struct * p)578 static void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
579 {
580 	struct rb_node *leftmost;
581 
582 	WARN_ON_ONCE(!RB_EMPTY_NODE(&p->pushable_dl_tasks));
583 
584 	leftmost = rb_add_cached(&p->pushable_dl_tasks,
585 				 &rq->dl.pushable_dl_tasks_root,
586 				 __pushable_less);
587 	if (leftmost)
588 		rq->dl.earliest_dl.next = p->dl.deadline;
589 
590 	if (!rq->dl.overloaded) {
591 		dl_set_overload(rq);
592 		rq->dl.overloaded = 1;
593 	}
594 }
595 
dequeue_pushable_dl_task(struct rq * rq,struct task_struct * p)596 static void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
597 {
598 	struct dl_rq *dl_rq = &rq->dl;
599 	struct rb_root_cached *root = &dl_rq->pushable_dl_tasks_root;
600 	struct rb_node *leftmost;
601 
602 	if (RB_EMPTY_NODE(&p->pushable_dl_tasks))
603 		return;
604 
605 	leftmost = rb_erase_cached(&p->pushable_dl_tasks, root);
606 	if (leftmost)
607 		dl_rq->earliest_dl.next = __node_2_pdl(leftmost)->dl.deadline;
608 
609 	RB_CLEAR_NODE(&p->pushable_dl_tasks);
610 
611 	if (!has_pushable_dl_tasks(rq) && rq->dl.overloaded) {
612 		dl_clear_overload(rq);
613 		rq->dl.overloaded = 0;
614 	}
615 }
616 
617 static int push_dl_task(struct rq *rq);
618 
need_pull_dl_task(struct rq * rq,struct task_struct * prev)619 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
620 {
621 	return rq->online && dl_task(prev);
622 }
623 
624 static DEFINE_PER_CPU(struct balance_callback, dl_push_head);
625 static DEFINE_PER_CPU(struct balance_callback, dl_pull_head);
626 
627 static void push_dl_tasks(struct rq *);
628 static void pull_dl_task(struct rq *);
629 
deadline_queue_push_tasks(struct rq * rq)630 static inline void deadline_queue_push_tasks(struct rq *rq)
631 {
632 	if (!has_pushable_dl_tasks(rq))
633 		return;
634 
635 	queue_balance_callback(rq, &per_cpu(dl_push_head, rq->cpu), push_dl_tasks);
636 }
637 
deadline_queue_pull_task(struct rq * rq)638 static inline void deadline_queue_pull_task(struct rq *rq)
639 {
640 	queue_balance_callback(rq, &per_cpu(dl_pull_head, rq->cpu), pull_dl_task);
641 }
642 
643 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq);
644 
dl_task_offline_migration(struct rq * rq,struct task_struct * p)645 static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p)
646 {
647 	struct rq *later_rq = NULL;
648 	struct dl_bw *dl_b;
649 
650 	later_rq = find_lock_later_rq(p, rq);
651 	if (!later_rq) {
652 		int cpu;
653 
654 		/*
655 		 * If we cannot preempt any rq, fall back to pick any
656 		 * online CPU:
657 		 */
658 		cpu = cpumask_any_and(cpu_active_mask, p->cpus_ptr);
659 		if (cpu >= nr_cpu_ids) {
660 			/*
661 			 * Failed to find any suitable CPU.
662 			 * The task will never come back!
663 			 */
664 			WARN_ON_ONCE(dl_bandwidth_enabled());
665 
666 			/*
667 			 * If admission control is disabled we
668 			 * try a little harder to let the task
669 			 * run.
670 			 */
671 			cpu = cpumask_any(cpu_active_mask);
672 		}
673 		later_rq = cpu_rq(cpu);
674 		double_lock_balance(rq, later_rq);
675 	}
676 
677 	if (p->dl.dl_non_contending || p->dl.dl_throttled) {
678 		/*
679 		 * Inactive timer is armed (or callback is running, but
680 		 * waiting for us to release rq locks). In any case, when it
681 		 * will fire (or continue), it will see running_bw of this
682 		 * task migrated to later_rq (and correctly handle it).
683 		 */
684 		sub_running_bw(&p->dl, &rq->dl);
685 		sub_rq_bw(&p->dl, &rq->dl);
686 
687 		add_rq_bw(&p->dl, &later_rq->dl);
688 		add_running_bw(&p->dl, &later_rq->dl);
689 	} else {
690 		sub_rq_bw(&p->dl, &rq->dl);
691 		add_rq_bw(&p->dl, &later_rq->dl);
692 	}
693 
694 	/*
695 	 * And we finally need to fix up root_domain(s) bandwidth accounting,
696 	 * since p is still hanging out in the old (now moved to default) root
697 	 * domain.
698 	 */
699 	dl_b = &rq->rd->dl_bw;
700 	raw_spin_lock(&dl_b->lock);
701 	__dl_sub(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
702 	raw_spin_unlock(&dl_b->lock);
703 
704 	dl_b = &later_rq->rd->dl_bw;
705 	raw_spin_lock(&dl_b->lock);
706 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(later_rq->rd->span));
707 	raw_spin_unlock(&dl_b->lock);
708 
709 	set_task_cpu(p, later_rq->cpu);
710 	double_unlock_balance(later_rq, rq);
711 
712 	return later_rq;
713 }
714 
715 static void
716 enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags);
717 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags);
718 static void dequeue_dl_entity(struct sched_dl_entity *dl_se, int flags);
719 static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p, int flags);
720 
replenish_dl_new_period(struct sched_dl_entity * dl_se,struct rq * rq)721 static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
722 					    struct rq *rq)
723 {
724 	/* for non-boosted task, pi_of(dl_se) == dl_se */
725 	dl_se->deadline = rq_clock(rq) + pi_of(dl_se)->dl_deadline;
726 	dl_se->runtime = pi_of(dl_se)->dl_runtime;
727 
728 	/*
729 	 * If it is a deferred reservation, and the server
730 	 * is not handling an starvation case, defer it.
731 	 */
732 	if (dl_se->dl_defer && !dl_se->dl_defer_running) {
733 		dl_se->dl_throttled = 1;
734 		dl_se->dl_defer_armed = 1;
735 	}
736 }
737 
738 /*
739  * We are being explicitly informed that a new instance is starting,
740  * and this means that:
741  *  - the absolute deadline of the entity has to be placed at
742  *    current time + relative deadline;
743  *  - the runtime of the entity has to be set to the maximum value.
744  *
745  * The capability of specifying such event is useful whenever a -deadline
746  * entity wants to (try to!) synchronize its behaviour with the scheduler's
747  * one, and to (try to!) reconcile itself with its own scheduling
748  * parameters.
749  */
setup_new_dl_entity(struct sched_dl_entity * dl_se)750 static inline void setup_new_dl_entity(struct sched_dl_entity *dl_se)
751 {
752 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
753 	struct rq *rq = rq_of_dl_rq(dl_rq);
754 
755 	update_rq_clock(rq);
756 
757 	WARN_ON(is_dl_boosted(dl_se));
758 	WARN_ON(dl_time_before(rq_clock(rq), dl_se->deadline));
759 
760 	/*
761 	 * We are racing with the deadline timer. So, do nothing because
762 	 * the deadline timer handler will take care of properly recharging
763 	 * the runtime and postponing the deadline
764 	 */
765 	if (dl_se->dl_throttled)
766 		return;
767 
768 	/*
769 	 * We use the regular wall clock time to set deadlines in the
770 	 * future; in fact, we must consider execution overheads (time
771 	 * spent on hardirq context, etc.).
772 	 */
773 	replenish_dl_new_period(dl_se, rq);
774 }
775 
776 static int start_dl_timer(struct sched_dl_entity *dl_se);
777 static bool dl_entity_overflow(struct sched_dl_entity *dl_se, u64 t);
778 
779 /*
780  * Pure Earliest Deadline First (EDF) scheduling does not deal with the
781  * possibility of a entity lasting more than what it declared, and thus
782  * exhausting its runtime.
783  *
784  * Here we are interested in making runtime overrun possible, but we do
785  * not want a entity which is misbehaving to affect the scheduling of all
786  * other entities.
787  * Therefore, a budgeting strategy called Constant Bandwidth Server (CBS)
788  * is used, in order to confine each entity within its own bandwidth.
789  *
790  * This function deals exactly with that, and ensures that when the runtime
791  * of a entity is replenished, its deadline is also postponed. That ensures
792  * the overrunning entity can't interfere with other entity in the system and
793  * can't make them miss their deadlines. Reasons why this kind of overruns
794  * could happen are, typically, a entity voluntarily trying to overcome its
795  * runtime, or it just underestimated it during sched_setattr().
796  */
replenish_dl_entity(struct sched_dl_entity * dl_se)797 static void replenish_dl_entity(struct sched_dl_entity *dl_se)
798 {
799 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
800 	struct rq *rq = rq_of_dl_rq(dl_rq);
801 
802 	WARN_ON_ONCE(pi_of(dl_se)->dl_runtime <= 0);
803 
804 	/*
805 	 * This could be the case for a !-dl task that is boosted.
806 	 * Just go with full inherited parameters.
807 	 *
808 	 * Or, it could be the case of a deferred reservation that
809 	 * was not able to consume its runtime in background and
810 	 * reached this point with current u > U.
811 	 *
812 	 * In both cases, set a new period.
813 	 */
814 	if (dl_se->dl_deadline == 0 ||
815 	    (dl_se->dl_defer_armed && dl_entity_overflow(dl_se, rq_clock(rq)))) {
816 		dl_se->deadline = rq_clock(rq) + pi_of(dl_se)->dl_deadline;
817 		dl_se->runtime = pi_of(dl_se)->dl_runtime;
818 	}
819 
820 	if (dl_se->dl_yielded && dl_se->runtime > 0)
821 		dl_se->runtime = 0;
822 
823 	/*
824 	 * We keep moving the deadline away until we get some
825 	 * available runtime for the entity. This ensures correct
826 	 * handling of situations where the runtime overrun is
827 	 * arbitrary large.
828 	 */
829 	while (dl_se->runtime <= 0) {
830 		dl_se->deadline += pi_of(dl_se)->dl_period;
831 		dl_se->runtime += pi_of(dl_se)->dl_runtime;
832 	}
833 
834 	/*
835 	 * At this point, the deadline really should be "in
836 	 * the future" with respect to rq->clock. If it's
837 	 * not, we are, for some reason, lagging too much!
838 	 * Anyway, after having warn userspace abut that,
839 	 * we still try to keep the things running by
840 	 * resetting the deadline and the budget of the
841 	 * entity.
842 	 */
843 	if (dl_time_before(dl_se->deadline, rq_clock(rq))) {
844 		printk_deferred_once("sched: DL replenish lagged too much\n");
845 		replenish_dl_new_period(dl_se, rq);
846 	}
847 
848 	if (dl_se->dl_yielded)
849 		dl_se->dl_yielded = 0;
850 	if (dl_se->dl_throttled)
851 		dl_se->dl_throttled = 0;
852 
853 	/*
854 	 * If this is the replenishment of a deferred reservation,
855 	 * clear the flag and return.
856 	 */
857 	if (dl_se->dl_defer_armed) {
858 		dl_se->dl_defer_armed = 0;
859 		return;
860 	}
861 
862 	/*
863 	 * A this point, if the deferred server is not armed, and the deadline
864 	 * is in the future, if it is not running already, throttle the server
865 	 * and arm the defer timer.
866 	 */
867 	if (dl_se->dl_defer && !dl_se->dl_defer_running &&
868 	    dl_time_before(rq_clock(dl_se->rq), dl_se->deadline - dl_se->runtime)) {
869 		if (!is_dl_boosted(dl_se)) {
870 
871 			/*
872 			 * Set dl_se->dl_defer_armed and dl_throttled variables to
873 			 * inform the start_dl_timer() that this is a deferred
874 			 * activation.
875 			 */
876 			dl_se->dl_defer_armed = 1;
877 			dl_se->dl_throttled = 1;
878 			if (!start_dl_timer(dl_se)) {
879 				/*
880 				 * If for whatever reason (delays), a previous timer was
881 				 * queued but not serviced, cancel it and clean the
882 				 * deferrable server variables intended for start_dl_timer().
883 				 */
884 				hrtimer_try_to_cancel(&dl_se->dl_timer);
885 				dl_se->dl_defer_armed = 0;
886 				dl_se->dl_throttled = 0;
887 			}
888 		}
889 	}
890 }
891 
892 /*
893  * Here we check if --at time t-- an entity (which is probably being
894  * [re]activated or, in general, enqueued) can use its remaining runtime
895  * and its current deadline _without_ exceeding the bandwidth it is
896  * assigned (function returns true if it can't). We are in fact applying
897  * one of the CBS rules: when a task wakes up, if the residual runtime
898  * over residual deadline fits within the allocated bandwidth, then we
899  * can keep the current (absolute) deadline and residual budget without
900  * disrupting the schedulability of the system. Otherwise, we should
901  * refill the runtime and set the deadline a period in the future,
902  * because keeping the current (absolute) deadline of the task would
903  * result in breaking guarantees promised to other tasks (refer to
904  * Documentation/scheduler/sched-deadline.rst for more information).
905  *
906  * This function returns true if:
907  *
908  *   runtime / (deadline - t) > dl_runtime / dl_deadline ,
909  *
910  * IOW we can't recycle current parameters.
911  *
912  * Notice that the bandwidth check is done against the deadline. For
913  * task with deadline equal to period this is the same of using
914  * dl_period instead of dl_deadline in the equation above.
915  */
dl_entity_overflow(struct sched_dl_entity * dl_se,u64 t)916 static bool dl_entity_overflow(struct sched_dl_entity *dl_se, u64 t)
917 {
918 	u64 left, right;
919 
920 	/*
921 	 * left and right are the two sides of the equation above,
922 	 * after a bit of shuffling to use multiplications instead
923 	 * of divisions.
924 	 *
925 	 * Note that none of the time values involved in the two
926 	 * multiplications are absolute: dl_deadline and dl_runtime
927 	 * are the relative deadline and the maximum runtime of each
928 	 * instance, runtime is the runtime left for the last instance
929 	 * and (deadline - t), since t is rq->clock, is the time left
930 	 * to the (absolute) deadline. Even if overflowing the u64 type
931 	 * is very unlikely to occur in both cases, here we scale down
932 	 * as we want to avoid that risk at all. Scaling down by 10
933 	 * means that we reduce granularity to 1us. We are fine with it,
934 	 * since this is only a true/false check and, anyway, thinking
935 	 * of anything below microseconds resolution is actually fiction
936 	 * (but still we want to give the user that illusion >;).
937 	 */
938 	left = (pi_of(dl_se)->dl_deadline >> DL_SCALE) * (dl_se->runtime >> DL_SCALE);
939 	right = ((dl_se->deadline - t) >> DL_SCALE) *
940 		(pi_of(dl_se)->dl_runtime >> DL_SCALE);
941 
942 	return dl_time_before(right, left);
943 }
944 
945 /*
946  * Revised wakeup rule [1]: For self-suspending tasks, rather then
947  * re-initializing task's runtime and deadline, the revised wakeup
948  * rule adjusts the task's runtime to avoid the task to overrun its
949  * density.
950  *
951  * Reasoning: a task may overrun the density if:
952  *    runtime / (deadline - t) > dl_runtime / dl_deadline
953  *
954  * Therefore, runtime can be adjusted to:
955  *     runtime = (dl_runtime / dl_deadline) * (deadline - t)
956  *
957  * In such way that runtime will be equal to the maximum density
958  * the task can use without breaking any rule.
959  *
960  * [1] Luca Abeni, Giuseppe Lipari, and Juri Lelli. 2015. Constant
961  * bandwidth server revisited. SIGBED Rev. 11, 4 (January 2015), 19-24.
962  */
963 static void
update_dl_revised_wakeup(struct sched_dl_entity * dl_se,struct rq * rq)964 update_dl_revised_wakeup(struct sched_dl_entity *dl_se, struct rq *rq)
965 {
966 	u64 laxity = dl_se->deadline - rq_clock(rq);
967 
968 	/*
969 	 * If the task has deadline < period, and the deadline is in the past,
970 	 * it should already be throttled before this check.
971 	 *
972 	 * See update_dl_entity() comments for further details.
973 	 */
974 	WARN_ON(dl_time_before(dl_se->deadline, rq_clock(rq)));
975 
976 	dl_se->runtime = (dl_se->dl_density * laxity) >> BW_SHIFT;
977 }
978 
979 /*
980  * Regarding the deadline, a task with implicit deadline has a relative
981  * deadline == relative period. A task with constrained deadline has a
982  * relative deadline <= relative period.
983  *
984  * We support constrained deadline tasks. However, there are some restrictions
985  * applied only for tasks which do not have an implicit deadline. See
986  * update_dl_entity() to know more about such restrictions.
987  *
988  * The dl_is_implicit() returns true if the task has an implicit deadline.
989  */
dl_is_implicit(struct sched_dl_entity * dl_se)990 static inline bool dl_is_implicit(struct sched_dl_entity *dl_se)
991 {
992 	return dl_se->dl_deadline == dl_se->dl_period;
993 }
994 
995 /*
996  * When a deadline entity is placed in the runqueue, its runtime and deadline
997  * might need to be updated. This is done by a CBS wake up rule. There are two
998  * different rules: 1) the original CBS; and 2) the Revisited CBS.
999  *
1000  * When the task is starting a new period, the Original CBS is used. In this
1001  * case, the runtime is replenished and a new absolute deadline is set.
1002  *
1003  * When a task is queued before the begin of the next period, using the
1004  * remaining runtime and deadline could make the entity to overflow, see
1005  * dl_entity_overflow() to find more about runtime overflow. When such case
1006  * is detected, the runtime and deadline need to be updated.
1007  *
1008  * If the task has an implicit deadline, i.e., deadline == period, the Original
1009  * CBS is applied. The runtime is replenished and a new absolute deadline is
1010  * set, as in the previous cases.
1011  *
1012  * However, the Original CBS does not work properly for tasks with
1013  * deadline < period, which are said to have a constrained deadline. By
1014  * applying the Original CBS, a constrained deadline task would be able to run
1015  * runtime/deadline in a period. With deadline < period, the task would
1016  * overrun the runtime/period allowed bandwidth, breaking the admission test.
1017  *
1018  * In order to prevent this misbehave, the Revisited CBS is used for
1019  * constrained deadline tasks when a runtime overflow is detected. In the
1020  * Revisited CBS, rather than replenishing & setting a new absolute deadline,
1021  * the remaining runtime of the task is reduced to avoid runtime overflow.
1022  * Please refer to the comments update_dl_revised_wakeup() function to find
1023  * more about the Revised CBS rule.
1024  */
update_dl_entity(struct sched_dl_entity * dl_se)1025 static void update_dl_entity(struct sched_dl_entity *dl_se)
1026 {
1027 	struct rq *rq = rq_of_dl_se(dl_se);
1028 
1029 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
1030 	    dl_entity_overflow(dl_se, rq_clock(rq))) {
1031 
1032 		if (unlikely(!dl_is_implicit(dl_se) &&
1033 			     !dl_time_before(dl_se->deadline, rq_clock(rq)) &&
1034 			     !is_dl_boosted(dl_se))) {
1035 			update_dl_revised_wakeup(dl_se, rq);
1036 			return;
1037 		}
1038 
1039 		replenish_dl_new_period(dl_se, rq);
1040 	} else if (dl_server(dl_se) && dl_se->dl_defer) {
1041 		/*
1042 		 * The server can still use its previous deadline, so check if
1043 		 * it left the dl_defer_running state.
1044 		 */
1045 		if (!dl_se->dl_defer_running) {
1046 			dl_se->dl_defer_armed = 1;
1047 			dl_se->dl_throttled = 1;
1048 		}
1049 	}
1050 }
1051 
dl_next_period(struct sched_dl_entity * dl_se)1052 static inline u64 dl_next_period(struct sched_dl_entity *dl_se)
1053 {
1054 	return dl_se->deadline - dl_se->dl_deadline + dl_se->dl_period;
1055 }
1056 
1057 /*
1058  * If the entity depleted all its runtime, and if we want it to sleep
1059  * while waiting for some new execution time to become available, we
1060  * set the bandwidth replenishment timer to the replenishment instant
1061  * and try to activate it.
1062  *
1063  * Notice that it is important for the caller to know if the timer
1064  * actually started or not (i.e., the replenishment instant is in
1065  * the future or in the past).
1066  */
start_dl_timer(struct sched_dl_entity * dl_se)1067 static int start_dl_timer(struct sched_dl_entity *dl_se)
1068 {
1069 	struct hrtimer *timer = &dl_se->dl_timer;
1070 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
1071 	struct rq *rq = rq_of_dl_rq(dl_rq);
1072 	ktime_t now, act;
1073 	s64 delta;
1074 
1075 	lockdep_assert_rq_held(rq);
1076 
1077 	/*
1078 	 * We want the timer to fire at the deadline, but considering
1079 	 * that it is actually coming from rq->clock and not from
1080 	 * hrtimer's time base reading.
1081 	 *
1082 	 * The deferred reservation will have its timer set to
1083 	 * (deadline - runtime). At that point, the CBS rule will decide
1084 	 * if the current deadline can be used, or if a replenishment is
1085 	 * required to avoid add too much pressure on the system
1086 	 * (current u > U).
1087 	 */
1088 	if (dl_se->dl_defer_armed) {
1089 		WARN_ON_ONCE(!dl_se->dl_throttled);
1090 		act = ns_to_ktime(dl_se->deadline - dl_se->runtime);
1091 	} else {
1092 		/* act = deadline - rel-deadline + period */
1093 		act = ns_to_ktime(dl_next_period(dl_se));
1094 	}
1095 
1096 	now = hrtimer_cb_get_time(timer);
1097 	delta = ktime_to_ns(now) - rq_clock(rq);
1098 	act = ktime_add_ns(act, delta);
1099 
1100 	/*
1101 	 * If the expiry time already passed, e.g., because the value
1102 	 * chosen as the deadline is too small, don't even try to
1103 	 * start the timer in the past!
1104 	 */
1105 	if (ktime_us_delta(act, now) < 0)
1106 		return 0;
1107 
1108 	/*
1109 	 * !enqueued will guarantee another callback; even if one is already in
1110 	 * progress. This ensures a balanced {get,put}_task_struct().
1111 	 *
1112 	 * The race against __run_timer() clearing the enqueued state is
1113 	 * harmless because we're holding task_rq()->lock, therefore the timer
1114 	 * expiring after we've done the check will wait on its task_rq_lock()
1115 	 * and observe our state.
1116 	 */
1117 	if (!hrtimer_is_queued(timer)) {
1118 		if (!dl_server(dl_se))
1119 			get_task_struct(dl_task_of(dl_se));
1120 		hrtimer_start(timer, act, HRTIMER_MODE_ABS_HARD);
1121 	}
1122 
1123 	return 1;
1124 }
1125 
__push_dl_task(struct rq * rq,struct rq_flags * rf)1126 static void __push_dl_task(struct rq *rq, struct rq_flags *rf)
1127 {
1128 	/*
1129 	 * Queueing this task back might have overloaded rq, check if we need
1130 	 * to kick someone away.
1131 	 */
1132 	if (has_pushable_dl_tasks(rq)) {
1133 		/*
1134 		 * Nothing relies on rq->lock after this, so its safe to drop
1135 		 * rq->lock.
1136 		 */
1137 		rq_unpin_lock(rq, rf);
1138 		push_dl_task(rq);
1139 		rq_repin_lock(rq, rf);
1140 	}
1141 }
1142 
1143 /* a defer timer will not be reset if the runtime consumed was < dl_server_min_res */
1144 static const u64 dl_server_min_res = 1 * NSEC_PER_MSEC;
1145 
dl_server_timer(struct hrtimer * timer,struct sched_dl_entity * dl_se)1146 static enum hrtimer_restart dl_server_timer(struct hrtimer *timer, struct sched_dl_entity *dl_se)
1147 {
1148 	struct rq *rq = rq_of_dl_se(dl_se);
1149 	u64 fw;
1150 
1151 	scoped_guard (rq_lock, rq) {
1152 		struct rq_flags *rf = &scope.rf;
1153 
1154 		if (!dl_se->dl_throttled || !dl_se->dl_runtime)
1155 			return HRTIMER_NORESTART;
1156 
1157 		sched_clock_tick();
1158 		update_rq_clock(rq);
1159 
1160 		/*
1161 		 * Make sure current has propagated its pending runtime into
1162 		 * any relevant server through calling dl_server_update() and
1163 		 * friends.
1164 		 */
1165 		rq->donor->sched_class->update_curr(rq);
1166 
1167 		if (dl_se->dl_defer_idle) {
1168 			dl_server_stop(dl_se);
1169 			return HRTIMER_NORESTART;
1170 		}
1171 
1172 		if (dl_se->dl_defer_armed) {
1173 			/*
1174 			 * First check if the server could consume runtime in background.
1175 			 * If so, it is possible to push the defer timer for this amount
1176 			 * of time. The dl_server_min_res serves as a limit to avoid
1177 			 * forwarding the timer for a too small amount of time.
1178 			 */
1179 			if (dl_time_before(rq_clock(dl_se->rq),
1180 					   (dl_se->deadline - dl_se->runtime - dl_server_min_res))) {
1181 
1182 				/* reset the defer timer */
1183 				fw = dl_se->deadline - rq_clock(dl_se->rq) - dl_se->runtime;
1184 
1185 				hrtimer_forward_now(timer, ns_to_ktime(fw));
1186 				return HRTIMER_RESTART;
1187 			}
1188 
1189 			dl_se->dl_defer_running = 1;
1190 		}
1191 
1192 		enqueue_dl_entity(dl_se, ENQUEUE_REPLENISH);
1193 
1194 		if (!dl_task(dl_se->rq->curr) || dl_entity_preempt(dl_se, &dl_se->rq->curr->dl))
1195 			resched_curr(rq);
1196 
1197 		__push_dl_task(rq, rf);
1198 	}
1199 
1200 	return HRTIMER_NORESTART;
1201 }
1202 
1203 /*
1204  * This is the bandwidth enforcement timer callback. If here, we know
1205  * a task is not on its dl_rq, since the fact that the timer was running
1206  * means the task is throttled and needs a runtime replenishment.
1207  *
1208  * However, what we actually do depends on the fact the task is active,
1209  * (it is on its rq) or has been removed from there by a call to
1210  * dequeue_task_dl(). In the former case we must issue the runtime
1211  * replenishment and add the task back to the dl_rq; in the latter, we just
1212  * do nothing but clearing dl_throttled, so that runtime and deadline
1213  * updating (and the queueing back to dl_rq) will be done by the
1214  * next call to enqueue_task_dl().
1215  */
dl_task_timer(struct hrtimer * timer)1216 static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
1217 {
1218 	struct sched_dl_entity *dl_se = container_of(timer,
1219 						     struct sched_dl_entity,
1220 						     dl_timer);
1221 	struct task_struct *p;
1222 	struct rq_flags rf;
1223 	struct rq *rq;
1224 
1225 	if (dl_server(dl_se))
1226 		return dl_server_timer(timer, dl_se);
1227 
1228 	p = dl_task_of(dl_se);
1229 	rq = task_rq_lock(p, &rf);
1230 
1231 	/*
1232 	 * The task might have changed its scheduling policy to something
1233 	 * different than SCHED_DEADLINE (through switched_from_dl()).
1234 	 */
1235 	if (!dl_task(p))
1236 		goto unlock;
1237 
1238 	/*
1239 	 * The task might have been boosted by someone else and might be in the
1240 	 * boosting/deboosting path, its not throttled.
1241 	 */
1242 	if (is_dl_boosted(dl_se))
1243 		goto unlock;
1244 
1245 	/*
1246 	 * Spurious timer due to start_dl_timer() race; or we already received
1247 	 * a replenishment from rt_mutex_setprio().
1248 	 */
1249 	if (!dl_se->dl_throttled)
1250 		goto unlock;
1251 
1252 	sched_clock_tick();
1253 	update_rq_clock(rq);
1254 
1255 	/*
1256 	 * If the throttle happened during sched-out; like:
1257 	 *
1258 	 *   schedule()
1259 	 *     deactivate_task()
1260 	 *       dequeue_task_dl()
1261 	 *         update_curr_dl()
1262 	 *           start_dl_timer()
1263 	 *         __dequeue_task_dl()
1264 	 *     prev->on_rq = 0;
1265 	 *
1266 	 * We can be both throttled and !queued. Replenish the counter
1267 	 * but do not enqueue -- wait for our wakeup to do that.
1268 	 */
1269 	if (!task_on_rq_queued(p)) {
1270 		replenish_dl_entity(dl_se);
1271 		goto unlock;
1272 	}
1273 
1274 	if (unlikely(!rq->online)) {
1275 		/*
1276 		 * If the runqueue is no longer available, migrate the
1277 		 * task elsewhere. This necessarily changes rq.
1278 		 */
1279 		lockdep_unpin_lock(__rq_lockp(rq), rf.cookie);
1280 		rq = dl_task_offline_migration(rq, p);
1281 		rf.cookie = lockdep_pin_lock(__rq_lockp(rq));
1282 		update_rq_clock(rq);
1283 
1284 		/*
1285 		 * Now that the task has been migrated to the new RQ and we
1286 		 * have that locked, proceed as normal and enqueue the task
1287 		 * there.
1288 		 */
1289 	}
1290 
1291 	enqueue_task_dl(rq, p, ENQUEUE_REPLENISH);
1292 	if (dl_task(rq->donor))
1293 		wakeup_preempt_dl(rq, p, 0);
1294 	else
1295 		resched_curr(rq);
1296 
1297 	__push_dl_task(rq, &rf);
1298 
1299 unlock:
1300 	task_rq_unlock(rq, p, &rf);
1301 
1302 	/*
1303 	 * This can free the task_struct, including this hrtimer, do not touch
1304 	 * anything related to that after this.
1305 	 */
1306 	put_task_struct(p);
1307 
1308 	return HRTIMER_NORESTART;
1309 }
1310 
init_dl_task_timer(struct sched_dl_entity * dl_se)1311 static void init_dl_task_timer(struct sched_dl_entity *dl_se)
1312 {
1313 	struct hrtimer *timer = &dl_se->dl_timer;
1314 
1315 	hrtimer_setup(timer, dl_task_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
1316 }
1317 
1318 /*
1319  * During the activation, CBS checks if it can reuse the current task's
1320  * runtime and period. If the deadline of the task is in the past, CBS
1321  * cannot use the runtime, and so it replenishes the task. This rule
1322  * works fine for implicit deadline tasks (deadline == period), and the
1323  * CBS was designed for implicit deadline tasks. However, a task with
1324  * constrained deadline (deadline < period) might be awakened after the
1325  * deadline, but before the next period. In this case, replenishing the
1326  * task would allow it to run for runtime / deadline. As in this case
1327  * deadline < period, CBS enables a task to run for more than the
1328  * runtime / period. In a very loaded system, this can cause a domino
1329  * effect, making other tasks miss their deadlines.
1330  *
1331  * To avoid this problem, in the activation of a constrained deadline
1332  * task after the deadline but before the next period, throttle the
1333  * task and set the replenishing timer to the begin of the next period,
1334  * unless it is boosted.
1335  */
dl_check_constrained_dl(struct sched_dl_entity * dl_se)1336 static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
1337 {
1338 	struct rq *rq = rq_of_dl_se(dl_se);
1339 
1340 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) &&
1341 	    dl_time_before(rq_clock(rq), dl_next_period(dl_se))) {
1342 		if (unlikely(is_dl_boosted(dl_se) || !start_dl_timer(dl_se)))
1343 			return;
1344 		dl_se->dl_throttled = 1;
1345 		if (dl_se->runtime > 0)
1346 			dl_se->runtime = 0;
1347 	}
1348 }
1349 
1350 static
dl_runtime_exceeded(struct sched_dl_entity * dl_se)1351 int dl_runtime_exceeded(struct sched_dl_entity *dl_se)
1352 {
1353 	return (dl_se->runtime <= 0);
1354 }
1355 
1356 /*
1357  * This function implements the GRUB accounting rule. According to the
1358  * GRUB reclaiming algorithm, the runtime is not decreased as "dq = -dt",
1359  * but as "dq = -(max{u, (Umax - Uinact - Uextra)} / Umax) dt",
1360  * where u is the utilization of the task, Umax is the maximum reclaimable
1361  * utilization, Uinact is the (per-runqueue) inactive utilization, computed
1362  * as the difference between the "total runqueue utilization" and the
1363  * "runqueue active utilization", and Uextra is the (per runqueue) extra
1364  * reclaimable utilization.
1365  * Since rq->dl.running_bw and rq->dl.this_bw contain utilizations multiplied
1366  * by 2^BW_SHIFT, the result has to be shifted right by BW_SHIFT.
1367  * Since rq->dl.bw_ratio contains 1 / Umax multiplied by 2^RATIO_SHIFT, dl_bw
1368  * is multiplied by rq->dl.bw_ratio and shifted right by RATIO_SHIFT.
1369  * Since delta is a 64 bit variable, to have an overflow its value should be
1370  * larger than 2^(64 - 20 - 8), which is more than 64 seconds. So, overflow is
1371  * not an issue here.
1372  */
grub_reclaim(u64 delta,struct rq * rq,struct sched_dl_entity * dl_se)1373 static u64 grub_reclaim(u64 delta, struct rq *rq, struct sched_dl_entity *dl_se)
1374 {
1375 	u64 u_act;
1376 	u64 u_inact = rq->dl.this_bw - rq->dl.running_bw; /* Utot - Uact */
1377 
1378 	/*
1379 	 * Instead of computing max{u, (u_max - u_inact - u_extra)}, we
1380 	 * compare u_inact + u_extra with u_max - u, because u_inact + u_extra
1381 	 * can be larger than u_max. So, u_max - u_inact - u_extra would be
1382 	 * negative leading to wrong results.
1383 	 */
1384 	if (u_inact + rq->dl.extra_bw > rq->dl.max_bw - dl_se->dl_bw)
1385 		u_act = dl_se->dl_bw;
1386 	else
1387 		u_act = rq->dl.max_bw - u_inact - rq->dl.extra_bw;
1388 
1389 	u_act = (u_act * rq->dl.bw_ratio) >> RATIO_SHIFT;
1390 	return (delta * u_act) >> BW_SHIFT;
1391 }
1392 
dl_scaled_delta_exec(struct rq * rq,struct sched_dl_entity * dl_se,s64 delta_exec)1393 s64 dl_scaled_delta_exec(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta_exec)
1394 {
1395 	s64 scaled_delta_exec;
1396 
1397 	/*
1398 	 * For tasks that participate in GRUB, we implement GRUB-PA: the
1399 	 * spare reclaimed bandwidth is used to clock down frequency.
1400 	 *
1401 	 * For the others, we still need to scale reservation parameters
1402 	 * according to current frequency and CPU maximum capacity.
1403 	 */
1404 	if (unlikely(dl_se->flags & SCHED_FLAG_RECLAIM)) {
1405 		scaled_delta_exec = grub_reclaim(delta_exec, rq, dl_se);
1406 	} else {
1407 		int cpu = cpu_of(rq);
1408 		unsigned long scale_freq = arch_scale_freq_capacity(cpu);
1409 		unsigned long scale_cpu = arch_scale_cpu_capacity(cpu);
1410 
1411 		scaled_delta_exec = cap_scale(delta_exec, scale_freq);
1412 		scaled_delta_exec = cap_scale(scaled_delta_exec, scale_cpu);
1413 	}
1414 
1415 	return scaled_delta_exec;
1416 }
1417 
1418 static inline void
1419 update_stats_dequeue_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se, int flags);
1420 
update_curr_dl_se(struct rq * rq,struct sched_dl_entity * dl_se,s64 delta_exec)1421 static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta_exec)
1422 {
1423 	bool idle = rq->curr == rq->idle;
1424 	s64 scaled_delta_exec;
1425 
1426 	if (unlikely(delta_exec <= 0)) {
1427 		if (unlikely(dl_se->dl_yielded))
1428 			goto throttle;
1429 		return;
1430 	}
1431 
1432 	if (dl_server(dl_se) && dl_se->dl_throttled && !dl_se->dl_defer)
1433 		return;
1434 
1435 	if (dl_entity_is_special(dl_se))
1436 		return;
1437 
1438 	scaled_delta_exec = delta_exec;
1439 	if (!dl_server(dl_se))
1440 		scaled_delta_exec = dl_scaled_delta_exec(rq, dl_se, delta_exec);
1441 
1442 	dl_se->runtime -= scaled_delta_exec;
1443 
1444 	if (dl_se->dl_defer_idle && !idle)
1445 		dl_se->dl_defer_idle = 0;
1446 
1447 	/*
1448 	 * The fair server can consume its runtime while throttled (not queued/
1449 	 * running as regular CFS).
1450 	 *
1451 	 * If the server consumes its entire runtime in this state. The server
1452 	 * is not required for the current period. Thus, reset the server by
1453 	 * starting a new period, pushing the activation.
1454 	 */
1455 	if (dl_se->dl_defer && dl_se->dl_throttled && dl_runtime_exceeded(dl_se)) {
1456 		/*
1457 		 * Non-servers would never get time accounted while throttled.
1458 		 */
1459 		WARN_ON_ONCE(!dl_server(dl_se));
1460 
1461 		/*
1462 		 * While the server is marked idle, do not push out the
1463 		 * activation further, instead wait for the period timer
1464 		 * to lapse and stop the server.
1465 		 */
1466 		if (dl_se->dl_defer_idle && idle) {
1467 			/*
1468 			 * The timer is at the zero-laxity point, this means
1469 			 * dl_server_stop() / dl_server_start() can happen
1470 			 * while now < deadline. This means update_dl_entity()
1471 			 * will not replenish. Additionally start_dl_timer()
1472 			 * will be set for 'deadline - runtime'. Negative
1473 			 * runtime will not do.
1474 			 */
1475 			dl_se->runtime = 0;
1476 			return;
1477 		}
1478 
1479 		/*
1480 		 * If the server was previously activated - the starving condition
1481 		 * took place, it this point it went away because the fair scheduler
1482 		 * was able to get runtime in background. So return to the initial
1483 		 * state.
1484 		 */
1485 		dl_se->dl_defer_running = 0;
1486 
1487 		hrtimer_try_to_cancel(&dl_se->dl_timer);
1488 
1489 		replenish_dl_new_period(dl_se, dl_se->rq);
1490 
1491 		if (idle)
1492 			dl_se->dl_defer_idle = 1;
1493 
1494 		/*
1495 		 * Not being able to start the timer seems problematic. If it could not
1496 		 * be started for whatever reason, we need to "unthrottle" the DL server
1497 		 * and queue right away. Otherwise nothing might queue it. That's similar
1498 		 * to what enqueue_dl_entity() does on start_dl_timer==0. For now, just warn.
1499 		 */
1500 		WARN_ON_ONCE(!start_dl_timer(dl_se));
1501 
1502 		return;
1503 	}
1504 
1505 throttle:
1506 	if (dl_runtime_exceeded(dl_se) || dl_se->dl_yielded) {
1507 		dl_se->dl_throttled = 1;
1508 
1509 		/* If requested, inform the user about runtime overruns. */
1510 		if (dl_runtime_exceeded(dl_se) &&
1511 		    (dl_se->flags & SCHED_FLAG_DL_OVERRUN))
1512 			dl_se->dl_overrun = 1;
1513 
1514 		dequeue_dl_entity(dl_se, 0);
1515 		if (!dl_server(dl_se)) {
1516 			update_stats_dequeue_dl(&rq->dl, dl_se, 0);
1517 			dequeue_pushable_dl_task(rq, dl_task_of(dl_se));
1518 		}
1519 
1520 		if (unlikely(is_dl_boosted(dl_se) || !start_dl_timer(dl_se))) {
1521 			if (dl_server(dl_se)) {
1522 				replenish_dl_new_period(dl_se, rq);
1523 				start_dl_timer(dl_se);
1524 			} else {
1525 				enqueue_task_dl(rq, dl_task_of(dl_se), ENQUEUE_REPLENISH);
1526 			}
1527 		}
1528 
1529 		if (!is_leftmost(dl_se, &rq->dl))
1530 			resched_curr(rq);
1531 	}
1532 
1533 	/*
1534 	 * The fair server (sole dl_server) does not account for real-time
1535 	 * workload because it is running fair work.
1536 	 */
1537 	if (dl_se == &rq->fair_server)
1538 		return;
1539 
1540 #ifdef CONFIG_RT_GROUP_SCHED
1541 	/*
1542 	 * Because -- for now -- we share the rt bandwidth, we need to
1543 	 * account our runtime there too, otherwise actual rt tasks
1544 	 * would be able to exceed the shared quota.
1545 	 *
1546 	 * Account to the root rt group for now.
1547 	 *
1548 	 * The solution we're working towards is having the RT groups scheduled
1549 	 * using deadline servers -- however there's a few nasties to figure
1550 	 * out before that can happen.
1551 	 */
1552 	if (rt_bandwidth_enabled()) {
1553 		struct rt_rq *rt_rq = &rq->rt;
1554 
1555 		raw_spin_lock(&rt_rq->rt_runtime_lock);
1556 		/*
1557 		 * We'll let actual RT tasks worry about the overflow here, we
1558 		 * have our own CBS to keep us inline; only account when RT
1559 		 * bandwidth is relevant.
1560 		 */
1561 		if (sched_rt_bandwidth_account(rt_rq))
1562 			rt_rq->rt_time += delta_exec;
1563 		raw_spin_unlock(&rt_rq->rt_runtime_lock);
1564 	}
1565 #endif /* CONFIG_RT_GROUP_SCHED */
1566 }
1567 
1568 /*
1569  * In the non-defer mode, the idle time is not accounted, as the
1570  * server provides a guarantee.
1571  *
1572  * If the dl_server is in defer mode, the idle time is also considered
1573  * as time available for the fair server, avoiding a penalty for the
1574  * rt scheduler that did not consumed that time.
1575  */
dl_server_update_idle(struct sched_dl_entity * dl_se,s64 delta_exec)1576 void dl_server_update_idle(struct sched_dl_entity *dl_se, s64 delta_exec)
1577 {
1578 	if (dl_se->dl_server_active && dl_se->dl_runtime && dl_se->dl_defer)
1579 		update_curr_dl_se(dl_se->rq, dl_se, delta_exec);
1580 }
1581 
dl_server_update(struct sched_dl_entity * dl_se,s64 delta_exec)1582 void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec)
1583 {
1584 	/* 0 runtime = fair server disabled */
1585 	if (dl_se->dl_server_active && dl_se->dl_runtime)
1586 		update_curr_dl_se(dl_se->rq, dl_se, delta_exec);
1587 }
1588 
1589 /*
1590  * dl_server && dl_defer:
1591  *
1592  *                                        6
1593  *                            +--------------------+
1594  *                            v                    |
1595  *     +-------------+  4   +-----------+  5     +------------------+
1596  * +-> |   A:init    | <--- | D:running | -----> | E:replenish-wait |
1597  * |   +-------------+      +-----------+        +------------------+
1598  * |     |         |    1     ^    ^               |
1599  * |     | 1       +----------+    | 3             |
1600  * |     v                         |               |
1601  * |   +--------------------------------+   2      |
1602  * |   |                                | ----+    |
1603  * | 8 |       B:zero_laxity-wait       |     |    |
1604  * |   |                                | <---+    |
1605  * |   +--------------------------------+          |
1606  * |     |              ^     ^           2        |
1607  * |     | 7            | 2   +--------------------+
1608  * |     v              |
1609  * |   +-------------+  |
1610  * +-- | C:idle-wait | -+
1611  *     +-------------+
1612  *       ^ 7       |
1613  *       +---------+
1614  *
1615  *
1616  * [A] - init
1617  *   dl_server_active = 0
1618  *   dl_throttled = 0
1619  *   dl_defer_armed = 0
1620  *   dl_defer_running = 0/1
1621  *   dl_defer_idle = 0
1622  *
1623  * [B] - zero_laxity-wait
1624  *   dl_server_active = 1
1625  *   dl_throttled = 1
1626  *   dl_defer_armed = 1
1627  *   dl_defer_running = 0
1628  *   dl_defer_idle = 0
1629  *
1630  * [C] - idle-wait
1631  *   dl_server_active = 1
1632  *   dl_throttled = 1
1633  *   dl_defer_armed = 1
1634  *   dl_defer_running = 0
1635  *   dl_defer_idle = 1
1636  *
1637  * [D] - running
1638  *   dl_server_active = 1
1639  *   dl_throttled = 0
1640  *   dl_defer_armed = 0
1641  *   dl_defer_running = 1
1642  *   dl_defer_idle = 0
1643  *
1644  * [E] - replenish-wait
1645  *   dl_server_active = 1
1646  *   dl_throttled = 1
1647  *   dl_defer_armed = 0
1648  *   dl_defer_running = 1
1649  *   dl_defer_idle = 0
1650  *
1651  *
1652  * [1] A->B, A->D
1653  * dl_server_start()
1654  *   dl_server_active = 1;
1655  *   enqueue_dl_entity()
1656  *     update_dl_entity(WAKEUP)
1657  *       if (!dl_defer_running)
1658  *         dl_defer_armed = 1;
1659  *         dl_throttled = 1;
1660  *     if (dl_throttled && start_dl_timer())
1661  *       return; // [B]
1662  *     __enqueue_dl_entity();
1663  *     // [D]
1664  *
1665  * // deplete server runtime from client-class
1666  * [2] B->B, C->B, E->B
1667  * dl_server_update()
1668  *   update_curr_dl_se() // idle = false
1669  *     if (dl_defer_idle)
1670  *       dl_defer_idle = 0;
1671  *     if (dl_defer && dl_throttled && dl_runtime_exceeded())
1672  *       dl_defer_running = 0;
1673  *       hrtimer_try_to_cancel();   // stop timer
1674  *       replenish_dl_new_period()
1675  *         // fwd period
1676  *         dl_throttled = 1;
1677  *         dl_defer_armed = 1;
1678  *       start_dl_timer();        // restart timer
1679  *       // [B]
1680  *
1681  * // timer actually fires means we have runtime
1682  * [3] B->D
1683  * dl_server_timer()
1684  *   if (dl_defer_armed)
1685  *     dl_defer_running = 1;
1686  *   enqueue_dl_entity(REPLENISH)
1687  *     replenish_dl_entity()
1688  *       // fwd period
1689  *       if (dl_throttled)
1690  *         dl_throttled = 0;
1691  *       if (dl_defer_armed)
1692  *         dl_defer_armed = 0;
1693  *     __enqueue_dl_entity();
1694  *     // [D]
1695  *
1696  * // schedule server
1697  * [4] D->A
1698  * pick_task_dl()
1699  *   p = server_pick_task();
1700  *   if (!p)
1701  *     dl_server_stop()
1702  *       dequeue_dl_entity();
1703  *       hrtimer_try_to_cancel();
1704  *       dl_defer_armed = 0;
1705  *       dl_throttled = 0;
1706  *       dl_server_active = 0;
1707  *       // [A]
1708  *   return p;
1709  *
1710  * // server running
1711  * [5] D->E
1712  * update_curr_dl_se()
1713  *   if (dl_runtime_exceeded())
1714  *     dl_throttled = 1;
1715  *     dequeue_dl_entity();
1716  *     start_dl_timer();
1717  *     // [E]
1718  *
1719  * // server replenished
1720  * [6] E->D
1721  * dl_server_timer()
1722  *   enqueue_dl_entity(REPLENISH)
1723  *     replenish_dl_entity()
1724  *       fwd-period
1725  *       if (dl_throttled)
1726  *         dl_throttled = 0;
1727  *     __enqueue_dl_entity();
1728  *     // [D]
1729  *
1730  * // deplete server runtime from idle
1731  * [7] B->C, C->C
1732  * dl_server_update_idle()
1733  *   update_curr_dl_se() // idle = true
1734  *     if (dl_defer && dl_throttled && dl_runtime_exceeded())
1735  *       if (dl_defer_idle)
1736  *         return;
1737  *       dl_defer_running = 0;
1738  *       hrtimer_try_to_cancel();
1739  *       replenish_dl_new_period()
1740  *         // fwd period
1741  *         dl_throttled = 1;
1742  *         dl_defer_armed = 1;
1743  *       dl_defer_idle = 1;
1744  *       start_dl_timer();        // restart timer
1745  *       // [C]
1746  *
1747  * // stop idle server
1748  * [8] C->A
1749  * dl_server_timer()
1750  *   if (dl_defer_idle)
1751  *     dl_server_stop();
1752  *     // [A]
1753  *
1754  *
1755  * digraph dl_server {
1756  *   "A:init" -> "B:zero_laxity-wait"             [label="1:dl_server_start"]
1757  *   "A:init" -> "D:running"                      [label="1:dl_server_start"]
1758  *   "B:zero_laxity-wait" -> "B:zero_laxity-wait" [label="2:dl_server_update"]
1759  *   "B:zero_laxity-wait" -> "C:idle-wait"        [label="7:dl_server_update_idle"]
1760  *   "B:zero_laxity-wait" -> "D:running"          [label="3:dl_server_timer"]
1761  *   "C:idle-wait" -> "A:init"                    [label="8:dl_server_timer"]
1762  *   "C:idle-wait" -> "B:zero_laxity-wait"        [label="2:dl_server_update"]
1763  *   "C:idle-wait" -> "C:idle-wait"               [label="7:dl_server_update_idle"]
1764  *   "D:running" -> "A:init"                      [label="4:pick_task_dl"]
1765  *   "D:running" -> "E:replenish-wait"            [label="5:update_curr_dl_se"]
1766  *   "E:replenish-wait" -> "B:zero_laxity-wait"   [label="2:dl_server_update"]
1767  *   "E:replenish-wait" -> "D:running"            [label="6:dl_server_timer"]
1768  * }
1769  *
1770  *
1771  * Notes:
1772  *
1773  *  - When there are fair tasks running the most likely loop is [2]->[2].
1774  *    the dl_server never actually runs, the timer never fires.
1775  *
1776  *  - When there is actual fair starvation; the timer fires and starts the
1777  *    dl_server. This will then throttle and replenish like a normal DL
1778  *    task. Notably it will not 'defer' again.
1779  *
1780  *  - When idle it will push the actication forward once, and then wait
1781  *    for the timer to hit or a non-idle update to restart things.
1782  */
dl_server_start(struct sched_dl_entity * dl_se)1783 void dl_server_start(struct sched_dl_entity *dl_se)
1784 {
1785 	struct rq *rq = dl_se->rq;
1786 
1787 	if (!dl_server(dl_se) || dl_se->dl_server_active)
1788 		return;
1789 
1790 	/*
1791 	 * Update the current task to 'now'.
1792 	 */
1793 	rq->donor->sched_class->update_curr(rq);
1794 
1795 	if (WARN_ON_ONCE(!cpu_online(cpu_of(rq))))
1796 		return;
1797 
1798 	dl_se->dl_server_active = 1;
1799 	enqueue_dl_entity(dl_se, ENQUEUE_WAKEUP);
1800 	if (!dl_task(dl_se->rq->curr) || dl_entity_preempt(dl_se, &rq->curr->dl))
1801 		resched_curr(dl_se->rq);
1802 }
1803 
dl_server_stop(struct sched_dl_entity * dl_se)1804 void dl_server_stop(struct sched_dl_entity *dl_se)
1805 {
1806 	if (!dl_server(dl_se) || !dl_server_active(dl_se))
1807 		return;
1808 
1809 	dequeue_dl_entity(dl_se, DEQUEUE_SLEEP);
1810 	hrtimer_try_to_cancel(&dl_se->dl_timer);
1811 	dl_se->dl_defer_armed = 0;
1812 	dl_se->dl_throttled = 0;
1813 	dl_se->dl_defer_idle = 0;
1814 	dl_se->dl_server_active = 0;
1815 }
1816 
dl_server_init(struct sched_dl_entity * dl_se,struct rq * rq,dl_server_pick_f pick_task)1817 void dl_server_init(struct sched_dl_entity *dl_se, struct rq *rq,
1818 		    dl_server_pick_f pick_task)
1819 {
1820 	dl_se->rq = rq;
1821 	dl_se->server_pick_task = pick_task;
1822 }
1823 
sched_init_dl_servers(void)1824 void sched_init_dl_servers(void)
1825 {
1826 	int cpu;
1827 	struct rq *rq;
1828 	struct sched_dl_entity *dl_se;
1829 
1830 	for_each_online_cpu(cpu) {
1831 		u64 runtime =  50 * NSEC_PER_MSEC;
1832 		u64 period = 1000 * NSEC_PER_MSEC;
1833 
1834 		rq = cpu_rq(cpu);
1835 
1836 		guard(rq_lock_irq)(rq);
1837 
1838 		dl_se = &rq->fair_server;
1839 
1840 		WARN_ON(dl_server(dl_se));
1841 
1842 		dl_server_apply_params(dl_se, runtime, period, 1);
1843 
1844 		dl_se->dl_server = 1;
1845 		dl_se->dl_defer = 1;
1846 		setup_new_dl_entity(dl_se);
1847 	}
1848 }
1849 
__dl_server_attach_root(struct sched_dl_entity * dl_se,struct rq * rq)1850 void __dl_server_attach_root(struct sched_dl_entity *dl_se, struct rq *rq)
1851 {
1852 	u64 new_bw = dl_se->dl_bw;
1853 	int cpu = cpu_of(rq);
1854 	struct dl_bw *dl_b;
1855 
1856 	dl_b = dl_bw_of(cpu_of(rq));
1857 	guard(raw_spinlock)(&dl_b->lock);
1858 
1859 	if (!dl_bw_cpus(cpu))
1860 		return;
1861 
1862 	__dl_add(dl_b, new_bw, dl_bw_cpus(cpu));
1863 }
1864 
dl_server_apply_params(struct sched_dl_entity * dl_se,u64 runtime,u64 period,bool init)1865 int dl_server_apply_params(struct sched_dl_entity *dl_se, u64 runtime, u64 period, bool init)
1866 {
1867 	u64 old_bw = init ? 0 : to_ratio(dl_se->dl_period, dl_se->dl_runtime);
1868 	u64 new_bw = to_ratio(period, runtime);
1869 	struct rq *rq = dl_se->rq;
1870 	int cpu = cpu_of(rq);
1871 	struct dl_bw *dl_b;
1872 	unsigned long cap;
1873 	int retval = 0;
1874 	int cpus;
1875 
1876 	dl_b = dl_bw_of(cpu);
1877 	guard(raw_spinlock)(&dl_b->lock);
1878 
1879 	cpus = dl_bw_cpus(cpu);
1880 	cap = dl_bw_capacity(cpu);
1881 
1882 	if (__dl_overflow(dl_b, cap, old_bw, new_bw))
1883 		return -EBUSY;
1884 
1885 	if (init) {
1886 		__add_rq_bw(new_bw, &rq->dl);
1887 		__dl_add(dl_b, new_bw, cpus);
1888 	} else {
1889 		__dl_sub(dl_b, dl_se->dl_bw, cpus);
1890 		__dl_add(dl_b, new_bw, cpus);
1891 
1892 		dl_rq_change_utilization(rq, dl_se, new_bw);
1893 	}
1894 
1895 	dl_se->dl_runtime = runtime;
1896 	dl_se->dl_deadline = period;
1897 	dl_se->dl_period = period;
1898 
1899 	dl_se->runtime = 0;
1900 	dl_se->deadline = 0;
1901 
1902 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
1903 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
1904 
1905 	return retval;
1906 }
1907 
1908 /*
1909  * Update the current task's runtime statistics (provided it is still
1910  * a -deadline task and has not been removed from the dl_rq).
1911  */
update_curr_dl(struct rq * rq)1912 static void update_curr_dl(struct rq *rq)
1913 {
1914 	struct task_struct *donor = rq->donor;
1915 	struct sched_dl_entity *dl_se = &donor->dl;
1916 	s64 delta_exec;
1917 
1918 	if (!dl_task(donor) || !on_dl_rq(dl_se))
1919 		return;
1920 
1921 	/*
1922 	 * Consumed budget is computed considering the time as
1923 	 * observed by schedulable tasks (excluding time spent
1924 	 * in hardirq context, etc.). Deadlines are instead
1925 	 * computed using hard walltime. This seems to be the more
1926 	 * natural solution, but the full ramifications of this
1927 	 * approach need further study.
1928 	 */
1929 	delta_exec = update_curr_common(rq);
1930 	update_curr_dl_se(rq, dl_se, delta_exec);
1931 }
1932 
inactive_task_timer(struct hrtimer * timer)1933 static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
1934 {
1935 	struct sched_dl_entity *dl_se = container_of(timer,
1936 						     struct sched_dl_entity,
1937 						     inactive_timer);
1938 	struct task_struct *p = NULL;
1939 	struct rq_flags rf;
1940 	struct rq *rq;
1941 
1942 	if (!dl_server(dl_se)) {
1943 		p = dl_task_of(dl_se);
1944 		rq = task_rq_lock(p, &rf);
1945 	} else {
1946 		rq = dl_se->rq;
1947 		rq_lock(rq, &rf);
1948 	}
1949 
1950 	sched_clock_tick();
1951 	update_rq_clock(rq);
1952 
1953 	if (dl_server(dl_se))
1954 		goto no_task;
1955 
1956 	if (!dl_task(p) || READ_ONCE(p->__state) == TASK_DEAD) {
1957 		struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
1958 
1959 		if (READ_ONCE(p->__state) == TASK_DEAD && dl_se->dl_non_contending) {
1960 			sub_running_bw(&p->dl, dl_rq_of_se(&p->dl));
1961 			sub_rq_bw(&p->dl, dl_rq_of_se(&p->dl));
1962 			dl_se->dl_non_contending = 0;
1963 		}
1964 
1965 		raw_spin_lock(&dl_b->lock);
1966 		__dl_sub(dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
1967 		raw_spin_unlock(&dl_b->lock);
1968 		__dl_clear_params(dl_se);
1969 
1970 		goto unlock;
1971 	}
1972 
1973 no_task:
1974 	if (dl_se->dl_non_contending == 0)
1975 		goto unlock;
1976 
1977 	sub_running_bw(dl_se, &rq->dl);
1978 	dl_se->dl_non_contending = 0;
1979 unlock:
1980 
1981 	if (!dl_server(dl_se)) {
1982 		task_rq_unlock(rq, p, &rf);
1983 		put_task_struct(p);
1984 	} else {
1985 		rq_unlock(rq, &rf);
1986 	}
1987 
1988 	return HRTIMER_NORESTART;
1989 }
1990 
init_dl_inactive_task_timer(struct sched_dl_entity * dl_se)1991 static void init_dl_inactive_task_timer(struct sched_dl_entity *dl_se)
1992 {
1993 	struct hrtimer *timer = &dl_se->inactive_timer;
1994 
1995 	hrtimer_setup(timer, inactive_task_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
1996 }
1997 
1998 #define __node_2_dle(node) \
1999 	rb_entry((node), struct sched_dl_entity, rb_node)
2000 
inc_dl_deadline(struct dl_rq * dl_rq,u64 deadline)2001 static void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
2002 {
2003 	struct rq *rq = rq_of_dl_rq(dl_rq);
2004 
2005 	if (dl_rq->earliest_dl.curr == 0 ||
2006 	    dl_time_before(deadline, dl_rq->earliest_dl.curr)) {
2007 		if (dl_rq->earliest_dl.curr == 0)
2008 			cpupri_set(&rq->rd->cpupri, rq->cpu, CPUPRI_HIGHER);
2009 		dl_rq->earliest_dl.curr = deadline;
2010 		cpudl_set(&rq->rd->cpudl, rq->cpu, deadline);
2011 	}
2012 }
2013 
dec_dl_deadline(struct dl_rq * dl_rq,u64 deadline)2014 static void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
2015 {
2016 	struct rq *rq = rq_of_dl_rq(dl_rq);
2017 
2018 	/*
2019 	 * Since we may have removed our earliest (and/or next earliest)
2020 	 * task we must recompute them.
2021 	 */
2022 	if (!dl_rq->dl_nr_running) {
2023 		dl_rq->earliest_dl.curr = 0;
2024 		dl_rq->earliest_dl.next = 0;
2025 		cpudl_clear(&rq->rd->cpudl, rq->cpu, rq->online);
2026 		cpupri_set(&rq->rd->cpupri, rq->cpu, rq->rt.highest_prio.curr);
2027 	} else {
2028 		struct rb_node *leftmost = rb_first_cached(&dl_rq->root);
2029 		struct sched_dl_entity *entry = __node_2_dle(leftmost);
2030 
2031 		dl_rq->earliest_dl.curr = entry->deadline;
2032 		cpudl_set(&rq->rd->cpudl, rq->cpu, entry->deadline);
2033 	}
2034 }
2035 
2036 static inline
inc_dl_tasks(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)2037 void inc_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
2038 {
2039 	u64 deadline = dl_se->deadline;
2040 
2041 	dl_rq->dl_nr_running++;
2042 
2043 	if (!dl_server(dl_se))
2044 		add_nr_running(rq_of_dl_rq(dl_rq), 1);
2045 
2046 	inc_dl_deadline(dl_rq, deadline);
2047 }
2048 
2049 static inline
dec_dl_tasks(struct sched_dl_entity * dl_se,struct dl_rq * dl_rq)2050 void dec_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
2051 {
2052 	WARN_ON(!dl_rq->dl_nr_running);
2053 	dl_rq->dl_nr_running--;
2054 
2055 	if (!dl_server(dl_se))
2056 		sub_nr_running(rq_of_dl_rq(dl_rq), 1);
2057 
2058 	dec_dl_deadline(dl_rq, dl_se->deadline);
2059 }
2060 
__dl_less(struct rb_node * a,const struct rb_node * b)2061 static inline bool __dl_less(struct rb_node *a, const struct rb_node *b)
2062 {
2063 	return dl_time_before(__node_2_dle(a)->deadline, __node_2_dle(b)->deadline);
2064 }
2065 
2066 static __always_inline struct sched_statistics *
__schedstats_from_dl_se(struct sched_dl_entity * dl_se)2067 __schedstats_from_dl_se(struct sched_dl_entity *dl_se)
2068 {
2069 	if (!schedstat_enabled())
2070 		return NULL;
2071 
2072 	if (dl_server(dl_se))
2073 		return NULL;
2074 
2075 	return &dl_task_of(dl_se)->stats;
2076 }
2077 
2078 static inline void
update_stats_wait_start_dl(struct dl_rq * dl_rq,struct sched_dl_entity * dl_se)2079 update_stats_wait_start_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se)
2080 {
2081 	struct sched_statistics *stats = __schedstats_from_dl_se(dl_se);
2082 	if (stats)
2083 		__update_stats_wait_start(rq_of_dl_rq(dl_rq), dl_task_of(dl_se), stats);
2084 }
2085 
2086 static inline void
update_stats_wait_end_dl(struct dl_rq * dl_rq,struct sched_dl_entity * dl_se)2087 update_stats_wait_end_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se)
2088 {
2089 	struct sched_statistics *stats = __schedstats_from_dl_se(dl_se);
2090 	if (stats)
2091 		__update_stats_wait_end(rq_of_dl_rq(dl_rq), dl_task_of(dl_se), stats);
2092 }
2093 
2094 static inline void
update_stats_enqueue_sleeper_dl(struct dl_rq * dl_rq,struct sched_dl_entity * dl_se)2095 update_stats_enqueue_sleeper_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se)
2096 {
2097 	struct sched_statistics *stats = __schedstats_from_dl_se(dl_se);
2098 	if (stats)
2099 		__update_stats_enqueue_sleeper(rq_of_dl_rq(dl_rq), dl_task_of(dl_se), stats);
2100 }
2101 
2102 static inline void
update_stats_enqueue_dl(struct dl_rq * dl_rq,struct sched_dl_entity * dl_se,int flags)2103 update_stats_enqueue_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se,
2104 			int flags)
2105 {
2106 	if (!schedstat_enabled())
2107 		return;
2108 
2109 	if (flags & ENQUEUE_WAKEUP)
2110 		update_stats_enqueue_sleeper_dl(dl_rq, dl_se);
2111 }
2112 
2113 static inline void
update_stats_dequeue_dl(struct dl_rq * dl_rq,struct sched_dl_entity * dl_se,int flags)2114 update_stats_dequeue_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se,
2115 			int flags)
2116 {
2117 	struct task_struct *p = dl_task_of(dl_se);
2118 
2119 	if (!schedstat_enabled())
2120 		return;
2121 
2122 	if ((flags & DEQUEUE_SLEEP)) {
2123 		unsigned int state;
2124 
2125 		state = READ_ONCE(p->__state);
2126 		if (state & TASK_INTERRUPTIBLE)
2127 			__schedstat_set(p->stats.sleep_start,
2128 					rq_clock(rq_of_dl_rq(dl_rq)));
2129 
2130 		if (state & TASK_UNINTERRUPTIBLE)
2131 			__schedstat_set(p->stats.block_start,
2132 					rq_clock(rq_of_dl_rq(dl_rq)));
2133 	}
2134 }
2135 
__enqueue_dl_entity(struct sched_dl_entity * dl_se)2136 static void __enqueue_dl_entity(struct sched_dl_entity *dl_se)
2137 {
2138 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
2139 
2140 	WARN_ON_ONCE(!RB_EMPTY_NODE(&dl_se->rb_node));
2141 
2142 	rb_add_cached(&dl_se->rb_node, &dl_rq->root, __dl_less);
2143 
2144 	inc_dl_tasks(dl_se, dl_rq);
2145 }
2146 
__dequeue_dl_entity(struct sched_dl_entity * dl_se)2147 static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
2148 {
2149 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
2150 
2151 	if (RB_EMPTY_NODE(&dl_se->rb_node))
2152 		return;
2153 
2154 	rb_erase_cached(&dl_se->rb_node, &dl_rq->root);
2155 
2156 	RB_CLEAR_NODE(&dl_se->rb_node);
2157 
2158 	dec_dl_tasks(dl_se, dl_rq);
2159 }
2160 
2161 static void
enqueue_dl_entity(struct sched_dl_entity * dl_se,int flags)2162 enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
2163 {
2164 	WARN_ON_ONCE(on_dl_rq(dl_se));
2165 
2166 	update_stats_enqueue_dl(dl_rq_of_se(dl_se), dl_se, flags);
2167 
2168 	/*
2169 	 * Check if a constrained deadline task was activated
2170 	 * after the deadline but before the next period.
2171 	 * If that is the case, the task will be throttled and
2172 	 * the replenishment timer will be set to the next period.
2173 	 */
2174 	if (!dl_se->dl_throttled && !dl_is_implicit(dl_se))
2175 		dl_check_constrained_dl(dl_se);
2176 
2177 	if (flags & (ENQUEUE_RESTORE|ENQUEUE_MIGRATING)) {
2178 		struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
2179 
2180 		add_rq_bw(dl_se, dl_rq);
2181 		add_running_bw(dl_se, dl_rq);
2182 	}
2183 
2184 	/*
2185 	 * If p is throttled, we do not enqueue it. In fact, if it exhausted
2186 	 * its budget it needs a replenishment and, since it now is on
2187 	 * its rq, the bandwidth timer callback (which clearly has not
2188 	 * run yet) will take care of this.
2189 	 * However, the active utilization does not depend on the fact
2190 	 * that the task is on the runqueue or not (but depends on the
2191 	 * task's state - in GRUB parlance, "inactive" vs "active contending").
2192 	 * In other words, even if a task is throttled its utilization must
2193 	 * be counted in the active utilization; hence, we need to call
2194 	 * add_running_bw().
2195 	 */
2196 	if (!dl_se->dl_defer && dl_se->dl_throttled && !(flags & ENQUEUE_REPLENISH)) {
2197 		if (flags & ENQUEUE_WAKEUP)
2198 			task_contending(dl_se, flags);
2199 
2200 		return;
2201 	}
2202 
2203 	/*
2204 	 * If this is a wakeup or a new instance, the scheduling
2205 	 * parameters of the task might need updating. Otherwise,
2206 	 * we want a replenishment of its runtime.
2207 	 */
2208 	if (flags & ENQUEUE_WAKEUP) {
2209 		task_contending(dl_se, flags);
2210 		update_dl_entity(dl_se);
2211 	} else if (flags & ENQUEUE_REPLENISH) {
2212 		replenish_dl_entity(dl_se);
2213 	} else if ((flags & ENQUEUE_RESTORE) &&
2214 		   !is_dl_boosted(dl_se) &&
2215 		   dl_time_before(dl_se->deadline, rq_clock(rq_of_dl_se(dl_se)))) {
2216 		setup_new_dl_entity(dl_se);
2217 	}
2218 
2219 	/*
2220 	 * If the reservation is still throttled, e.g., it got replenished but is a
2221 	 * deferred task and still got to wait, don't enqueue.
2222 	 */
2223 	if (dl_se->dl_throttled && start_dl_timer(dl_se))
2224 		return;
2225 
2226 	/*
2227 	 * We're about to enqueue, make sure we're not ->dl_throttled!
2228 	 * In case the timer was not started, say because the defer time
2229 	 * has passed, mark as not throttled and mark unarmed.
2230 	 * Also cancel earlier timers, since letting those run is pointless.
2231 	 */
2232 	if (dl_se->dl_throttled) {
2233 		hrtimer_try_to_cancel(&dl_se->dl_timer);
2234 		dl_se->dl_defer_armed = 0;
2235 		dl_se->dl_throttled = 0;
2236 	}
2237 
2238 	__enqueue_dl_entity(dl_se);
2239 }
2240 
dequeue_dl_entity(struct sched_dl_entity * dl_se,int flags)2241 static void dequeue_dl_entity(struct sched_dl_entity *dl_se, int flags)
2242 {
2243 	__dequeue_dl_entity(dl_se);
2244 
2245 	if (flags & (DEQUEUE_SAVE|DEQUEUE_MIGRATING)) {
2246 		struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
2247 
2248 		sub_running_bw(dl_se, dl_rq);
2249 		sub_rq_bw(dl_se, dl_rq);
2250 	}
2251 
2252 	/*
2253 	 * This check allows to start the inactive timer (or to immediately
2254 	 * decrease the active utilization, if needed) in two cases:
2255 	 * when the task blocks and when it is terminating
2256 	 * (p->state == TASK_DEAD). We can handle the two cases in the same
2257 	 * way, because from GRUB's point of view the same thing is happening
2258 	 * (the task moves from "active contending" to "active non contending"
2259 	 * or "inactive")
2260 	 */
2261 	if (flags & DEQUEUE_SLEEP)
2262 		task_non_contending(dl_se, true);
2263 }
2264 
enqueue_task_dl(struct rq * rq,struct task_struct * p,int flags)2265 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags)
2266 {
2267 	if (is_dl_boosted(&p->dl)) {
2268 		/*
2269 		 * Because of delays in the detection of the overrun of a
2270 		 * thread's runtime, it might be the case that a thread
2271 		 * goes to sleep in a rt mutex with negative runtime. As
2272 		 * a consequence, the thread will be throttled.
2273 		 *
2274 		 * While waiting for the mutex, this thread can also be
2275 		 * boosted via PI, resulting in a thread that is throttled
2276 		 * and boosted at the same time.
2277 		 *
2278 		 * In this case, the boost overrides the throttle.
2279 		 */
2280 		if (p->dl.dl_throttled) {
2281 			/*
2282 			 * The replenish timer needs to be canceled. No
2283 			 * problem if it fires concurrently: boosted threads
2284 			 * are ignored in dl_task_timer().
2285 			 */
2286 			cancel_replenish_timer(&p->dl);
2287 			p->dl.dl_throttled = 0;
2288 		}
2289 	} else if (!dl_prio(p->normal_prio)) {
2290 		/*
2291 		 * Special case in which we have a !SCHED_DEADLINE task that is going
2292 		 * to be deboosted, but exceeds its runtime while doing so. No point in
2293 		 * replenishing it, as it's going to return back to its original
2294 		 * scheduling class after this. If it has been throttled, we need to
2295 		 * clear the flag, otherwise the task may wake up as throttled after
2296 		 * being boosted again with no means to replenish the runtime and clear
2297 		 * the throttle.
2298 		 */
2299 		p->dl.dl_throttled = 0;
2300 		if (!(flags & ENQUEUE_REPLENISH))
2301 			printk_deferred_once("sched: DL de-boosted task PID %d: REPLENISH flag missing\n",
2302 					     task_pid_nr(p));
2303 
2304 		return;
2305 	}
2306 
2307 	check_schedstat_required();
2308 	update_stats_wait_start_dl(dl_rq_of_se(&p->dl), &p->dl);
2309 
2310 	if (p->on_rq == TASK_ON_RQ_MIGRATING)
2311 		flags |= ENQUEUE_MIGRATING;
2312 
2313 	enqueue_dl_entity(&p->dl, flags);
2314 
2315 	if (dl_server(&p->dl))
2316 		return;
2317 
2318 	if (task_is_blocked(p))
2319 		return;
2320 
2321 	if (!task_current(rq, p) && !p->dl.dl_throttled && p->nr_cpus_allowed > 1)
2322 		enqueue_pushable_dl_task(rq, p);
2323 }
2324 
dequeue_task_dl(struct rq * rq,struct task_struct * p,int flags)2325 static bool dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
2326 {
2327 	update_curr_dl(rq);
2328 
2329 	if (p->on_rq == TASK_ON_RQ_MIGRATING)
2330 		flags |= DEQUEUE_MIGRATING;
2331 
2332 	dequeue_dl_entity(&p->dl, flags);
2333 	if (!p->dl.dl_throttled && !dl_server(&p->dl))
2334 		dequeue_pushable_dl_task(rq, p);
2335 
2336 	return true;
2337 }
2338 
2339 /*
2340  * Yield task semantic for -deadline tasks is:
2341  *
2342  *   get off from the CPU until our next instance, with
2343  *   a new runtime. This is of little use now, since we
2344  *   don't have a bandwidth reclaiming mechanism. Anyway,
2345  *   bandwidth reclaiming is planned for the future, and
2346  *   yield_task_dl will indicate that some spare budget
2347  *   is available for other task instances to use it.
2348  */
yield_task_dl(struct rq * rq)2349 static void yield_task_dl(struct rq *rq)
2350 {
2351 	/*
2352 	 * We make the task go to sleep until its current deadline by
2353 	 * forcing its runtime to zero. This way, update_curr_dl() stops
2354 	 * it and the bandwidth timer will wake it up and will give it
2355 	 * new scheduling parameters (thanks to dl_yielded=1).
2356 	 */
2357 	rq->donor->dl.dl_yielded = 1;
2358 
2359 	update_rq_clock(rq);
2360 	update_curr_dl(rq);
2361 	/*
2362 	 * Tell update_rq_clock() that we've just updated,
2363 	 * so we don't do microscopic update in schedule()
2364 	 * and double the fastpath cost.
2365 	 */
2366 	rq_clock_skip_update(rq);
2367 }
2368 
dl_task_is_earliest_deadline(struct task_struct * p,struct rq * rq)2369 static inline bool dl_task_is_earliest_deadline(struct task_struct *p,
2370 						 struct rq *rq)
2371 {
2372 	return (!rq->dl.dl_nr_running ||
2373 		dl_time_before(p->dl.deadline,
2374 			       rq->dl.earliest_dl.curr));
2375 }
2376 
2377 static int find_later_rq(struct task_struct *task);
2378 
2379 static int
select_task_rq_dl(struct task_struct * p,int cpu,int flags)2380 select_task_rq_dl(struct task_struct *p, int cpu, int flags)
2381 {
2382 	struct task_struct *curr, *donor;
2383 	bool select_rq;
2384 	struct rq *rq;
2385 
2386 	if (!(flags & WF_TTWU))
2387 		return cpu;
2388 
2389 	rq = cpu_rq(cpu);
2390 
2391 	rcu_read_lock();
2392 	curr = READ_ONCE(rq->curr); /* unlocked access */
2393 	donor = READ_ONCE(rq->donor);
2394 
2395 	/*
2396 	 * If we are dealing with a -deadline task, we must
2397 	 * decide where to wake it up.
2398 	 * If it has a later deadline and the current task
2399 	 * on this rq can't move (provided the waking task
2400 	 * can!) we prefer to send it somewhere else. On the
2401 	 * other hand, if it has a shorter deadline, we
2402 	 * try to make it stay here, it might be important.
2403 	 */
2404 	select_rq = unlikely(dl_task(donor)) &&
2405 		    (curr->nr_cpus_allowed < 2 ||
2406 		     !dl_entity_preempt(&p->dl, &donor->dl)) &&
2407 		    p->nr_cpus_allowed > 1;
2408 
2409 	/*
2410 	 * Take the capacity of the CPU into account to
2411 	 * ensure it fits the requirement of the task.
2412 	 */
2413 	if (sched_asym_cpucap_active())
2414 		select_rq |= !dl_task_fits_capacity(p, cpu);
2415 
2416 	if (select_rq) {
2417 		int target = find_later_rq(p);
2418 
2419 		if (target != -1 &&
2420 		    dl_task_is_earliest_deadline(p, cpu_rq(target)))
2421 			cpu = target;
2422 	}
2423 	rcu_read_unlock();
2424 
2425 	return cpu;
2426 }
2427 
migrate_task_rq_dl(struct task_struct * p,int new_cpu __maybe_unused)2428 static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused)
2429 {
2430 	struct rq_flags rf;
2431 	struct rq *rq;
2432 
2433 	if (READ_ONCE(p->__state) != TASK_WAKING)
2434 		return;
2435 
2436 	rq = task_rq(p);
2437 	/*
2438 	 * Since p->state == TASK_WAKING, set_task_cpu() has been called
2439 	 * from try_to_wake_up(). Hence, p->pi_lock is locked, but
2440 	 * rq->lock is not... So, lock it
2441 	 */
2442 	rq_lock(rq, &rf);
2443 	if (p->dl.dl_non_contending) {
2444 		update_rq_clock(rq);
2445 		sub_running_bw(&p->dl, &rq->dl);
2446 		p->dl.dl_non_contending = 0;
2447 		/*
2448 		 * If the timer handler is currently running and the
2449 		 * timer cannot be canceled, inactive_task_timer()
2450 		 * will see that dl_not_contending is not set, and
2451 		 * will not touch the rq's active utilization,
2452 		 * so we are still safe.
2453 		 */
2454 		cancel_inactive_timer(&p->dl);
2455 	}
2456 	sub_rq_bw(&p->dl, &rq->dl);
2457 	rq_unlock(rq, &rf);
2458 }
2459 
check_preempt_equal_dl(struct rq * rq,struct task_struct * p)2460 static void check_preempt_equal_dl(struct rq *rq, struct task_struct *p)
2461 {
2462 	/*
2463 	 * Current can't be migrated, useless to reschedule,
2464 	 * let's hope p can move out.
2465 	 */
2466 	if (rq->curr->nr_cpus_allowed == 1 ||
2467 	    !cpudl_find(&rq->rd->cpudl, rq->donor, NULL))
2468 		return;
2469 
2470 	/*
2471 	 * p is migratable, so let's not schedule it and
2472 	 * see if it is pushed or pulled somewhere else.
2473 	 */
2474 	if (p->nr_cpus_allowed != 1 &&
2475 	    cpudl_find(&rq->rd->cpudl, p, NULL))
2476 		return;
2477 
2478 	resched_curr(rq);
2479 }
2480 
balance_dl(struct rq * rq,struct task_struct * p,struct rq_flags * rf)2481 static int balance_dl(struct rq *rq, struct task_struct *p, struct rq_flags *rf)
2482 {
2483 	if (!on_dl_rq(&p->dl) && need_pull_dl_task(rq, p)) {
2484 		/*
2485 		 * This is OK, because current is on_cpu, which avoids it being
2486 		 * picked for load-balance and preemption/IRQs are still
2487 		 * disabled avoiding further scheduler activity on it and we've
2488 		 * not yet started the picking loop.
2489 		 */
2490 		rq_unpin_lock(rq, rf);
2491 		pull_dl_task(rq);
2492 		rq_repin_lock(rq, rf);
2493 	}
2494 
2495 	return sched_stop_runnable(rq) || sched_dl_runnable(rq);
2496 }
2497 
2498 /*
2499  * Only called when both the current and waking task are -deadline
2500  * tasks.
2501  */
wakeup_preempt_dl(struct rq * rq,struct task_struct * p,int flags)2502 static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p,
2503 				  int flags)
2504 {
2505 	if (dl_entity_preempt(&p->dl, &rq->donor->dl)) {
2506 		resched_curr(rq);
2507 		return;
2508 	}
2509 
2510 	/*
2511 	 * In the unlikely case current and p have the same deadline
2512 	 * let us try to decide what's the best thing to do...
2513 	 */
2514 	if ((p->dl.deadline == rq->donor->dl.deadline) &&
2515 	    !test_tsk_need_resched(rq->curr))
2516 		check_preempt_equal_dl(rq, p);
2517 }
2518 
2519 #ifdef CONFIG_SCHED_HRTICK
start_hrtick_dl(struct rq * rq,struct sched_dl_entity * dl_se)2520 static void start_hrtick_dl(struct rq *rq, struct sched_dl_entity *dl_se)
2521 {
2522 	hrtick_start(rq, dl_se->runtime);
2523 }
2524 #else /* !CONFIG_SCHED_HRTICK: */
start_hrtick_dl(struct rq * rq,struct sched_dl_entity * dl_se)2525 static void start_hrtick_dl(struct rq *rq, struct sched_dl_entity *dl_se)
2526 {
2527 }
2528 #endif /* !CONFIG_SCHED_HRTICK */
2529 
set_next_task_dl(struct rq * rq,struct task_struct * p,bool first)2530 static void set_next_task_dl(struct rq *rq, struct task_struct *p, bool first)
2531 {
2532 	struct sched_dl_entity *dl_se = &p->dl;
2533 	struct dl_rq *dl_rq = &rq->dl;
2534 
2535 	p->se.exec_start = rq_clock_task(rq);
2536 	if (on_dl_rq(&p->dl))
2537 		update_stats_wait_end_dl(dl_rq, dl_se);
2538 
2539 	/* You can't push away the running task */
2540 	dequeue_pushable_dl_task(rq, p);
2541 
2542 	if (!first)
2543 		return;
2544 
2545 	if (rq->donor->sched_class != &dl_sched_class)
2546 		update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 0);
2547 
2548 	deadline_queue_push_tasks(rq);
2549 
2550 	if (hrtick_enabled_dl(rq))
2551 		start_hrtick_dl(rq, &p->dl);
2552 }
2553 
pick_next_dl_entity(struct dl_rq * dl_rq)2554 static struct sched_dl_entity *pick_next_dl_entity(struct dl_rq *dl_rq)
2555 {
2556 	struct rb_node *left = rb_first_cached(&dl_rq->root);
2557 
2558 	if (!left)
2559 		return NULL;
2560 
2561 	return __node_2_dle(left);
2562 }
2563 
2564 /*
2565  * __pick_next_task_dl - Helper to pick the next -deadline task to run.
2566  * @rq: The runqueue to pick the next task from.
2567  */
__pick_task_dl(struct rq * rq,struct rq_flags * rf)2568 static struct task_struct *__pick_task_dl(struct rq *rq, struct rq_flags *rf)
2569 {
2570 	struct sched_dl_entity *dl_se;
2571 	struct dl_rq *dl_rq = &rq->dl;
2572 	struct task_struct *p;
2573 
2574 again:
2575 	if (!sched_dl_runnable(rq))
2576 		return NULL;
2577 
2578 	dl_se = pick_next_dl_entity(dl_rq);
2579 	WARN_ON_ONCE(!dl_se);
2580 
2581 	if (dl_server(dl_se)) {
2582 		p = dl_se->server_pick_task(dl_se, rf);
2583 		if (!p) {
2584 			dl_server_stop(dl_se);
2585 			goto again;
2586 		}
2587 		rq->dl_server = dl_se;
2588 	} else {
2589 		p = dl_task_of(dl_se);
2590 	}
2591 
2592 	return p;
2593 }
2594 
pick_task_dl(struct rq * rq,struct rq_flags * rf)2595 static struct task_struct *pick_task_dl(struct rq *rq, struct rq_flags *rf)
2596 {
2597 	return __pick_task_dl(rq, rf);
2598 }
2599 
put_prev_task_dl(struct rq * rq,struct task_struct * p,struct task_struct * next)2600 static void put_prev_task_dl(struct rq *rq, struct task_struct *p, struct task_struct *next)
2601 {
2602 	struct sched_dl_entity *dl_se = &p->dl;
2603 	struct dl_rq *dl_rq = &rq->dl;
2604 
2605 	if (on_dl_rq(&p->dl))
2606 		update_stats_wait_start_dl(dl_rq, dl_se);
2607 
2608 	update_curr_dl(rq);
2609 
2610 	update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 1);
2611 
2612 	if (task_is_blocked(p))
2613 		return;
2614 
2615 	if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1)
2616 		enqueue_pushable_dl_task(rq, p);
2617 }
2618 
2619 /*
2620  * scheduler tick hitting a task of our scheduling class.
2621  *
2622  * NOTE: This function can be called remotely by the tick offload that
2623  * goes along full dynticks. Therefore no local assumption can be made
2624  * and everything must be accessed through the @rq and @curr passed in
2625  * parameters.
2626  */
task_tick_dl(struct rq * rq,struct task_struct * p,int queued)2627 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued)
2628 {
2629 	update_curr_dl(rq);
2630 
2631 	update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 1);
2632 	/*
2633 	 * Even when we have runtime, update_curr_dl() might have resulted in us
2634 	 * not being the leftmost task anymore. In that case NEED_RESCHED will
2635 	 * be set and schedule() will start a new hrtick for the next task.
2636 	 */
2637 	if (hrtick_enabled_dl(rq) && queued && p->dl.runtime > 0 &&
2638 	    is_leftmost(&p->dl, &rq->dl))
2639 		start_hrtick_dl(rq, &p->dl);
2640 }
2641 
task_fork_dl(struct task_struct * p)2642 static void task_fork_dl(struct task_struct *p)
2643 {
2644 	/*
2645 	 * SCHED_DEADLINE tasks cannot fork and this is achieved through
2646 	 * sched_fork()
2647 	 */
2648 }
2649 
2650 /* Only try algorithms three times */
2651 #define DL_MAX_TRIES 3
2652 
2653 /*
2654  * Return the earliest pushable rq's task, which is suitable to be executed
2655  * on the CPU, NULL otherwise:
2656  */
pick_earliest_pushable_dl_task(struct rq * rq,int cpu)2657 static struct task_struct *pick_earliest_pushable_dl_task(struct rq *rq, int cpu)
2658 {
2659 	struct task_struct *p = NULL;
2660 	struct rb_node *next_node;
2661 
2662 	if (!has_pushable_dl_tasks(rq))
2663 		return NULL;
2664 
2665 	next_node = rb_first_cached(&rq->dl.pushable_dl_tasks_root);
2666 	while (next_node) {
2667 		p = __node_2_pdl(next_node);
2668 
2669 		if (task_is_pushable(rq, p, cpu))
2670 			return p;
2671 
2672 		next_node = rb_next(next_node);
2673 	}
2674 
2675 	return NULL;
2676 }
2677 
2678 /* Access rule: must be called on local CPU with preemption disabled */
2679 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
2680 
find_later_rq(struct task_struct * task)2681 static int find_later_rq(struct task_struct *task)
2682 {
2683 	struct sched_domain *sd;
2684 	struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
2685 	int this_cpu = smp_processor_id();
2686 	int cpu = task_cpu(task);
2687 
2688 	/* Make sure the mask is initialized first */
2689 	if (unlikely(!later_mask))
2690 		return -1;
2691 
2692 	if (task->nr_cpus_allowed == 1)
2693 		return -1;
2694 
2695 	/*
2696 	 * We have to consider system topology and task affinity
2697 	 * first, then we can look for a suitable CPU.
2698 	 */
2699 	if (!cpudl_find(&task_rq(task)->rd->cpudl, task, later_mask))
2700 		return -1;
2701 
2702 	/*
2703 	 * If we are here, some targets have been found, including
2704 	 * the most suitable which is, among the runqueues where the
2705 	 * current tasks have later deadlines than the task's one, the
2706 	 * rq with the latest possible one.
2707 	 *
2708 	 * Now we check how well this matches with task's
2709 	 * affinity and system topology.
2710 	 *
2711 	 * The last CPU where the task run is our first
2712 	 * guess, since it is most likely cache-hot there.
2713 	 */
2714 	if (cpumask_test_cpu(cpu, later_mask))
2715 		return cpu;
2716 	/*
2717 	 * Check if this_cpu is to be skipped (i.e., it is
2718 	 * not in the mask) or not.
2719 	 */
2720 	if (!cpumask_test_cpu(this_cpu, later_mask))
2721 		this_cpu = -1;
2722 
2723 	rcu_read_lock();
2724 	for_each_domain(cpu, sd) {
2725 		if (sd->flags & SD_WAKE_AFFINE) {
2726 			int best_cpu;
2727 
2728 			/*
2729 			 * If possible, preempting this_cpu is
2730 			 * cheaper than migrating.
2731 			 */
2732 			if (this_cpu != -1 &&
2733 			    cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
2734 				rcu_read_unlock();
2735 				return this_cpu;
2736 			}
2737 
2738 			best_cpu = cpumask_any_and_distribute(later_mask,
2739 							      sched_domain_span(sd));
2740 			/*
2741 			 * Last chance: if a CPU being in both later_mask
2742 			 * and current sd span is valid, that becomes our
2743 			 * choice. Of course, the latest possible CPU is
2744 			 * already under consideration through later_mask.
2745 			 */
2746 			if (best_cpu < nr_cpu_ids) {
2747 				rcu_read_unlock();
2748 				return best_cpu;
2749 			}
2750 		}
2751 	}
2752 	rcu_read_unlock();
2753 
2754 	/*
2755 	 * At this point, all our guesses failed, we just return
2756 	 * 'something', and let the caller sort the things out.
2757 	 */
2758 	if (this_cpu != -1)
2759 		return this_cpu;
2760 
2761 	cpu = cpumask_any_distribute(later_mask);
2762 	if (cpu < nr_cpu_ids)
2763 		return cpu;
2764 
2765 	return -1;
2766 }
2767 
pick_next_pushable_dl_task(struct rq * rq)2768 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq)
2769 {
2770 	struct task_struct *p;
2771 
2772 	if (!has_pushable_dl_tasks(rq))
2773 		return NULL;
2774 
2775 	p = __node_2_pdl(rb_first_cached(&rq->dl.pushable_dl_tasks_root));
2776 
2777 	WARN_ON_ONCE(rq->cpu != task_cpu(p));
2778 	WARN_ON_ONCE(task_current(rq, p));
2779 	WARN_ON_ONCE(p->nr_cpus_allowed <= 1);
2780 
2781 	WARN_ON_ONCE(!task_on_rq_queued(p));
2782 	WARN_ON_ONCE(!dl_task(p));
2783 
2784 	return p;
2785 }
2786 
2787 /* Locks the rq it finds */
find_lock_later_rq(struct task_struct * task,struct rq * rq)2788 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq)
2789 {
2790 	struct rq *later_rq = NULL;
2791 	int tries;
2792 	int cpu;
2793 
2794 	for (tries = 0; tries < DL_MAX_TRIES; tries++) {
2795 		cpu = find_later_rq(task);
2796 
2797 		if ((cpu == -1) || (cpu == rq->cpu))
2798 			break;
2799 
2800 		later_rq = cpu_rq(cpu);
2801 
2802 		if (!dl_task_is_earliest_deadline(task, later_rq)) {
2803 			/*
2804 			 * Target rq has tasks of equal or earlier deadline,
2805 			 * retrying does not release any lock and is unlikely
2806 			 * to yield a different result.
2807 			 */
2808 			later_rq = NULL;
2809 			break;
2810 		}
2811 
2812 		/* Retry if something changed. */
2813 		if (double_lock_balance(rq, later_rq)) {
2814 			/*
2815 			 * double_lock_balance had to release rq->lock, in the
2816 			 * meantime, task may no longer be fit to be migrated.
2817 			 * Check the following to ensure that the task is
2818 			 * still suitable for migration:
2819 			 * 1. It is possible the task was scheduled,
2820 			 *    migrate_disabled was set and then got preempted,
2821 			 *    so we must check the task migration disable
2822 			 *    flag.
2823 			 * 2. The CPU picked is in the task's affinity.
2824 			 * 3. For throttled task (dl_task_offline_migration),
2825 			 *    check the following:
2826 			 *    - the task is not on the rq anymore (it was
2827 			 *      migrated)
2828 			 *    - the task is not on CPU anymore
2829 			 *    - the task is still a dl task
2830 			 *    - the task is not queued on the rq anymore
2831 			 * 4. For the non-throttled task (push_dl_task), the
2832 			 *    check to ensure that this task is still at the
2833 			 *    head of the pushable tasks list is enough.
2834 			 */
2835 			if (unlikely(is_migration_disabled(task) ||
2836 				     !cpumask_test_cpu(later_rq->cpu, &task->cpus_mask) ||
2837 				     (task->dl.dl_throttled &&
2838 				      (task_rq(task) != rq ||
2839 				       task_on_cpu(rq, task) ||
2840 				       !dl_task(task) ||
2841 				       !task_on_rq_queued(task))) ||
2842 				     (!task->dl.dl_throttled &&
2843 				      task != pick_next_pushable_dl_task(rq)))) {
2844 
2845 				double_unlock_balance(rq, later_rq);
2846 				later_rq = NULL;
2847 				break;
2848 			}
2849 		}
2850 
2851 		/*
2852 		 * If the rq we found has no -deadline task, or
2853 		 * its earliest one has a later deadline than our
2854 		 * task, the rq is a good one.
2855 		 */
2856 		if (dl_task_is_earliest_deadline(task, later_rq))
2857 			break;
2858 
2859 		/* Otherwise we try again. */
2860 		double_unlock_balance(rq, later_rq);
2861 		later_rq = NULL;
2862 	}
2863 
2864 	return later_rq;
2865 }
2866 
2867 /*
2868  * See if the non running -deadline tasks on this rq
2869  * can be sent to some other CPU where they can preempt
2870  * and start executing.
2871  */
push_dl_task(struct rq * rq)2872 static int push_dl_task(struct rq *rq)
2873 {
2874 	struct task_struct *next_task;
2875 	struct rq *later_rq;
2876 	int ret = 0;
2877 
2878 	next_task = pick_next_pushable_dl_task(rq);
2879 	if (!next_task)
2880 		return 0;
2881 
2882 retry:
2883 	/*
2884 	 * If next_task preempts rq->curr, and rq->curr
2885 	 * can move away, it makes sense to just reschedule
2886 	 * without going further in pushing next_task.
2887 	 */
2888 	if (dl_task(rq->donor) &&
2889 	    dl_time_before(next_task->dl.deadline, rq->donor->dl.deadline) &&
2890 	    rq->curr->nr_cpus_allowed > 1) {
2891 		resched_curr(rq);
2892 		return 0;
2893 	}
2894 
2895 	if (is_migration_disabled(next_task))
2896 		return 0;
2897 
2898 	if (WARN_ON(next_task == rq->curr))
2899 		return 0;
2900 
2901 	/* We might release rq lock */
2902 	get_task_struct(next_task);
2903 
2904 	/* Will lock the rq it'll find */
2905 	later_rq = find_lock_later_rq(next_task, rq);
2906 	if (!later_rq) {
2907 		struct task_struct *task;
2908 
2909 		/*
2910 		 * We must check all this again, since
2911 		 * find_lock_later_rq releases rq->lock and it is
2912 		 * then possible that next_task has migrated.
2913 		 */
2914 		task = pick_next_pushable_dl_task(rq);
2915 		if (task == next_task) {
2916 			/*
2917 			 * The task is still there. We don't try
2918 			 * again, some other CPU will pull it when ready.
2919 			 */
2920 			goto out;
2921 		}
2922 
2923 		if (!task)
2924 			/* No more tasks */
2925 			goto out;
2926 
2927 		put_task_struct(next_task);
2928 		next_task = task;
2929 		goto retry;
2930 	}
2931 
2932 	move_queued_task_locked(rq, later_rq, next_task);
2933 	ret = 1;
2934 
2935 	resched_curr(later_rq);
2936 
2937 	double_unlock_balance(rq, later_rq);
2938 
2939 out:
2940 	put_task_struct(next_task);
2941 
2942 	return ret;
2943 }
2944 
push_dl_tasks(struct rq * rq)2945 static void push_dl_tasks(struct rq *rq)
2946 {
2947 	/* push_dl_task() will return true if it moved a -deadline task */
2948 	while (push_dl_task(rq))
2949 		;
2950 }
2951 
pull_dl_task(struct rq * this_rq)2952 static void pull_dl_task(struct rq *this_rq)
2953 {
2954 	int this_cpu = this_rq->cpu, cpu;
2955 	struct task_struct *p, *push_task;
2956 	bool resched = false;
2957 	struct rq *src_rq;
2958 	u64 dmin = LONG_MAX;
2959 
2960 	if (likely(!dl_overloaded(this_rq)))
2961 		return;
2962 
2963 	/*
2964 	 * Match the barrier from dl_set_overloaded; this guarantees that if we
2965 	 * see overloaded we must also see the dlo_mask bit.
2966 	 */
2967 	smp_rmb();
2968 
2969 	for_each_cpu(cpu, this_rq->rd->dlo_mask) {
2970 		if (this_cpu == cpu)
2971 			continue;
2972 
2973 		src_rq = cpu_rq(cpu);
2974 
2975 		/*
2976 		 * It looks racy, and it is! However, as in sched_rt.c,
2977 		 * we are fine with this.
2978 		 */
2979 		if (this_rq->dl.dl_nr_running &&
2980 		    dl_time_before(this_rq->dl.earliest_dl.curr,
2981 				   src_rq->dl.earliest_dl.next))
2982 			continue;
2983 
2984 		/* Might drop this_rq->lock */
2985 		push_task = NULL;
2986 		double_lock_balance(this_rq, src_rq);
2987 
2988 		/*
2989 		 * If there are no more pullable tasks on the
2990 		 * rq, we're done with it.
2991 		 */
2992 		if (src_rq->dl.dl_nr_running <= 1)
2993 			goto skip;
2994 
2995 		p = pick_earliest_pushable_dl_task(src_rq, this_cpu);
2996 
2997 		/*
2998 		 * We found a task to be pulled if:
2999 		 *  - it preempts our current (if there's one),
3000 		 *  - it will preempt the last one we pulled (if any).
3001 		 */
3002 		if (p && dl_time_before(p->dl.deadline, dmin) &&
3003 		    dl_task_is_earliest_deadline(p, this_rq)) {
3004 			WARN_ON(p == src_rq->curr);
3005 			WARN_ON(!task_on_rq_queued(p));
3006 
3007 			/*
3008 			 * Then we pull iff p has actually an earlier
3009 			 * deadline than the current task of its runqueue.
3010 			 */
3011 			if (dl_time_before(p->dl.deadline,
3012 					   src_rq->donor->dl.deadline))
3013 				goto skip;
3014 
3015 			if (is_migration_disabled(p)) {
3016 				push_task = get_push_task(src_rq);
3017 			} else {
3018 				move_queued_task_locked(src_rq, this_rq, p);
3019 				dmin = p->dl.deadline;
3020 				resched = true;
3021 			}
3022 
3023 			/* Is there any other task even earlier? */
3024 		}
3025 skip:
3026 		double_unlock_balance(this_rq, src_rq);
3027 
3028 		if (push_task) {
3029 			preempt_disable();
3030 			raw_spin_rq_unlock(this_rq);
3031 			stop_one_cpu_nowait(src_rq->cpu, push_cpu_stop,
3032 					    push_task, &src_rq->push_work);
3033 			preempt_enable();
3034 			raw_spin_rq_lock(this_rq);
3035 		}
3036 	}
3037 
3038 	if (resched)
3039 		resched_curr(this_rq);
3040 }
3041 
3042 /*
3043  * Since the task is not running and a reschedule is not going to happen
3044  * anytime soon on its runqueue, we try pushing it away now.
3045  */
task_woken_dl(struct rq * rq,struct task_struct * p)3046 static void task_woken_dl(struct rq *rq, struct task_struct *p)
3047 {
3048 	if (!task_on_cpu(rq, p) &&
3049 	    !test_tsk_need_resched(rq->curr) &&
3050 	    p->nr_cpus_allowed > 1 &&
3051 	    dl_task(rq->donor) &&
3052 	    (rq->curr->nr_cpus_allowed < 2 ||
3053 	     !dl_entity_preempt(&p->dl, &rq->donor->dl))) {
3054 		push_dl_tasks(rq);
3055 	}
3056 }
3057 
set_cpus_allowed_dl(struct task_struct * p,struct affinity_context * ctx)3058 static void set_cpus_allowed_dl(struct task_struct *p,
3059 				struct affinity_context *ctx)
3060 {
3061 	struct root_domain *src_rd;
3062 	struct rq *rq;
3063 
3064 	WARN_ON_ONCE(!dl_task(p));
3065 
3066 	rq = task_rq(p);
3067 	src_rd = rq->rd;
3068 	/*
3069 	 * Migrating a SCHED_DEADLINE task between exclusive
3070 	 * cpusets (different root_domains) entails a bandwidth
3071 	 * update. We already made space for us in the destination
3072 	 * domain (see cpuset_can_attach()).
3073 	 */
3074 	if (!cpumask_intersects(src_rd->span, ctx->new_mask)) {
3075 		struct dl_bw *src_dl_b;
3076 
3077 		src_dl_b = dl_bw_of(cpu_of(rq));
3078 		/*
3079 		 * We now free resources of the root_domain we are migrating
3080 		 * off. In the worst case, sched_setattr() may temporary fail
3081 		 * until we complete the update.
3082 		 */
3083 		raw_spin_lock(&src_dl_b->lock);
3084 		__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
3085 		raw_spin_unlock(&src_dl_b->lock);
3086 	}
3087 
3088 	set_cpus_allowed_common(p, ctx);
3089 }
3090 
3091 /* Assumes rq->lock is held */
rq_online_dl(struct rq * rq)3092 static void rq_online_dl(struct rq *rq)
3093 {
3094 	if (rq->dl.overloaded)
3095 		dl_set_overload(rq);
3096 
3097 	if (rq->dl.dl_nr_running > 0)
3098 		cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr);
3099 	else
3100 		cpudl_clear(&rq->rd->cpudl, rq->cpu, true);
3101 }
3102 
3103 /* Assumes rq->lock is held */
rq_offline_dl(struct rq * rq)3104 static void rq_offline_dl(struct rq *rq)
3105 {
3106 	if (rq->dl.overloaded)
3107 		dl_clear_overload(rq);
3108 
3109 	cpudl_clear(&rq->rd->cpudl, rq->cpu, false);
3110 }
3111 
init_sched_dl_class(void)3112 void __init init_sched_dl_class(void)
3113 {
3114 	unsigned int i;
3115 
3116 	for_each_possible_cpu(i)
3117 		zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
3118 					GFP_KERNEL, cpu_to_node(i));
3119 }
3120 
3121 /*
3122  * This function always returns a non-empty bitmap in @cpus. This is because
3123  * if a root domain has reserved bandwidth for DL tasks, the DL bandwidth
3124  * check will prevent CPU hotplug from deactivating all CPUs in that domain.
3125  */
dl_get_task_effective_cpus(struct task_struct * p,struct cpumask * cpus)3126 static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cpus)
3127 {
3128 	const struct cpumask *hk_msk;
3129 
3130 	hk_msk = housekeeping_cpumask(HK_TYPE_DOMAIN);
3131 	if (housekeeping_enabled(HK_TYPE_DOMAIN)) {
3132 		if (!cpumask_intersects(p->cpus_ptr, hk_msk)) {
3133 			/*
3134 			 * CPUs isolated by isolcpu="domain" always belong to
3135 			 * def_root_domain.
3136 			 */
3137 			cpumask_andnot(cpus, cpu_active_mask, hk_msk);
3138 			return;
3139 		}
3140 	}
3141 
3142 	/*
3143 	 * If a root domain holds a DL task, it must have active CPUs. So
3144 	 * active CPUs can always be found by walking up the task's cpuset
3145 	 * hierarchy up to the partition root.
3146 	 */
3147 	cpuset_cpus_allowed_locked(p, cpus);
3148 }
3149 
3150 /* The caller should hold cpuset_mutex */
dl_add_task_root_domain(struct task_struct * p)3151 void dl_add_task_root_domain(struct task_struct *p)
3152 {
3153 	struct rq_flags rf;
3154 	struct rq *rq;
3155 	struct dl_bw *dl_b;
3156 	unsigned int cpu;
3157 	struct cpumask *msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
3158 
3159 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
3160 	if (!dl_task(p) || dl_entity_is_special(&p->dl)) {
3161 		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
3162 		return;
3163 	}
3164 
3165 	/*
3166 	 * Get an active rq, whose rq->rd traces the correct root
3167 	 * domain.
3168 	 * Ideally this would be under cpuset reader lock until rq->rd is
3169 	 * fetched.  However, sleepable locks cannot nest inside pi_lock, so we
3170 	 * rely on the caller of dl_add_task_root_domain() holds 'cpuset_mutex'
3171 	 * to guarantee the CPU stays in the cpuset.
3172 	 */
3173 	dl_get_task_effective_cpus(p, msk);
3174 	cpu = cpumask_first_and(cpu_active_mask, msk);
3175 	BUG_ON(cpu >= nr_cpu_ids);
3176 	rq = cpu_rq(cpu);
3177 	dl_b = &rq->rd->dl_bw;
3178 	/* End of fetching rd */
3179 
3180 	raw_spin_lock(&dl_b->lock);
3181 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
3182 	raw_spin_unlock(&dl_b->lock);
3183 	raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
3184 }
3185 
dl_clear_root_domain(struct root_domain * rd)3186 void dl_clear_root_domain(struct root_domain *rd)
3187 {
3188 	int i;
3189 
3190 	guard(raw_spinlock_irqsave)(&rd->dl_bw.lock);
3191 
3192 	/*
3193 	 * Reset total_bw to zero and extra_bw to max_bw so that next
3194 	 * loop will add dl-servers contributions back properly,
3195 	 */
3196 	rd->dl_bw.total_bw = 0;
3197 	for_each_cpu(i, rd->span)
3198 		cpu_rq(i)->dl.extra_bw = cpu_rq(i)->dl.max_bw;
3199 
3200 	/*
3201 	 * dl_servers are not tasks. Since dl_add_task_root_domain ignores
3202 	 * them, we need to account for them here explicitly.
3203 	 */
3204 	for_each_cpu(i, rd->span) {
3205 		struct sched_dl_entity *dl_se = &cpu_rq(i)->fair_server;
3206 
3207 		if (dl_server(dl_se) && cpu_active(i))
3208 			__dl_add(&rd->dl_bw, dl_se->dl_bw, dl_bw_cpus(i));
3209 	}
3210 }
3211 
dl_clear_root_domain_cpu(int cpu)3212 void dl_clear_root_domain_cpu(int cpu)
3213 {
3214 	dl_clear_root_domain(cpu_rq(cpu)->rd);
3215 }
3216 
switched_from_dl(struct rq * rq,struct task_struct * p)3217 static void switched_from_dl(struct rq *rq, struct task_struct *p)
3218 {
3219 	/*
3220 	 * task_non_contending() can start the "inactive timer" (if the 0-lag
3221 	 * time is in the future). If the task switches back to dl before
3222 	 * the "inactive timer" fires, it can continue to consume its current
3223 	 * runtime using its current deadline. If it stays outside of
3224 	 * SCHED_DEADLINE until the 0-lag time passes, inactive_task_timer()
3225 	 * will reset the task parameters.
3226 	 */
3227 	if (task_on_rq_queued(p) && p->dl.dl_runtime)
3228 		task_non_contending(&p->dl, false);
3229 
3230 	/*
3231 	 * In case a task is setscheduled out from SCHED_DEADLINE we need to
3232 	 * keep track of that on its cpuset (for correct bandwidth tracking).
3233 	 */
3234 	dec_dl_tasks_cs(p);
3235 
3236 	if (!task_on_rq_queued(p)) {
3237 		/*
3238 		 * Inactive timer is armed. However, p is leaving DEADLINE and
3239 		 * might migrate away from this rq while continuing to run on
3240 		 * some other class. We need to remove its contribution from
3241 		 * this rq running_bw now, or sub_rq_bw (below) will complain.
3242 		 */
3243 		if (p->dl.dl_non_contending)
3244 			sub_running_bw(&p->dl, &rq->dl);
3245 		sub_rq_bw(&p->dl, &rq->dl);
3246 	}
3247 
3248 	/*
3249 	 * We cannot use inactive_task_timer() to invoke sub_running_bw()
3250 	 * at the 0-lag time, because the task could have been migrated
3251 	 * while SCHED_OTHER in the meanwhile.
3252 	 */
3253 	if (p->dl.dl_non_contending)
3254 		p->dl.dl_non_contending = 0;
3255 
3256 	/*
3257 	 * Since this might be the only -deadline task on the rq,
3258 	 * this is the right place to try to pull some other one
3259 	 * from an overloaded CPU, if any.
3260 	 */
3261 	if (!task_on_rq_queued(p) || rq->dl.dl_nr_running)
3262 		return;
3263 
3264 	deadline_queue_pull_task(rq);
3265 }
3266 
3267 /*
3268  * When switching to -deadline, we may overload the rq, then
3269  * we try to push someone off, if possible.
3270  */
switched_to_dl(struct rq * rq,struct task_struct * p)3271 static void switched_to_dl(struct rq *rq, struct task_struct *p)
3272 {
3273 	cancel_inactive_timer(&p->dl);
3274 
3275 	/*
3276 	 * In case a task is setscheduled to SCHED_DEADLINE we need to keep
3277 	 * track of that on its cpuset (for correct bandwidth tracking).
3278 	 */
3279 	inc_dl_tasks_cs(p);
3280 
3281 	/* If p is not queued we will update its parameters at next wakeup. */
3282 	if (!task_on_rq_queued(p)) {
3283 		add_rq_bw(&p->dl, &rq->dl);
3284 
3285 		return;
3286 	}
3287 
3288 	if (rq->donor != p) {
3289 		if (p->nr_cpus_allowed > 1 && rq->dl.overloaded)
3290 			deadline_queue_push_tasks(rq);
3291 		if (dl_task(rq->donor))
3292 			wakeup_preempt_dl(rq, p, 0);
3293 		else
3294 			resched_curr(rq);
3295 	} else {
3296 		update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 0);
3297 	}
3298 }
3299 
get_prio_dl(struct rq * rq,struct task_struct * p)3300 static u64 get_prio_dl(struct rq *rq, struct task_struct *p)
3301 {
3302 	return p->dl.deadline;
3303 }
3304 
3305 /*
3306  * If the scheduling parameters of a -deadline task changed,
3307  * a push or pull operation might be needed.
3308  */
prio_changed_dl(struct rq * rq,struct task_struct * p,u64 old_deadline)3309 static void prio_changed_dl(struct rq *rq, struct task_struct *p, u64 old_deadline)
3310 {
3311 	if (!task_on_rq_queued(p))
3312 		return;
3313 
3314 	if (p->dl.deadline == old_deadline)
3315 		return;
3316 
3317 	if (dl_time_before(old_deadline, p->dl.deadline))
3318 		deadline_queue_pull_task(rq);
3319 
3320 	if (task_current_donor(rq, p)) {
3321 		/*
3322 		 * If we now have a earlier deadline task than p,
3323 		 * then reschedule, provided p is still on this
3324 		 * runqueue.
3325 		 */
3326 		if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline))
3327 			resched_curr(rq);
3328 	} else {
3329 		/*
3330 		 * Current may not be deadline in case p was throttled but we
3331 		 * have just replenished it (e.g. rt_mutex_setprio()).
3332 		 *
3333 		 * Otherwise, if p was given an earlier deadline, reschedule.
3334 		 */
3335 		if (!dl_task(rq->curr) ||
3336 		    dl_time_before(p->dl.deadline, rq->curr->dl.deadline))
3337 			resched_curr(rq);
3338 	}
3339 }
3340 
3341 #ifdef CONFIG_SCHED_CORE
task_is_throttled_dl(struct task_struct * p,int cpu)3342 static int task_is_throttled_dl(struct task_struct *p, int cpu)
3343 {
3344 	return p->dl.dl_throttled;
3345 }
3346 #endif
3347 
3348 DEFINE_SCHED_CLASS(dl) = {
3349 
3350 	.queue_mask		= 8,
3351 
3352 	.enqueue_task		= enqueue_task_dl,
3353 	.dequeue_task		= dequeue_task_dl,
3354 	.yield_task		= yield_task_dl,
3355 
3356 	.wakeup_preempt		= wakeup_preempt_dl,
3357 
3358 	.pick_task		= pick_task_dl,
3359 	.put_prev_task		= put_prev_task_dl,
3360 	.set_next_task		= set_next_task_dl,
3361 
3362 	.balance		= balance_dl,
3363 	.select_task_rq		= select_task_rq_dl,
3364 	.migrate_task_rq	= migrate_task_rq_dl,
3365 	.set_cpus_allowed       = set_cpus_allowed_dl,
3366 	.rq_online              = rq_online_dl,
3367 	.rq_offline             = rq_offline_dl,
3368 	.task_woken		= task_woken_dl,
3369 	.find_lock_rq		= find_lock_later_rq,
3370 
3371 	.task_tick		= task_tick_dl,
3372 	.task_fork              = task_fork_dl,
3373 
3374 	.get_prio		= get_prio_dl,
3375 	.prio_changed           = prio_changed_dl,
3376 	.switched_from		= switched_from_dl,
3377 	.switched_to		= switched_to_dl,
3378 
3379 	.update_curr		= update_curr_dl,
3380 #ifdef CONFIG_SCHED_CORE
3381 	.task_is_throttled	= task_is_throttled_dl,
3382 #endif
3383 };
3384 
3385 /*
3386  * Used for dl_bw check and update, used under sched_rt_handler()::mutex and
3387  * sched_domains_mutex.
3388  */
3389 u64 dl_cookie;
3390 
sched_dl_global_validate(void)3391 int sched_dl_global_validate(void)
3392 {
3393 	u64 runtime = global_rt_runtime();
3394 	u64 period = global_rt_period();
3395 	u64 new_bw = to_ratio(period, runtime);
3396 	u64 cookie = ++dl_cookie;
3397 	struct dl_bw *dl_b;
3398 	int cpu, cpus, ret = 0;
3399 	unsigned long flags;
3400 
3401 	/*
3402 	 * Here we want to check the bandwidth not being set to some
3403 	 * value smaller than the currently allocated bandwidth in
3404 	 * any of the root_domains.
3405 	 */
3406 	for_each_online_cpu(cpu) {
3407 		rcu_read_lock_sched();
3408 
3409 		if (dl_bw_visited(cpu, cookie))
3410 			goto next;
3411 
3412 		dl_b = dl_bw_of(cpu);
3413 		cpus = dl_bw_cpus(cpu);
3414 
3415 		raw_spin_lock_irqsave(&dl_b->lock, flags);
3416 		if (new_bw * cpus < dl_b->total_bw)
3417 			ret = -EBUSY;
3418 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
3419 
3420 next:
3421 		rcu_read_unlock_sched();
3422 
3423 		if (ret)
3424 			break;
3425 	}
3426 
3427 	return ret;
3428 }
3429 
init_dl_rq_bw_ratio(struct dl_rq * dl_rq)3430 static void init_dl_rq_bw_ratio(struct dl_rq *dl_rq)
3431 {
3432 	if (global_rt_runtime() == RUNTIME_INF) {
3433 		dl_rq->bw_ratio = 1 << RATIO_SHIFT;
3434 		dl_rq->max_bw = dl_rq->extra_bw = 1 << BW_SHIFT;
3435 	} else {
3436 		dl_rq->bw_ratio = to_ratio(global_rt_runtime(),
3437 			  global_rt_period()) >> (BW_SHIFT - RATIO_SHIFT);
3438 		dl_rq->max_bw = dl_rq->extra_bw =
3439 			to_ratio(global_rt_period(), global_rt_runtime());
3440 	}
3441 }
3442 
sched_dl_do_global(void)3443 void sched_dl_do_global(void)
3444 {
3445 	u64 new_bw = -1;
3446 	u64 cookie = ++dl_cookie;
3447 	struct dl_bw *dl_b;
3448 	int cpu;
3449 	unsigned long flags;
3450 
3451 	if (global_rt_runtime() != RUNTIME_INF)
3452 		new_bw = to_ratio(global_rt_period(), global_rt_runtime());
3453 
3454 	for_each_possible_cpu(cpu)
3455 		init_dl_rq_bw_ratio(&cpu_rq(cpu)->dl);
3456 
3457 	for_each_possible_cpu(cpu) {
3458 		rcu_read_lock_sched();
3459 
3460 		if (dl_bw_visited(cpu, cookie)) {
3461 			rcu_read_unlock_sched();
3462 			continue;
3463 		}
3464 
3465 		dl_b = dl_bw_of(cpu);
3466 
3467 		raw_spin_lock_irqsave(&dl_b->lock, flags);
3468 		dl_b->bw = new_bw;
3469 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
3470 
3471 		rcu_read_unlock_sched();
3472 	}
3473 }
3474 
3475 /*
3476  * We must be sure that accepting a new task (or allowing changing the
3477  * parameters of an existing one) is consistent with the bandwidth
3478  * constraints. If yes, this function also accordingly updates the currently
3479  * allocated bandwidth to reflect the new situation.
3480  *
3481  * This function is called while holding p's rq->lock.
3482  */
sched_dl_overflow(struct task_struct * p,int policy,const struct sched_attr * attr)3483 int sched_dl_overflow(struct task_struct *p, int policy,
3484 		      const struct sched_attr *attr)
3485 {
3486 	u64 period = attr->sched_period ?: attr->sched_deadline;
3487 	u64 runtime = attr->sched_runtime;
3488 	u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
3489 	int cpus, err = -1, cpu = task_cpu(p);
3490 	struct dl_bw *dl_b = dl_bw_of(cpu);
3491 	unsigned long cap;
3492 
3493 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
3494 		return 0;
3495 
3496 	/* !deadline task may carry old deadline bandwidth */
3497 	if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
3498 		return 0;
3499 
3500 	/*
3501 	 * Either if a task, enters, leave, or stays -deadline but changes
3502 	 * its parameters, we may need to update accordingly the total
3503 	 * allocated bandwidth of the container.
3504 	 */
3505 	raw_spin_lock(&dl_b->lock);
3506 	cpus = dl_bw_cpus(cpu);
3507 	cap = dl_bw_capacity(cpu);
3508 
3509 	if (dl_policy(policy) && !task_has_dl_policy(p) &&
3510 	    !__dl_overflow(dl_b, cap, 0, new_bw)) {
3511 		if (hrtimer_active(&p->dl.inactive_timer))
3512 			__dl_sub(dl_b, p->dl.dl_bw, cpus);
3513 		__dl_add(dl_b, new_bw, cpus);
3514 		err = 0;
3515 	} else if (dl_policy(policy) && task_has_dl_policy(p) &&
3516 		   !__dl_overflow(dl_b, cap, p->dl.dl_bw, new_bw)) {
3517 		/*
3518 		 * XXX this is slightly incorrect: when the task
3519 		 * utilization decreases, we should delay the total
3520 		 * utilization change until the task's 0-lag point.
3521 		 * But this would require to set the task's "inactive
3522 		 * timer" when the task is not inactive.
3523 		 */
3524 		__dl_sub(dl_b, p->dl.dl_bw, cpus);
3525 		__dl_add(dl_b, new_bw, cpus);
3526 		dl_change_utilization(p, new_bw);
3527 		err = 0;
3528 	} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
3529 		/*
3530 		 * Do not decrease the total deadline utilization here,
3531 		 * switched_from_dl() will take care to do it at the correct
3532 		 * (0-lag) time.
3533 		 */
3534 		err = 0;
3535 	}
3536 	raw_spin_unlock(&dl_b->lock);
3537 
3538 	return err;
3539 }
3540 
3541 /*
3542  * This function initializes the sched_dl_entity of a newly becoming
3543  * SCHED_DEADLINE task.
3544  *
3545  * Only the static values are considered here, the actual runtime and the
3546  * absolute deadline will be properly calculated when the task is enqueued
3547  * for the first time with its new policy.
3548  */
__setparam_dl(struct task_struct * p,const struct sched_attr * attr)3549 void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3550 {
3551 	struct sched_dl_entity *dl_se = &p->dl;
3552 
3553 	dl_se->dl_runtime = attr->sched_runtime;
3554 	dl_se->dl_deadline = attr->sched_deadline;
3555 	dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3556 	dl_se->flags = attr->sched_flags & SCHED_DL_FLAGS;
3557 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3558 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
3559 }
3560 
__getparam_dl(struct task_struct * p,struct sched_attr * attr)3561 void __getparam_dl(struct task_struct *p, struct sched_attr *attr)
3562 {
3563 	struct sched_dl_entity *dl_se = &p->dl;
3564 
3565 	attr->sched_priority = p->rt_priority;
3566 	attr->sched_runtime = dl_se->dl_runtime;
3567 	attr->sched_deadline = dl_se->dl_deadline;
3568 	attr->sched_period = dl_se->dl_period;
3569 	attr->sched_flags &= ~SCHED_DL_FLAGS;
3570 	attr->sched_flags |= dl_se->flags;
3571 }
3572 
3573 /*
3574  * This function validates the new parameters of a -deadline task.
3575  * We ask for the deadline not being zero, and greater or equal
3576  * than the runtime, as well as the period of being zero or
3577  * greater than deadline. Furthermore, we have to be sure that
3578  * user parameters are above the internal resolution of 1us (we
3579  * check sched_runtime only since it is always the smaller one) and
3580  * below 2^63 ns (we have to check both sched_deadline and
3581  * sched_period, as the latter can be zero).
3582  */
__checkparam_dl(const struct sched_attr * attr)3583 bool __checkparam_dl(const struct sched_attr *attr)
3584 {
3585 	u64 period, max, min;
3586 
3587 	/* special dl tasks don't actually use any parameter */
3588 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
3589 		return true;
3590 
3591 	/* deadline != 0 */
3592 	if (attr->sched_deadline == 0)
3593 		return false;
3594 
3595 	/*
3596 	 * Since we truncate DL_SCALE bits, make sure we're at least
3597 	 * that big.
3598 	 */
3599 	if (attr->sched_runtime < (1ULL << DL_SCALE))
3600 		return false;
3601 
3602 	/*
3603 	 * Since we use the MSB for wrap-around and sign issues, make
3604 	 * sure it's not set (mind that period can be equal to zero).
3605 	 */
3606 	if (attr->sched_deadline & (1ULL << 63) ||
3607 	    attr->sched_period & (1ULL << 63))
3608 		return false;
3609 
3610 	period = attr->sched_period;
3611 	if (!period)
3612 		period = attr->sched_deadline;
3613 
3614 	/* runtime <= deadline <= period (if period != 0) */
3615 	if (period < attr->sched_deadline ||
3616 	    attr->sched_deadline < attr->sched_runtime)
3617 		return false;
3618 
3619 	max = (u64)READ_ONCE(sysctl_sched_dl_period_max) * NSEC_PER_USEC;
3620 	min = (u64)READ_ONCE(sysctl_sched_dl_period_min) * NSEC_PER_USEC;
3621 
3622 	if (period < min || period > max)
3623 		return false;
3624 
3625 	return true;
3626 }
3627 
3628 /*
3629  * This function clears the sched_dl_entity static params.
3630  */
__dl_clear_params(struct sched_dl_entity * dl_se)3631 static void __dl_clear_params(struct sched_dl_entity *dl_se)
3632 {
3633 	dl_se->dl_runtime		= 0;
3634 	dl_se->dl_deadline		= 0;
3635 	dl_se->dl_period		= 0;
3636 	dl_se->flags			= 0;
3637 	dl_se->dl_bw			= 0;
3638 	dl_se->dl_density		= 0;
3639 
3640 	dl_se->dl_throttled		= 0;
3641 	dl_se->dl_yielded		= 0;
3642 	dl_se->dl_non_contending	= 0;
3643 	dl_se->dl_overrun		= 0;
3644 	dl_se->dl_server		= 0;
3645 
3646 #ifdef CONFIG_RT_MUTEXES
3647 	dl_se->pi_se			= dl_se;
3648 #endif
3649 }
3650 
init_dl_entity(struct sched_dl_entity * dl_se)3651 void init_dl_entity(struct sched_dl_entity *dl_se)
3652 {
3653 	RB_CLEAR_NODE(&dl_se->rb_node);
3654 	init_dl_task_timer(dl_se);
3655 	init_dl_inactive_task_timer(dl_se);
3656 	__dl_clear_params(dl_se);
3657 }
3658 
dl_param_changed(struct task_struct * p,const struct sched_attr * attr)3659 bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
3660 {
3661 	struct sched_dl_entity *dl_se = &p->dl;
3662 
3663 	if (dl_se->dl_runtime != attr->sched_runtime ||
3664 	    dl_se->dl_deadline != attr->sched_deadline ||
3665 	    dl_se->dl_period != attr->sched_period ||
3666 	    dl_se->flags != (attr->sched_flags & SCHED_DL_FLAGS))
3667 		return true;
3668 
3669 	return false;
3670 }
3671 
dl_cpuset_cpumask_can_shrink(const struct cpumask * cur,const struct cpumask * trial)3672 int dl_cpuset_cpumask_can_shrink(const struct cpumask *cur,
3673 				 const struct cpumask *trial)
3674 {
3675 	unsigned long flags, cap;
3676 	struct dl_bw *cur_dl_b;
3677 	int ret = 1;
3678 
3679 	rcu_read_lock_sched();
3680 	cur_dl_b = dl_bw_of(cpumask_any(cur));
3681 	cap = __dl_bw_capacity(trial);
3682 	raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
3683 	if (__dl_overflow(cur_dl_b, cap, 0, 0))
3684 		ret = 0;
3685 	raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
3686 	rcu_read_unlock_sched();
3687 
3688 	return ret;
3689 }
3690 
3691 enum dl_bw_request {
3692 	dl_bw_req_deactivate = 0,
3693 	dl_bw_req_alloc,
3694 	dl_bw_req_free
3695 };
3696 
dl_bw_manage(enum dl_bw_request req,int cpu,u64 dl_bw)3697 static int dl_bw_manage(enum dl_bw_request req, int cpu, u64 dl_bw)
3698 {
3699 	unsigned long flags, cap;
3700 	struct dl_bw *dl_b;
3701 	bool overflow = 0;
3702 	u64 fair_server_bw = 0;
3703 
3704 	rcu_read_lock_sched();
3705 	dl_b = dl_bw_of(cpu);
3706 	raw_spin_lock_irqsave(&dl_b->lock, flags);
3707 
3708 	cap = dl_bw_capacity(cpu);
3709 	switch (req) {
3710 	case dl_bw_req_free:
3711 		__dl_sub(dl_b, dl_bw, dl_bw_cpus(cpu));
3712 		break;
3713 	case dl_bw_req_alloc:
3714 		overflow = __dl_overflow(dl_b, cap, 0, dl_bw);
3715 
3716 		if (!overflow) {
3717 			/*
3718 			 * We reserve space in the destination
3719 			 * root_domain, as we can't fail after this point.
3720 			 * We will free resources in the source root_domain
3721 			 * later on (see set_cpus_allowed_dl()).
3722 			 */
3723 			__dl_add(dl_b, dl_bw, dl_bw_cpus(cpu));
3724 		}
3725 		break;
3726 	case dl_bw_req_deactivate:
3727 		/*
3728 		 * cpu is not off yet, but we need to do the math by
3729 		 * considering it off already (i.e., what would happen if we
3730 		 * turn cpu off?).
3731 		 */
3732 		cap -= arch_scale_cpu_capacity(cpu);
3733 
3734 		/*
3735 		 * cpu is going offline and NORMAL tasks will be moved away
3736 		 * from it. We can thus discount dl_server bandwidth
3737 		 * contribution as it won't need to be servicing tasks after
3738 		 * the cpu is off.
3739 		 */
3740 		if (cpu_rq(cpu)->fair_server.dl_server)
3741 			fair_server_bw = cpu_rq(cpu)->fair_server.dl_bw;
3742 
3743 		/*
3744 		 * Not much to check if no DEADLINE bandwidth is present.
3745 		 * dl_servers we can discount, as tasks will be moved out the
3746 		 * offlined CPUs anyway.
3747 		 */
3748 		if (dl_b->total_bw - fair_server_bw > 0) {
3749 			/*
3750 			 * Leaving at least one CPU for DEADLINE tasks seems a
3751 			 * wise thing to do. As said above, cpu is not offline
3752 			 * yet, so account for that.
3753 			 */
3754 			if (dl_bw_cpus(cpu) - 1)
3755 				overflow = __dl_overflow(dl_b, cap, fair_server_bw, 0);
3756 			else
3757 				overflow = 1;
3758 		}
3759 
3760 		break;
3761 	}
3762 
3763 	raw_spin_unlock_irqrestore(&dl_b->lock, flags);
3764 	rcu_read_unlock_sched();
3765 
3766 	return overflow ? -EBUSY : 0;
3767 }
3768 
dl_bw_deactivate(int cpu)3769 int dl_bw_deactivate(int cpu)
3770 {
3771 	return dl_bw_manage(dl_bw_req_deactivate, cpu, 0);
3772 }
3773 
dl_bw_alloc(int cpu,u64 dl_bw)3774 int dl_bw_alloc(int cpu, u64 dl_bw)
3775 {
3776 	return dl_bw_manage(dl_bw_req_alloc, cpu, dl_bw);
3777 }
3778 
dl_bw_free(int cpu,u64 dl_bw)3779 void dl_bw_free(int cpu, u64 dl_bw)
3780 {
3781 	dl_bw_manage(dl_bw_req_free, cpu, dl_bw);
3782 }
3783 
print_dl_stats(struct seq_file * m,int cpu)3784 void print_dl_stats(struct seq_file *m, int cpu)
3785 {
3786 	print_dl_rq(m, cpu, &cpu_rq(cpu)->dl);
3787 }
3788