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