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