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