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