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