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