• 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 dl_rq * dl_rq)1853 static struct sched_dl_entity *pick_next_dl_entity(struct dl_rq *dl_rq)
1854 {
1855 	struct rb_node *left = rb_first_cached(&dl_rq->root);
1856 
1857 	if (!left)
1858 		return NULL;
1859 
1860 	return rb_entry(left, struct sched_dl_entity, rb_node);
1861 }
1862 
pick_next_task_dl(struct rq * rq)1863 static struct task_struct *pick_next_task_dl(struct rq *rq)
1864 {
1865 	struct sched_dl_entity *dl_se;
1866 	struct dl_rq *dl_rq = &rq->dl;
1867 	struct task_struct *p;
1868 
1869 	if (!sched_dl_runnable(rq))
1870 		return NULL;
1871 
1872 	dl_se = pick_next_dl_entity(dl_rq);
1873 	BUG_ON(!dl_se);
1874 	p = dl_task_of(dl_se);
1875 	set_next_task_dl(rq, p, true);
1876 	return p;
1877 }
1878 
put_prev_task_dl(struct rq * rq,struct task_struct * p)1879 static void put_prev_task_dl(struct rq *rq, struct task_struct *p)
1880 {
1881 	update_curr_dl(rq);
1882 
1883 	update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 1);
1884 	if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1)
1885 		enqueue_pushable_dl_task(rq, p);
1886 }
1887 
1888 /*
1889  * scheduler tick hitting a task of our scheduling class.
1890  *
1891  * NOTE: This function can be called remotely by the tick offload that
1892  * goes along full dynticks. Therefore no local assumption can be made
1893  * and everything must be accessed through the @rq and @curr passed in
1894  * parameters.
1895  */
task_tick_dl(struct rq * rq,struct task_struct * p,int queued)1896 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued)
1897 {
1898 	update_curr_dl(rq);
1899 
1900 	update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 1);
1901 	/*
1902 	 * Even when we have runtime, update_curr_dl() might have resulted in us
1903 	 * not being the leftmost task anymore. In that case NEED_RESCHED will
1904 	 * be set and schedule() will start a new hrtick for the next task.
1905 	 */
1906 	if (hrtick_enabled(rq) && queued && p->dl.runtime > 0 &&
1907 	    is_leftmost(p, &rq->dl))
1908 		start_hrtick_dl(rq, p);
1909 }
1910 
task_fork_dl(struct task_struct * p)1911 static void task_fork_dl(struct task_struct *p)
1912 {
1913 	/*
1914 	 * SCHED_DEADLINE tasks cannot fork and this is achieved through
1915 	 * sched_fork()
1916 	 */
1917 }
1918 
1919 #ifdef CONFIG_SMP
1920 
1921 /* Only try algorithms three times */
1922 #define DL_MAX_TRIES 3
1923 
pick_dl_task(struct rq * rq,struct task_struct * p,int cpu)1924 static int pick_dl_task(struct rq *rq, struct task_struct *p, int cpu)
1925 {
1926 	if (!task_running(rq, p) &&
1927 	    cpumask_test_cpu(cpu, p->cpus_ptr))
1928 		return 1;
1929 	return 0;
1930 }
1931 
1932 /*
1933  * Return the earliest pushable rq's task, which is suitable to be executed
1934  * on the CPU, NULL otherwise:
1935  */
pick_earliest_pushable_dl_task(struct rq * rq,int cpu)1936 static struct task_struct *pick_earliest_pushable_dl_task(struct rq *rq, int cpu)
1937 {
1938 	struct rb_node *next_node = rq->dl.pushable_dl_tasks_root.rb_leftmost;
1939 	struct task_struct *p = NULL;
1940 
1941 	if (!has_pushable_dl_tasks(rq))
1942 		return NULL;
1943 
1944 next_node:
1945 	if (next_node) {
1946 		p = rb_entry(next_node, struct task_struct, pushable_dl_tasks);
1947 
1948 		if (pick_dl_task(rq, p, cpu))
1949 			return p;
1950 
1951 		next_node = rb_next(next_node);
1952 		goto next_node;
1953 	}
1954 
1955 	return NULL;
1956 }
1957 
1958 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
1959 
find_later_rq(struct task_struct * task)1960 static int find_later_rq(struct task_struct *task)
1961 {
1962 	struct sched_domain *sd;
1963 	struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
1964 	int this_cpu = smp_processor_id();
1965 	int cpu = task_cpu(task);
1966 
1967 	/* Make sure the mask is initialized first */
1968 	if (unlikely(!later_mask))
1969 		return -1;
1970 
1971 	if (task->nr_cpus_allowed == 1)
1972 		return -1;
1973 
1974 	/*
1975 	 * We have to consider system topology and task affinity
1976 	 * first, then we can look for a suitable CPU.
1977 	 */
1978 	if (!cpudl_find(&task_rq(task)->rd->cpudl, task, later_mask))
1979 		return -1;
1980 
1981 	/*
1982 	 * If we are here, some targets have been found, including
1983 	 * the most suitable which is, among the runqueues where the
1984 	 * current tasks have later deadlines than the task's one, the
1985 	 * rq with the latest possible one.
1986 	 *
1987 	 * Now we check how well this matches with task's
1988 	 * affinity and system topology.
1989 	 *
1990 	 * The last CPU where the task run is our first
1991 	 * guess, since it is most likely cache-hot there.
1992 	 */
1993 	if (cpumask_test_cpu(cpu, later_mask))
1994 		return cpu;
1995 	/*
1996 	 * Check if this_cpu is to be skipped (i.e., it is
1997 	 * not in the mask) or not.
1998 	 */
1999 	if (!cpumask_test_cpu(this_cpu, later_mask))
2000 		this_cpu = -1;
2001 
2002 	rcu_read_lock();
2003 	for_each_domain(cpu, sd) {
2004 		if (sd->flags & SD_WAKE_AFFINE) {
2005 			int best_cpu;
2006 
2007 			/*
2008 			 * If possible, preempting this_cpu is
2009 			 * cheaper than migrating.
2010 			 */
2011 			if (this_cpu != -1 &&
2012 			    cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
2013 				rcu_read_unlock();
2014 				return this_cpu;
2015 			}
2016 
2017 			best_cpu = cpumask_first_and(later_mask,
2018 							sched_domain_span(sd));
2019 			/*
2020 			 * Last chance: if a CPU being in both later_mask
2021 			 * and current sd span is valid, that becomes our
2022 			 * choice. Of course, the latest possible CPU is
2023 			 * already under consideration through later_mask.
2024 			 */
2025 			if (best_cpu < nr_cpu_ids) {
2026 				rcu_read_unlock();
2027 				return best_cpu;
2028 			}
2029 		}
2030 	}
2031 	rcu_read_unlock();
2032 
2033 	/*
2034 	 * At this point, all our guesses failed, we just return
2035 	 * 'something', and let the caller sort the things out.
2036 	 */
2037 	if (this_cpu != -1)
2038 		return this_cpu;
2039 
2040 	cpu = cpumask_any(later_mask);
2041 	if (cpu < nr_cpu_ids)
2042 		return cpu;
2043 
2044 	return -1;
2045 }
2046 
pick_next_pushable_dl_task(struct rq * rq)2047 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq)
2048 {
2049 	struct task_struct *p;
2050 
2051 	if (!has_pushable_dl_tasks(rq))
2052 		return NULL;
2053 
2054 	p = rb_entry(rq->dl.pushable_dl_tasks_root.rb_leftmost,
2055 		     struct task_struct, pushable_dl_tasks);
2056 
2057 	BUG_ON(rq->cpu != task_cpu(p));
2058 	BUG_ON(task_current(rq, p));
2059 	BUG_ON(p->nr_cpus_allowed <= 1);
2060 
2061 	BUG_ON(!task_on_rq_queued(p));
2062 	BUG_ON(!dl_task(p));
2063 
2064 	return p;
2065 }
2066 
2067 /* Locks the rq it finds */
find_lock_later_rq(struct task_struct * task,struct rq * rq)2068 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq)
2069 {
2070 	struct rq *later_rq = NULL;
2071 	int tries;
2072 	int cpu;
2073 
2074 	for (tries = 0; tries < DL_MAX_TRIES; tries++) {
2075 		cpu = find_later_rq(task);
2076 
2077 		if ((cpu == -1) || (cpu == rq->cpu))
2078 			break;
2079 
2080 		later_rq = cpu_rq(cpu);
2081 
2082 		if (later_rq->dl.dl_nr_running &&
2083 		    !dl_time_before(task->dl.deadline,
2084 					later_rq->dl.earliest_dl.curr)) {
2085 			/*
2086 			 * Target rq has tasks of equal or earlier deadline,
2087 			 * retrying does not release any lock and is unlikely
2088 			 * to yield a different result.
2089 			 */
2090 			later_rq = NULL;
2091 			break;
2092 		}
2093 
2094 		/* Retry if something changed. */
2095 		if (double_lock_balance(rq, later_rq)) {
2096 			struct task_struct *next_task;
2097 			/*
2098 			 * We had to unlock the run queue. In
2099 			 * the mean time, task could have
2100 			 * migrated already or had its affinity changed.
2101 			 * Also make sure that it wasn't scheduled on its rq.
2102 			 */
2103 			next_task = pick_next_pushable_dl_task(rq);
2104 			if (unlikely(next_task != task ||
2105 						!cpumask_test_cpu(later_rq->cpu, task->cpus_ptr))) {
2106 				double_unlock_balance(rq, later_rq);
2107 				later_rq = NULL;
2108 				break;
2109 			}
2110 		}
2111 
2112 		/*
2113 		 * If the rq we found has no -deadline task, or
2114 		 * its earliest one has a later deadline than our
2115 		 * task, the rq is a good one.
2116 		 */
2117 		if (!later_rq->dl.dl_nr_running ||
2118 		    dl_time_before(task->dl.deadline,
2119 				   later_rq->dl.earliest_dl.curr))
2120 			break;
2121 
2122 		/* Otherwise we try again. */
2123 		double_unlock_balance(rq, later_rq);
2124 		later_rq = NULL;
2125 	}
2126 
2127 	return later_rq;
2128 }
2129 
2130 /*
2131  * See if the non running -deadline tasks on this rq
2132  * can be sent to some other CPU where they can preempt
2133  * and start executing.
2134  */
push_dl_task(struct rq * rq)2135 static int push_dl_task(struct rq *rq)
2136 {
2137 	struct task_struct *next_task;
2138 	struct rq *later_rq;
2139 	int ret = 0;
2140 
2141 	if (!rq->dl.overloaded)
2142 		return 0;
2143 
2144 	next_task = pick_next_pushable_dl_task(rq);
2145 	if (!next_task)
2146 		return 0;
2147 
2148 retry:
2149 	if (WARN_ON(next_task == rq->curr))
2150 		return 0;
2151 
2152 	/*
2153 	 * If next_task preempts rq->curr, and rq->curr
2154 	 * can move away, it makes sense to just reschedule
2155 	 * without going further in pushing next_task.
2156 	 */
2157 	if (dl_task(rq->curr) &&
2158 	    dl_time_before(next_task->dl.deadline, rq->curr->dl.deadline) &&
2159 	    rq->curr->nr_cpus_allowed > 1) {
2160 		resched_curr(rq);
2161 		return 0;
2162 	}
2163 
2164 	/* We might release rq lock */
2165 	get_task_struct(next_task);
2166 
2167 	/* Will lock the rq it'll find */
2168 	later_rq = find_lock_later_rq(next_task, rq);
2169 	if (!later_rq) {
2170 		struct task_struct *task;
2171 
2172 		/*
2173 		 * We must check all this again, since
2174 		 * find_lock_later_rq releases rq->lock and it is
2175 		 * then possible that next_task has migrated.
2176 		 */
2177 		task = pick_next_pushable_dl_task(rq);
2178 		if (task == next_task) {
2179 			/*
2180 			 * The task is still there. We don't try
2181 			 * again, some other CPU will pull it when ready.
2182 			 */
2183 			goto out;
2184 		}
2185 
2186 		if (!task)
2187 			/* No more tasks */
2188 			goto out;
2189 
2190 		put_task_struct(next_task);
2191 		next_task = task;
2192 		goto retry;
2193 	}
2194 
2195 	deactivate_task(rq, next_task, 0);
2196 	set_task_cpu(next_task, later_rq->cpu);
2197 
2198 	/*
2199 	 * Update the later_rq clock here, because the clock is used
2200 	 * by the cpufreq_update_util() inside __add_running_bw().
2201 	 */
2202 	update_rq_clock(later_rq);
2203 	activate_task(later_rq, next_task, ENQUEUE_NOCLOCK);
2204 	ret = 1;
2205 
2206 	resched_curr(later_rq);
2207 
2208 	double_unlock_balance(rq, later_rq);
2209 
2210 out:
2211 	put_task_struct(next_task);
2212 
2213 	return ret;
2214 }
2215 
push_dl_tasks(struct rq * rq)2216 static void push_dl_tasks(struct rq *rq)
2217 {
2218 	/* push_dl_task() will return true if it moved a -deadline task */
2219 	while (push_dl_task(rq))
2220 		;
2221 }
2222 
pull_dl_task(struct rq * this_rq)2223 static void pull_dl_task(struct rq *this_rq)
2224 {
2225 	int this_cpu = this_rq->cpu, cpu;
2226 	struct task_struct *p;
2227 	bool resched = false;
2228 	struct rq *src_rq;
2229 	u64 dmin = LONG_MAX;
2230 
2231 	if (likely(!dl_overloaded(this_rq)))
2232 		return;
2233 
2234 	/*
2235 	 * Match the barrier from dl_set_overloaded; this guarantees that if we
2236 	 * see overloaded we must also see the dlo_mask bit.
2237 	 */
2238 	smp_rmb();
2239 
2240 	for_each_cpu(cpu, this_rq->rd->dlo_mask) {
2241 		if (this_cpu == cpu)
2242 			continue;
2243 
2244 		src_rq = cpu_rq(cpu);
2245 
2246 		/*
2247 		 * It looks racy, abd it is! However, as in sched_rt.c,
2248 		 * we are fine with this.
2249 		 */
2250 		if (this_rq->dl.dl_nr_running &&
2251 		    dl_time_before(this_rq->dl.earliest_dl.curr,
2252 				   src_rq->dl.earliest_dl.next))
2253 			continue;
2254 
2255 		/* Might drop this_rq->lock */
2256 		double_lock_balance(this_rq, src_rq);
2257 
2258 		/*
2259 		 * If there are no more pullable tasks on the
2260 		 * rq, we're done with it.
2261 		 */
2262 		if (src_rq->dl.dl_nr_running <= 1)
2263 			goto skip;
2264 
2265 		p = pick_earliest_pushable_dl_task(src_rq, this_cpu);
2266 
2267 		/*
2268 		 * We found a task to be pulled if:
2269 		 *  - it preempts our current (if there's one),
2270 		 *  - it will preempt the last one we pulled (if any).
2271 		 */
2272 		if (p && dl_time_before(p->dl.deadline, dmin) &&
2273 		    (!this_rq->dl.dl_nr_running ||
2274 		     dl_time_before(p->dl.deadline,
2275 				    this_rq->dl.earliest_dl.curr))) {
2276 			WARN_ON(p == src_rq->curr);
2277 			WARN_ON(!task_on_rq_queued(p));
2278 
2279 			/*
2280 			 * Then we pull iff p has actually an earlier
2281 			 * deadline than the current task of its runqueue.
2282 			 */
2283 			if (dl_time_before(p->dl.deadline,
2284 					   src_rq->curr->dl.deadline))
2285 				goto skip;
2286 
2287 			resched = true;
2288 
2289 			deactivate_task(src_rq, p, 0);
2290 			set_task_cpu(p, this_cpu);
2291 			activate_task(this_rq, p, 0);
2292 			dmin = p->dl.deadline;
2293 
2294 			/* Is there any other task even earlier? */
2295 		}
2296 skip:
2297 		double_unlock_balance(this_rq, src_rq);
2298 	}
2299 
2300 	if (resched)
2301 		resched_curr(this_rq);
2302 }
2303 
2304 /*
2305  * Since the task is not running and a reschedule is not going to happen
2306  * anytime soon on its runqueue, we try pushing it away now.
2307  */
task_woken_dl(struct rq * rq,struct task_struct * p)2308 static void task_woken_dl(struct rq *rq, struct task_struct *p)
2309 {
2310 	if (!task_running(rq, p) &&
2311 	    !test_tsk_need_resched(rq->curr) &&
2312 	    p->nr_cpus_allowed > 1 &&
2313 	    dl_task(rq->curr) &&
2314 	    (rq->curr->nr_cpus_allowed < 2 ||
2315 	     !dl_entity_preempt(&p->dl, &rq->curr->dl))) {
2316 		push_dl_tasks(rq);
2317 	}
2318 }
2319 
set_cpus_allowed_dl(struct task_struct * p,const struct cpumask * new_mask)2320 static void set_cpus_allowed_dl(struct task_struct *p,
2321 				const struct cpumask *new_mask)
2322 {
2323 	struct root_domain *src_rd;
2324 	struct rq *rq;
2325 
2326 	BUG_ON(!dl_task(p));
2327 
2328 	rq = task_rq(p);
2329 	src_rd = rq->rd;
2330 	/*
2331 	 * Migrating a SCHED_DEADLINE task between exclusive
2332 	 * cpusets (different root_domains) entails a bandwidth
2333 	 * update. We already made space for us in the destination
2334 	 * domain (see cpuset_can_attach()).
2335 	 */
2336 	if (!cpumask_intersects(src_rd->span, new_mask)) {
2337 		struct dl_bw *src_dl_b;
2338 
2339 		src_dl_b = dl_bw_of(cpu_of(rq));
2340 		/*
2341 		 * We now free resources of the root_domain we are migrating
2342 		 * off. In the worst case, sched_setattr() may temporary fail
2343 		 * until we complete the update.
2344 		 */
2345 		raw_spin_lock(&src_dl_b->lock);
2346 		__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
2347 		raw_spin_unlock(&src_dl_b->lock);
2348 	}
2349 
2350 	set_cpus_allowed_common(p, new_mask);
2351 }
2352 
2353 /* Assumes rq->lock is held */
rq_online_dl(struct rq * rq)2354 static void rq_online_dl(struct rq *rq)
2355 {
2356 	if (rq->dl.overloaded)
2357 		dl_set_overload(rq);
2358 
2359 	cpudl_set_freecpu(&rq->rd->cpudl, rq->cpu);
2360 	if (rq->dl.dl_nr_running > 0)
2361 		cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr);
2362 }
2363 
2364 /* Assumes rq->lock is held */
rq_offline_dl(struct rq * rq)2365 static void rq_offline_dl(struct rq *rq)
2366 {
2367 	if (rq->dl.overloaded)
2368 		dl_clear_overload(rq);
2369 
2370 	cpudl_clear(&rq->rd->cpudl, rq->cpu);
2371 	cpudl_clear_freecpu(&rq->rd->cpudl, rq->cpu);
2372 }
2373 
init_sched_dl_class(void)2374 void __init init_sched_dl_class(void)
2375 {
2376 	unsigned int i;
2377 
2378 	for_each_possible_cpu(i)
2379 		zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
2380 					GFP_KERNEL, cpu_to_node(i));
2381 }
2382 
dl_add_task_root_domain(struct task_struct * p)2383 void dl_add_task_root_domain(struct task_struct *p)
2384 {
2385 	struct rq_flags rf;
2386 	struct rq *rq;
2387 	struct dl_bw *dl_b;
2388 
2389 	rq = task_rq_lock(p, &rf);
2390 	if (!dl_task(p))
2391 		goto unlock;
2392 
2393 	dl_b = &rq->rd->dl_bw;
2394 	raw_spin_lock(&dl_b->lock);
2395 
2396 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
2397 
2398 	raw_spin_unlock(&dl_b->lock);
2399 
2400 unlock:
2401 	task_rq_unlock(rq, p, &rf);
2402 }
2403 
dl_clear_root_domain(struct root_domain * rd)2404 void dl_clear_root_domain(struct root_domain *rd)
2405 {
2406 	unsigned long flags;
2407 
2408 	raw_spin_lock_irqsave(&rd->dl_bw.lock, flags);
2409 	rd->dl_bw.total_bw = 0;
2410 	raw_spin_unlock_irqrestore(&rd->dl_bw.lock, flags);
2411 }
2412 
2413 #endif /* CONFIG_SMP */
2414 
switched_from_dl(struct rq * rq,struct task_struct * p)2415 static void switched_from_dl(struct rq *rq, struct task_struct *p)
2416 {
2417 	/*
2418 	 * task_non_contending() can start the "inactive timer" (if the 0-lag
2419 	 * time is in the future). If the task switches back to dl before
2420 	 * the "inactive timer" fires, it can continue to consume its current
2421 	 * runtime using its current deadline. If it stays outside of
2422 	 * SCHED_DEADLINE until the 0-lag time passes, inactive_task_timer()
2423 	 * will reset the task parameters.
2424 	 */
2425 	if (task_on_rq_queued(p) && p->dl.dl_runtime)
2426 		task_non_contending(p);
2427 
2428 	if (!task_on_rq_queued(p)) {
2429 		/*
2430 		 * Inactive timer is armed. However, p is leaving DEADLINE and
2431 		 * might migrate away from this rq while continuing to run on
2432 		 * some other class. We need to remove its contribution from
2433 		 * this rq running_bw now, or sub_rq_bw (below) will complain.
2434 		 */
2435 		if (p->dl.dl_non_contending)
2436 			sub_running_bw(&p->dl, &rq->dl);
2437 		sub_rq_bw(&p->dl, &rq->dl);
2438 	}
2439 
2440 	/*
2441 	 * We cannot use inactive_task_timer() to invoke sub_running_bw()
2442 	 * at the 0-lag time, because the task could have been migrated
2443 	 * while SCHED_OTHER in the meanwhile.
2444 	 */
2445 	if (p->dl.dl_non_contending)
2446 		p->dl.dl_non_contending = 0;
2447 
2448 	/*
2449 	 * Since this might be the only -deadline task on the rq,
2450 	 * this is the right place to try to pull some other one
2451 	 * from an overloaded CPU, if any.
2452 	 */
2453 	if (!task_on_rq_queued(p) || rq->dl.dl_nr_running)
2454 		return;
2455 
2456 	deadline_queue_pull_task(rq);
2457 }
2458 
2459 /*
2460  * When switching to -deadline, we may overload the rq, then
2461  * we try to push someone off, if possible.
2462  */
switched_to_dl(struct rq * rq,struct task_struct * p)2463 static void switched_to_dl(struct rq *rq, struct task_struct *p)
2464 {
2465 	if (hrtimer_try_to_cancel(&p->dl.inactive_timer) == 1)
2466 		put_task_struct(p);
2467 
2468 	/* If p is not queued we will update its parameters at next wakeup. */
2469 	if (!task_on_rq_queued(p)) {
2470 		add_rq_bw(&p->dl, &rq->dl);
2471 
2472 		return;
2473 	}
2474 
2475 	if (rq->curr != p) {
2476 #ifdef CONFIG_SMP
2477 		if (p->nr_cpus_allowed > 1 && rq->dl.overloaded)
2478 			deadline_queue_push_tasks(rq);
2479 #endif
2480 		if (dl_task(rq->curr))
2481 			check_preempt_curr_dl(rq, p, 0);
2482 		else
2483 			resched_curr(rq);
2484 	} else {
2485 		update_dl_rq_load_avg(rq_clock_pelt(rq), rq, 0);
2486 	}
2487 }
2488 
2489 /*
2490  * If the scheduling parameters of a -deadline task changed,
2491  * a push or pull operation might be needed.
2492  */
prio_changed_dl(struct rq * rq,struct task_struct * p,int oldprio)2493 static void prio_changed_dl(struct rq *rq, struct task_struct *p,
2494 			    int oldprio)
2495 {
2496 	if (task_on_rq_queued(p) || rq->curr == p) {
2497 #ifdef CONFIG_SMP
2498 		/*
2499 		 * This might be too much, but unfortunately
2500 		 * we don't have the old deadline value, and
2501 		 * we can't argue if the task is increasing
2502 		 * or lowering its prio, so...
2503 		 */
2504 		if (!rq->dl.overloaded)
2505 			deadline_queue_pull_task(rq);
2506 
2507 		/*
2508 		 * If we now have a earlier deadline task than p,
2509 		 * then reschedule, provided p is still on this
2510 		 * runqueue.
2511 		 */
2512 		if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline))
2513 			resched_curr(rq);
2514 #else
2515 		/*
2516 		 * Again, we don't know if p has a earlier
2517 		 * or later deadline, so let's blindly set a
2518 		 * (maybe not needed) rescheduling point.
2519 		 */
2520 		resched_curr(rq);
2521 #endif /* CONFIG_SMP */
2522 	}
2523 }
2524 
2525 const struct sched_class dl_sched_class
2526 	__section("__dl_sched_class") = {
2527 	.enqueue_task		= enqueue_task_dl,
2528 	.dequeue_task		= dequeue_task_dl,
2529 	.yield_task		= yield_task_dl,
2530 
2531 	.check_preempt_curr	= check_preempt_curr_dl,
2532 
2533 	.pick_next_task		= pick_next_task_dl,
2534 	.put_prev_task		= put_prev_task_dl,
2535 	.set_next_task		= set_next_task_dl,
2536 
2537 #ifdef CONFIG_SMP
2538 	.balance		= balance_dl,
2539 	.select_task_rq		= select_task_rq_dl,
2540 	.migrate_task_rq	= migrate_task_rq_dl,
2541 	.set_cpus_allowed       = set_cpus_allowed_dl,
2542 	.rq_online              = rq_online_dl,
2543 	.rq_offline             = rq_offline_dl,
2544 	.task_woken		= task_woken_dl,
2545 #endif
2546 
2547 	.task_tick		= task_tick_dl,
2548 	.task_fork              = task_fork_dl,
2549 
2550 	.prio_changed           = prio_changed_dl,
2551 	.switched_from		= switched_from_dl,
2552 	.switched_to		= switched_to_dl,
2553 
2554 	.update_curr		= update_curr_dl,
2555 #ifdef CONFIG_SCHED_WALT
2556 	.fixup_walt_sched_stats	= fixup_walt_sched_stats_common,
2557 #endif
2558 };
2559 
sched_dl_global_validate(void)2560 int sched_dl_global_validate(void)
2561 {
2562 	u64 runtime = global_rt_runtime();
2563 	u64 period = global_rt_period();
2564 	u64 new_bw = to_ratio(period, runtime);
2565 	struct dl_bw *dl_b;
2566 	int cpu, cpus, ret = 0;
2567 	unsigned long flags;
2568 
2569 	/*
2570 	 * Here we want to check the bandwidth not being set to some
2571 	 * value smaller than the currently allocated bandwidth in
2572 	 * any of the root_domains.
2573 	 *
2574 	 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
2575 	 * cycling on root_domains... Discussion on different/better
2576 	 * solutions is welcome!
2577 	 */
2578 	for_each_possible_cpu(cpu) {
2579 		rcu_read_lock_sched();
2580 		dl_b = dl_bw_of(cpu);
2581 		cpus = dl_bw_cpus(cpu);
2582 
2583 		raw_spin_lock_irqsave(&dl_b->lock, flags);
2584 		if (new_bw * cpus < dl_b->total_bw)
2585 			ret = -EBUSY;
2586 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2587 
2588 		rcu_read_unlock_sched();
2589 
2590 		if (ret)
2591 			break;
2592 	}
2593 
2594 	return ret;
2595 }
2596 
init_dl_rq_bw_ratio(struct dl_rq * dl_rq)2597 static void init_dl_rq_bw_ratio(struct dl_rq *dl_rq)
2598 {
2599 	if (global_rt_runtime() == RUNTIME_INF) {
2600 		dl_rq->bw_ratio = 1 << RATIO_SHIFT;
2601 		dl_rq->extra_bw = 1 << BW_SHIFT;
2602 	} else {
2603 		dl_rq->bw_ratio = to_ratio(global_rt_runtime(),
2604 			  global_rt_period()) >> (BW_SHIFT - RATIO_SHIFT);
2605 		dl_rq->extra_bw = to_ratio(global_rt_period(),
2606 						    global_rt_runtime());
2607 	}
2608 }
2609 
sched_dl_do_global(void)2610 void sched_dl_do_global(void)
2611 {
2612 	u64 new_bw = -1;
2613 	struct dl_bw *dl_b;
2614 	int cpu;
2615 	unsigned long flags;
2616 
2617 	def_dl_bandwidth.dl_period = global_rt_period();
2618 	def_dl_bandwidth.dl_runtime = global_rt_runtime();
2619 
2620 	if (global_rt_runtime() != RUNTIME_INF)
2621 		new_bw = to_ratio(global_rt_period(), global_rt_runtime());
2622 
2623 	/*
2624 	 * FIXME: As above...
2625 	 */
2626 	for_each_possible_cpu(cpu) {
2627 		rcu_read_lock_sched();
2628 		dl_b = dl_bw_of(cpu);
2629 
2630 		raw_spin_lock_irqsave(&dl_b->lock, flags);
2631 		dl_b->bw = new_bw;
2632 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2633 
2634 		rcu_read_unlock_sched();
2635 		init_dl_rq_bw_ratio(&cpu_rq(cpu)->dl);
2636 	}
2637 }
2638 
2639 /*
2640  * We must be sure that accepting a new task (or allowing changing the
2641  * parameters of an existing one) is consistent with the bandwidth
2642  * constraints. If yes, this function also accordingly updates the currently
2643  * allocated bandwidth to reflect the new situation.
2644  *
2645  * This function is called while holding p's rq->lock.
2646  */
sched_dl_overflow(struct task_struct * p,int policy,const struct sched_attr * attr)2647 int sched_dl_overflow(struct task_struct *p, int policy,
2648 		      const struct sched_attr *attr)
2649 {
2650 	u64 period = attr->sched_period ?: attr->sched_deadline;
2651 	u64 runtime = attr->sched_runtime;
2652 	u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2653 	int cpus, err = -1, cpu = task_cpu(p);
2654 	struct dl_bw *dl_b = dl_bw_of(cpu);
2655 	unsigned long cap;
2656 
2657 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
2658 		return 0;
2659 
2660 	/* !deadline task may carry old deadline bandwidth */
2661 	if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2662 		return 0;
2663 
2664 	/*
2665 	 * Either if a task, enters, leave, or stays -deadline but changes
2666 	 * its parameters, we may need to update accordingly the total
2667 	 * allocated bandwidth of the container.
2668 	 */
2669 	raw_spin_lock(&dl_b->lock);
2670 	cpus = dl_bw_cpus(cpu);
2671 	cap = dl_bw_capacity(cpu);
2672 
2673 	if (dl_policy(policy) && !task_has_dl_policy(p) &&
2674 	    !__dl_overflow(dl_b, cap, 0, new_bw)) {
2675 		if (hrtimer_active(&p->dl.inactive_timer))
2676 			__dl_sub(dl_b, p->dl.dl_bw, cpus);
2677 		__dl_add(dl_b, new_bw, cpus);
2678 		err = 0;
2679 	} else if (dl_policy(policy) && task_has_dl_policy(p) &&
2680 		   !__dl_overflow(dl_b, cap, p->dl.dl_bw, new_bw)) {
2681 		/*
2682 		 * XXX this is slightly incorrect: when the task
2683 		 * utilization decreases, we should delay the total
2684 		 * utilization change until the task's 0-lag point.
2685 		 * But this would require to set the task's "inactive
2686 		 * timer" when the task is not inactive.
2687 		 */
2688 		__dl_sub(dl_b, p->dl.dl_bw, cpus);
2689 		__dl_add(dl_b, new_bw, cpus);
2690 		dl_change_utilization(p, new_bw);
2691 		err = 0;
2692 	} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2693 		/*
2694 		 * Do not decrease the total deadline utilization here,
2695 		 * switched_from_dl() will take care to do it at the correct
2696 		 * (0-lag) time.
2697 		 */
2698 		err = 0;
2699 	}
2700 	raw_spin_unlock(&dl_b->lock);
2701 
2702 	return err;
2703 }
2704 
2705 /*
2706  * This function initializes the sched_dl_entity of a newly becoming
2707  * SCHED_DEADLINE task.
2708  *
2709  * Only the static values are considered here, the actual runtime and the
2710  * absolute deadline will be properly calculated when the task is enqueued
2711  * for the first time with its new policy.
2712  */
__setparam_dl(struct task_struct * p,const struct sched_attr * attr)2713 void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
2714 {
2715 	struct sched_dl_entity *dl_se = &p->dl;
2716 
2717 	dl_se->dl_runtime = attr->sched_runtime;
2718 	dl_se->dl_deadline = attr->sched_deadline;
2719 	dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
2720 	dl_se->flags = attr->sched_flags & SCHED_DL_FLAGS;
2721 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
2722 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
2723 }
2724 
__getparam_dl(struct task_struct * p,struct sched_attr * attr)2725 void __getparam_dl(struct task_struct *p, struct sched_attr *attr)
2726 {
2727 	struct sched_dl_entity *dl_se = &p->dl;
2728 
2729 	attr->sched_priority = p->rt_priority;
2730 	attr->sched_runtime = dl_se->dl_runtime;
2731 	attr->sched_deadline = dl_se->dl_deadline;
2732 	attr->sched_period = dl_se->dl_period;
2733 	attr->sched_flags &= ~SCHED_DL_FLAGS;
2734 	attr->sched_flags |= dl_se->flags;
2735 }
2736 
2737 /*
2738  * Default limits for DL period; on the top end we guard against small util
2739  * tasks still getting rediculous long effective runtimes, on the bottom end we
2740  * guard against timer DoS.
2741  */
2742 unsigned int sysctl_sched_dl_period_max = 1 << 22; /* ~4 seconds */
2743 unsigned int sysctl_sched_dl_period_min = 100;     /* 100 us */
2744 
2745 /*
2746  * This function validates the new parameters of a -deadline task.
2747  * We ask for the deadline not being zero, and greater or equal
2748  * than the runtime, as well as the period of being zero or
2749  * greater than deadline. Furthermore, we have to be sure that
2750  * user parameters are above the internal resolution of 1us (we
2751  * check sched_runtime only since it is always the smaller one) and
2752  * below 2^63 ns (we have to check both sched_deadline and
2753  * sched_period, as the latter can be zero).
2754  */
__checkparam_dl(const struct sched_attr * attr)2755 bool __checkparam_dl(const struct sched_attr *attr)
2756 {
2757 	u64 period, max, min;
2758 
2759 	/* special dl tasks don't actually use any parameter */
2760 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
2761 		return true;
2762 
2763 	/* deadline != 0 */
2764 	if (attr->sched_deadline == 0)
2765 		return false;
2766 
2767 	/*
2768 	 * Since we truncate DL_SCALE bits, make sure we're at least
2769 	 * that big.
2770 	 */
2771 	if (attr->sched_runtime < (1ULL << DL_SCALE))
2772 		return false;
2773 
2774 	/*
2775 	 * Since we use the MSB for wrap-around and sign issues, make
2776 	 * sure it's not set (mind that period can be equal to zero).
2777 	 */
2778 	if (attr->sched_deadline & (1ULL << 63) ||
2779 	    attr->sched_period & (1ULL << 63))
2780 		return false;
2781 
2782 	period = attr->sched_period;
2783 	if (!period)
2784 		period = attr->sched_deadline;
2785 
2786 	/* runtime <= deadline <= period (if period != 0) */
2787 	if (period < attr->sched_deadline ||
2788 	    attr->sched_deadline < attr->sched_runtime)
2789 		return false;
2790 
2791 	max = (u64)READ_ONCE(sysctl_sched_dl_period_max) * NSEC_PER_USEC;
2792 	min = (u64)READ_ONCE(sysctl_sched_dl_period_min) * NSEC_PER_USEC;
2793 
2794 	if (period < min || period > max)
2795 		return false;
2796 
2797 	return true;
2798 }
2799 
2800 /*
2801  * This function clears the sched_dl_entity static params.
2802  */
__dl_clear_params(struct task_struct * p)2803 void __dl_clear_params(struct task_struct *p)
2804 {
2805 	struct sched_dl_entity *dl_se = &p->dl;
2806 
2807 	dl_se->dl_runtime		= 0;
2808 	dl_se->dl_deadline		= 0;
2809 	dl_se->dl_period		= 0;
2810 	dl_se->flags			= 0;
2811 	dl_se->dl_bw			= 0;
2812 	dl_se->dl_density		= 0;
2813 
2814 	dl_se->dl_throttled		= 0;
2815 	dl_se->dl_yielded		= 0;
2816 	dl_se->dl_non_contending	= 0;
2817 	dl_se->dl_overrun		= 0;
2818 
2819 #ifdef CONFIG_RT_MUTEXES
2820 	dl_se->pi_se			= dl_se;
2821 #endif
2822 }
2823 
dl_param_changed(struct task_struct * p,const struct sched_attr * attr)2824 bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
2825 {
2826 	struct sched_dl_entity *dl_se = &p->dl;
2827 
2828 	if (dl_se->dl_runtime != attr->sched_runtime ||
2829 	    dl_se->dl_deadline != attr->sched_deadline ||
2830 	    dl_se->dl_period != attr->sched_period ||
2831 	    dl_se->flags != (attr->sched_flags & SCHED_DL_FLAGS))
2832 		return true;
2833 
2834 	return false;
2835 }
2836 
2837 #ifdef CONFIG_SMP
dl_cpuset_cpumask_can_shrink(const struct cpumask * cur,const struct cpumask * trial)2838 int dl_cpuset_cpumask_can_shrink(const struct cpumask *cur,
2839 				 const struct cpumask *trial)
2840 {
2841 	int ret = 1, trial_cpus;
2842 	struct dl_bw *cur_dl_b;
2843 	unsigned long flags;
2844 
2845 	rcu_read_lock_sched();
2846 	cur_dl_b = dl_bw_of(cpumask_any(cur));
2847 	trial_cpus = cpumask_weight(trial);
2848 
2849 	raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
2850 	if (cur_dl_b->bw != -1 &&
2851 	    cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
2852 		ret = 0;
2853 	raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
2854 	rcu_read_unlock_sched();
2855 
2856 	return ret;
2857 }
2858 
dl_cpu_busy(int cpu,struct task_struct * p)2859 int dl_cpu_busy(int cpu, struct task_struct *p)
2860 {
2861 	unsigned long flags, cap;
2862 	struct dl_bw *dl_b;
2863 	bool overflow;
2864 
2865 	rcu_read_lock_sched();
2866 	dl_b = dl_bw_of(cpu);
2867 	raw_spin_lock_irqsave(&dl_b->lock, flags);
2868 	cap = dl_bw_capacity(cpu);
2869 	overflow = __dl_overflow(dl_b, cap, 0, p ? p->dl.dl_bw : 0);
2870 
2871 	if (!overflow && p) {
2872 		/*
2873 		 * We reserve space for this task in the destination
2874 		 * root_domain, as we can't fail after this point.
2875 		 * We will free resources in the source root_domain
2876 		 * later on (see set_cpus_allowed_dl()).
2877 		 */
2878 		__dl_add(dl_b, p->dl.dl_bw, dl_bw_cpus(cpu));
2879 	}
2880 
2881 	raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2882 	rcu_read_unlock_sched();
2883 
2884 	return overflow ? -EBUSY : 0;
2885 }
2886 #endif
2887 
2888 #ifdef CONFIG_SCHED_DEBUG
print_dl_stats(struct seq_file * m,int cpu)2889 void print_dl_stats(struct seq_file *m, int cpu)
2890 {
2891 	print_dl_rq(m, cpu, &cpu_rq(cpu)->dl);
2892 }
2893 #endif /* CONFIG_SCHED_DEBUG */
2894