xref: /openbmc/linux/kernel/sched/deadline.c (revision b24413180f5600bcb3bb70fbed5cf186b60864bd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Deadline Scheduling Class (SCHED_DEADLINE)
4  *
5  * Earliest Deadline First (EDF) + Constant Bandwidth Server (CBS).
6  *
7  * Tasks that periodically executes their instances for less than their
8  * runtime won't miss any of their deadlines.
9  * Tasks that are not periodic or sporadic or that tries to execute more
10  * than their reserved bandwidth will be slowed down (and may potentially
11  * miss some of their deadlines), and won't affect any other task.
12  *
13  * Copyright (C) 2012 Dario Faggioli <raistlin@linux.it>,
14  *                    Juri Lelli <juri.lelli@gmail.com>,
15  *                    Michael Trimarchi <michael@amarulasolutions.com>,
16  *                    Fabio Checconi <fchecconi@gmail.com>
17  */
18 #include "sched.h"
19 
20 #include <linux/slab.h>
21 #include <uapi/linux/sched/types.h>
22 
23 struct dl_bandwidth def_dl_bandwidth;
24 
25 static inline struct task_struct *dl_task_of(struct sched_dl_entity *dl_se)
26 {
27 	return container_of(dl_se, struct task_struct, dl);
28 }
29 
30 static inline struct rq *rq_of_dl_rq(struct dl_rq *dl_rq)
31 {
32 	return container_of(dl_rq, struct rq, dl);
33 }
34 
35 static inline struct dl_rq *dl_rq_of_se(struct sched_dl_entity *dl_se)
36 {
37 	struct task_struct *p = dl_task_of(dl_se);
38 	struct rq *rq = task_rq(p);
39 
40 	return &rq->dl;
41 }
42 
43 static inline int on_dl_rq(struct sched_dl_entity *dl_se)
44 {
45 	return !RB_EMPTY_NODE(&dl_se->rb_node);
46 }
47 
48 #ifdef CONFIG_SMP
49 static inline struct dl_bw *dl_bw_of(int i)
50 {
51 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
52 			 "sched RCU must be held");
53 	return &cpu_rq(i)->rd->dl_bw;
54 }
55 
56 static inline int dl_bw_cpus(int i)
57 {
58 	struct root_domain *rd = cpu_rq(i)->rd;
59 	int cpus = 0;
60 
61 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
62 			 "sched RCU must be held");
63 	for_each_cpu_and(i, rd->span, cpu_active_mask)
64 		cpus++;
65 
66 	return cpus;
67 }
68 #else
69 static inline struct dl_bw *dl_bw_of(int i)
70 {
71 	return &cpu_rq(i)->dl.dl_bw;
72 }
73 
74 static inline int dl_bw_cpus(int i)
75 {
76 	return 1;
77 }
78 #endif
79 
80 static inline
81 void add_running_bw(u64 dl_bw, struct dl_rq *dl_rq)
82 {
83 	u64 old = dl_rq->running_bw;
84 
85 	lockdep_assert_held(&(rq_of_dl_rq(dl_rq))->lock);
86 	dl_rq->running_bw += dl_bw;
87 	SCHED_WARN_ON(dl_rq->running_bw < old); /* overflow */
88 	SCHED_WARN_ON(dl_rq->running_bw > dl_rq->this_bw);
89 }
90 
91 static inline
92 void sub_running_bw(u64 dl_bw, struct dl_rq *dl_rq)
93 {
94 	u64 old = dl_rq->running_bw;
95 
96 	lockdep_assert_held(&(rq_of_dl_rq(dl_rq))->lock);
97 	dl_rq->running_bw -= dl_bw;
98 	SCHED_WARN_ON(dl_rq->running_bw > old); /* underflow */
99 	if (dl_rq->running_bw > old)
100 		dl_rq->running_bw = 0;
101 }
102 
103 static inline
104 void add_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)
105 {
106 	u64 old = dl_rq->this_bw;
107 
108 	lockdep_assert_held(&(rq_of_dl_rq(dl_rq))->lock);
109 	dl_rq->this_bw += dl_bw;
110 	SCHED_WARN_ON(dl_rq->this_bw < old); /* overflow */
111 }
112 
113 static inline
114 void sub_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)
115 {
116 	u64 old = dl_rq->this_bw;
117 
118 	lockdep_assert_held(&(rq_of_dl_rq(dl_rq))->lock);
119 	dl_rq->this_bw -= dl_bw;
120 	SCHED_WARN_ON(dl_rq->this_bw > old); /* underflow */
121 	if (dl_rq->this_bw > old)
122 		dl_rq->this_bw = 0;
123 	SCHED_WARN_ON(dl_rq->running_bw > dl_rq->this_bw);
124 }
125 
126 void dl_change_utilization(struct task_struct *p, u64 new_bw)
127 {
128 	struct rq *rq;
129 
130 	if (task_on_rq_queued(p))
131 		return;
132 
133 	rq = task_rq(p);
134 	if (p->dl.dl_non_contending) {
135 		sub_running_bw(p->dl.dl_bw, &rq->dl);
136 		p->dl.dl_non_contending = 0;
137 		/*
138 		 * If the timer handler is currently running and the
139 		 * timer cannot be cancelled, inactive_task_timer()
140 		 * will see that dl_not_contending is not set, and
141 		 * will not touch the rq's active utilization,
142 		 * so we are still safe.
143 		 */
144 		if (hrtimer_try_to_cancel(&p->dl.inactive_timer) == 1)
145 			put_task_struct(p);
146 	}
147 	sub_rq_bw(p->dl.dl_bw, &rq->dl);
148 	add_rq_bw(new_bw, &rq->dl);
149 }
150 
151 /*
152  * The utilization of a task cannot be immediately removed from
153  * the rq active utilization (running_bw) when the task blocks.
154  * Instead, we have to wait for the so called "0-lag time".
155  *
156  * If a task blocks before the "0-lag time", a timer (the inactive
157  * timer) is armed, and running_bw is decreased when the timer
158  * fires.
159  *
160  * If the task wakes up again before the inactive timer fires,
161  * the timer is cancelled, whereas if the task wakes up after the
162  * inactive timer fired (and running_bw has been decreased) the
163  * task's utilization has to be added to running_bw again.
164  * A flag in the deadline scheduling entity (dl_non_contending)
165  * is used to avoid race conditions between the inactive timer handler
166  * and task wakeups.
167  *
168  * The following diagram shows how running_bw is updated. A task is
169  * "ACTIVE" when its utilization contributes to running_bw; an
170  * "ACTIVE contending" task is in the TASK_RUNNING state, while an
171  * "ACTIVE non contending" task is a blocked task for which the "0-lag time"
172  * has not passed yet. An "INACTIVE" task is a task for which the "0-lag"
173  * time already passed, which does not contribute to running_bw anymore.
174  *                              +------------------+
175  *             wakeup           |    ACTIVE        |
176  *          +------------------>+   contending     |
177  *          | add_running_bw    |                  |
178  *          |                   +----+------+------+
179  *          |                        |      ^
180  *          |                dequeue |      |
181  * +--------+-------+                |      |
182  * |                |   t >= 0-lag   |      | wakeup
183  * |    INACTIVE    |<---------------+      |
184  * |                | sub_running_bw |      |
185  * +--------+-------+                |      |
186  *          ^                        |      |
187  *          |              t < 0-lag |      |
188  *          |                        |      |
189  *          |                        V      |
190  *          |                   +----+------+------+
191  *          | sub_running_bw    |    ACTIVE        |
192  *          +-------------------+                  |
193  *            inactive timer    |  non contending  |
194  *            fired             +------------------+
195  *
196  * The task_non_contending() function is invoked when a task
197  * blocks, and checks if the 0-lag time already passed or
198  * not (in the first case, it directly updates running_bw;
199  * in the second case, it arms the inactive timer).
200  *
201  * The task_contending() function is invoked when a task wakes
202  * up, and checks if the task is still in the "ACTIVE non contending"
203  * state or not (in the second case, it updates running_bw).
204  */
205 static void task_non_contending(struct task_struct *p)
206 {
207 	struct sched_dl_entity *dl_se = &p->dl;
208 	struct hrtimer *timer = &dl_se->inactive_timer;
209 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
210 	struct rq *rq = rq_of_dl_rq(dl_rq);
211 	s64 zerolag_time;
212 
213 	/*
214 	 * If this is a non-deadline task that has been boosted,
215 	 * do nothing
216 	 */
217 	if (dl_se->dl_runtime == 0)
218 		return;
219 
220 	WARN_ON(hrtimer_active(&dl_se->inactive_timer));
221 	WARN_ON(dl_se->dl_non_contending);
222 
223 	zerolag_time = dl_se->deadline -
224 		 div64_long((dl_se->runtime * dl_se->dl_period),
225 			dl_se->dl_runtime);
226 
227 	/*
228 	 * Using relative times instead of the absolute "0-lag time"
229 	 * allows to simplify the code
230 	 */
231 	zerolag_time -= rq_clock(rq);
232 
233 	/*
234 	 * If the "0-lag time" already passed, decrease the active
235 	 * utilization now, instead of starting a timer
236 	 */
237 	if (zerolag_time < 0) {
238 		if (dl_task(p))
239 			sub_running_bw(dl_se->dl_bw, dl_rq);
240 		if (!dl_task(p) || p->state == TASK_DEAD) {
241 			struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
242 
243 			if (p->state == TASK_DEAD)
244 				sub_rq_bw(p->dl.dl_bw, &rq->dl);
245 			raw_spin_lock(&dl_b->lock);
246 			__dl_clear(dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
247 			__dl_clear_params(p);
248 			raw_spin_unlock(&dl_b->lock);
249 		}
250 
251 		return;
252 	}
253 
254 	dl_se->dl_non_contending = 1;
255 	get_task_struct(p);
256 	hrtimer_start(timer, ns_to_ktime(zerolag_time), HRTIMER_MODE_REL);
257 }
258 
259 static void task_contending(struct sched_dl_entity *dl_se, int flags)
260 {
261 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
262 
263 	/*
264 	 * If this is a non-deadline task that has been boosted,
265 	 * do nothing
266 	 */
267 	if (dl_se->dl_runtime == 0)
268 		return;
269 
270 	if (flags & ENQUEUE_MIGRATED)
271 		add_rq_bw(dl_se->dl_bw, dl_rq);
272 
273 	if (dl_se->dl_non_contending) {
274 		dl_se->dl_non_contending = 0;
275 		/*
276 		 * If the timer handler is currently running and the
277 		 * timer cannot be cancelled, inactive_task_timer()
278 		 * will see that dl_not_contending is not set, and
279 		 * will not touch the rq's active utilization,
280 		 * so we are still safe.
281 		 */
282 		if (hrtimer_try_to_cancel(&dl_se->inactive_timer) == 1)
283 			put_task_struct(dl_task_of(dl_se));
284 	} else {
285 		/*
286 		 * Since "dl_non_contending" is not set, the
287 		 * task's utilization has already been removed from
288 		 * active utilization (either when the task blocked,
289 		 * when the "inactive timer" fired).
290 		 * So, add it back.
291 		 */
292 		add_running_bw(dl_se->dl_bw, dl_rq);
293 	}
294 }
295 
296 static inline int is_leftmost(struct task_struct *p, struct dl_rq *dl_rq)
297 {
298 	struct sched_dl_entity *dl_se = &p->dl;
299 
300 	return dl_rq->root.rb_leftmost == &dl_se->rb_node;
301 }
302 
303 void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime)
304 {
305 	raw_spin_lock_init(&dl_b->dl_runtime_lock);
306 	dl_b->dl_period = period;
307 	dl_b->dl_runtime = runtime;
308 }
309 
310 void init_dl_bw(struct dl_bw *dl_b)
311 {
312 	raw_spin_lock_init(&dl_b->lock);
313 	raw_spin_lock(&def_dl_bandwidth.dl_runtime_lock);
314 	if (global_rt_runtime() == RUNTIME_INF)
315 		dl_b->bw = -1;
316 	else
317 		dl_b->bw = to_ratio(global_rt_period(), global_rt_runtime());
318 	raw_spin_unlock(&def_dl_bandwidth.dl_runtime_lock);
319 	dl_b->total_bw = 0;
320 }
321 
322 void init_dl_rq(struct dl_rq *dl_rq)
323 {
324 	dl_rq->root = RB_ROOT_CACHED;
325 
326 #ifdef CONFIG_SMP
327 	/* zero means no -deadline tasks */
328 	dl_rq->earliest_dl.curr = dl_rq->earliest_dl.next = 0;
329 
330 	dl_rq->dl_nr_migratory = 0;
331 	dl_rq->overloaded = 0;
332 	dl_rq->pushable_dl_tasks_root = RB_ROOT_CACHED;
333 #else
334 	init_dl_bw(&dl_rq->dl_bw);
335 #endif
336 
337 	dl_rq->running_bw = 0;
338 	dl_rq->this_bw = 0;
339 	init_dl_rq_bw_ratio(dl_rq);
340 }
341 
342 #ifdef CONFIG_SMP
343 
344 static inline int dl_overloaded(struct rq *rq)
345 {
346 	return atomic_read(&rq->rd->dlo_count);
347 }
348 
349 static inline void dl_set_overload(struct rq *rq)
350 {
351 	if (!rq->online)
352 		return;
353 
354 	cpumask_set_cpu(rq->cpu, rq->rd->dlo_mask);
355 	/*
356 	 * Must be visible before the overload count is
357 	 * set (as in sched_rt.c).
358 	 *
359 	 * Matched by the barrier in pull_dl_task().
360 	 */
361 	smp_wmb();
362 	atomic_inc(&rq->rd->dlo_count);
363 }
364 
365 static inline void dl_clear_overload(struct rq *rq)
366 {
367 	if (!rq->online)
368 		return;
369 
370 	atomic_dec(&rq->rd->dlo_count);
371 	cpumask_clear_cpu(rq->cpu, rq->rd->dlo_mask);
372 }
373 
374 static void update_dl_migration(struct dl_rq *dl_rq)
375 {
376 	if (dl_rq->dl_nr_migratory && dl_rq->dl_nr_running > 1) {
377 		if (!dl_rq->overloaded) {
378 			dl_set_overload(rq_of_dl_rq(dl_rq));
379 			dl_rq->overloaded = 1;
380 		}
381 	} else if (dl_rq->overloaded) {
382 		dl_clear_overload(rq_of_dl_rq(dl_rq));
383 		dl_rq->overloaded = 0;
384 	}
385 }
386 
387 static void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
388 {
389 	struct task_struct *p = dl_task_of(dl_se);
390 
391 	if (p->nr_cpus_allowed > 1)
392 		dl_rq->dl_nr_migratory++;
393 
394 	update_dl_migration(dl_rq);
395 }
396 
397 static void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
398 {
399 	struct task_struct *p = dl_task_of(dl_se);
400 
401 	if (p->nr_cpus_allowed > 1)
402 		dl_rq->dl_nr_migratory--;
403 
404 	update_dl_migration(dl_rq);
405 }
406 
407 /*
408  * The list of pushable -deadline task is not a plist, like in
409  * sched_rt.c, it is an rb-tree with tasks ordered by deadline.
410  */
411 static void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
412 {
413 	struct dl_rq *dl_rq = &rq->dl;
414 	struct rb_node **link = &dl_rq->pushable_dl_tasks_root.rb_root.rb_node;
415 	struct rb_node *parent = NULL;
416 	struct task_struct *entry;
417 	bool leftmost = true;
418 
419 	BUG_ON(!RB_EMPTY_NODE(&p->pushable_dl_tasks));
420 
421 	while (*link) {
422 		parent = *link;
423 		entry = rb_entry(parent, struct task_struct,
424 				 pushable_dl_tasks);
425 		if (dl_entity_preempt(&p->dl, &entry->dl))
426 			link = &parent->rb_left;
427 		else {
428 			link = &parent->rb_right;
429 			leftmost = false;
430 		}
431 	}
432 
433 	if (leftmost)
434 		dl_rq->earliest_dl.next = p->dl.deadline;
435 
436 	rb_link_node(&p->pushable_dl_tasks, parent, link);
437 	rb_insert_color_cached(&p->pushable_dl_tasks,
438 			       &dl_rq->pushable_dl_tasks_root, leftmost);
439 }
440 
441 static void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
442 {
443 	struct dl_rq *dl_rq = &rq->dl;
444 
445 	if (RB_EMPTY_NODE(&p->pushable_dl_tasks))
446 		return;
447 
448 	if (dl_rq->pushable_dl_tasks_root.rb_leftmost == &p->pushable_dl_tasks) {
449 		struct rb_node *next_node;
450 
451 		next_node = rb_next(&p->pushable_dl_tasks);
452 		if (next_node) {
453 			dl_rq->earliest_dl.next = rb_entry(next_node,
454 				struct task_struct, pushable_dl_tasks)->dl.deadline;
455 		}
456 	}
457 
458 	rb_erase_cached(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root);
459 	RB_CLEAR_NODE(&p->pushable_dl_tasks);
460 }
461 
462 static inline int has_pushable_dl_tasks(struct rq *rq)
463 {
464 	return !RB_EMPTY_ROOT(&rq->dl.pushable_dl_tasks_root.rb_root);
465 }
466 
467 static int push_dl_task(struct rq *rq);
468 
469 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
470 {
471 	return dl_task(prev);
472 }
473 
474 static DEFINE_PER_CPU(struct callback_head, dl_push_head);
475 static DEFINE_PER_CPU(struct callback_head, dl_pull_head);
476 
477 static void push_dl_tasks(struct rq *);
478 static void pull_dl_task(struct rq *);
479 
480 static inline void queue_push_tasks(struct rq *rq)
481 {
482 	if (!has_pushable_dl_tasks(rq))
483 		return;
484 
485 	queue_balance_callback(rq, &per_cpu(dl_push_head, rq->cpu), push_dl_tasks);
486 }
487 
488 static inline void queue_pull_task(struct rq *rq)
489 {
490 	queue_balance_callback(rq, &per_cpu(dl_pull_head, rq->cpu), pull_dl_task);
491 }
492 
493 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq);
494 
495 static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p)
496 {
497 	struct rq *later_rq = NULL;
498 
499 	later_rq = find_lock_later_rq(p, rq);
500 	if (!later_rq) {
501 		int cpu;
502 
503 		/*
504 		 * If we cannot preempt any rq, fall back to pick any
505 		 * online cpu.
506 		 */
507 		cpu = cpumask_any_and(cpu_active_mask, &p->cpus_allowed);
508 		if (cpu >= nr_cpu_ids) {
509 			/*
510 			 * Fail to find any suitable cpu.
511 			 * The task will never come back!
512 			 */
513 			BUG_ON(dl_bandwidth_enabled());
514 
515 			/*
516 			 * If admission control is disabled we
517 			 * try a little harder to let the task
518 			 * run.
519 			 */
520 			cpu = cpumask_any(cpu_active_mask);
521 		}
522 		later_rq = cpu_rq(cpu);
523 		double_lock_balance(rq, later_rq);
524 	}
525 
526 	set_task_cpu(p, later_rq->cpu);
527 	double_unlock_balance(later_rq, rq);
528 
529 	return later_rq;
530 }
531 
532 #else
533 
534 static inline
535 void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
536 {
537 }
538 
539 static inline
540 void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
541 {
542 }
543 
544 static inline
545 void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
546 {
547 }
548 
549 static inline
550 void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
551 {
552 }
553 
554 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
555 {
556 	return false;
557 }
558 
559 static inline void pull_dl_task(struct rq *rq)
560 {
561 }
562 
563 static inline void queue_push_tasks(struct rq *rq)
564 {
565 }
566 
567 static inline void queue_pull_task(struct rq *rq)
568 {
569 }
570 #endif /* CONFIG_SMP */
571 
572 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags);
573 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags);
574 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
575 				  int flags);
576 
577 /*
578  * We are being explicitly informed that a new instance is starting,
579  * and this means that:
580  *  - the absolute deadline of the entity has to be placed at
581  *    current time + relative deadline;
582  *  - the runtime of the entity has to be set to the maximum value.
583  *
584  * The capability of specifying such event is useful whenever a -deadline
585  * entity wants to (try to!) synchronize its behaviour with the scheduler's
586  * one, and to (try to!) reconcile itself with its own scheduling
587  * parameters.
588  */
589 static inline void setup_new_dl_entity(struct sched_dl_entity *dl_se)
590 {
591 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
592 	struct rq *rq = rq_of_dl_rq(dl_rq);
593 
594 	WARN_ON(dl_se->dl_boosted);
595 	WARN_ON(dl_time_before(rq_clock(rq), dl_se->deadline));
596 
597 	/*
598 	 * We are racing with the deadline timer. So, do nothing because
599 	 * the deadline timer handler will take care of properly recharging
600 	 * the runtime and postponing the deadline
601 	 */
602 	if (dl_se->dl_throttled)
603 		return;
604 
605 	/*
606 	 * We use the regular wall clock time to set deadlines in the
607 	 * future; in fact, we must consider execution overheads (time
608 	 * spent on hardirq context, etc.).
609 	 */
610 	dl_se->deadline = rq_clock(rq) + dl_se->dl_deadline;
611 	dl_se->runtime = dl_se->dl_runtime;
612 }
613 
614 /*
615  * Pure Earliest Deadline First (EDF) scheduling does not deal with the
616  * possibility of a entity lasting more than what it declared, and thus
617  * exhausting its runtime.
618  *
619  * Here we are interested in making runtime overrun possible, but we do
620  * not want a entity which is misbehaving to affect the scheduling of all
621  * other entities.
622  * Therefore, a budgeting strategy called Constant Bandwidth Server (CBS)
623  * is used, in order to confine each entity within its own bandwidth.
624  *
625  * This function deals exactly with that, and ensures that when the runtime
626  * of a entity is replenished, its deadline is also postponed. That ensures
627  * the overrunning entity can't interfere with other entity in the system and
628  * can't make them miss their deadlines. Reasons why this kind of overruns
629  * could happen are, typically, a entity voluntarily trying to overcome its
630  * runtime, or it just underestimated it during sched_setattr().
631  */
632 static void replenish_dl_entity(struct sched_dl_entity *dl_se,
633 				struct sched_dl_entity *pi_se)
634 {
635 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
636 	struct rq *rq = rq_of_dl_rq(dl_rq);
637 
638 	BUG_ON(pi_se->dl_runtime <= 0);
639 
640 	/*
641 	 * This could be the case for a !-dl task that is boosted.
642 	 * Just go with full inherited parameters.
643 	 */
644 	if (dl_se->dl_deadline == 0) {
645 		dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
646 		dl_se->runtime = pi_se->dl_runtime;
647 	}
648 
649 	if (dl_se->dl_yielded && dl_se->runtime > 0)
650 		dl_se->runtime = 0;
651 
652 	/*
653 	 * We keep moving the deadline away until we get some
654 	 * available runtime for the entity. This ensures correct
655 	 * handling of situations where the runtime overrun is
656 	 * arbitrary large.
657 	 */
658 	while (dl_se->runtime <= 0) {
659 		dl_se->deadline += pi_se->dl_period;
660 		dl_se->runtime += pi_se->dl_runtime;
661 	}
662 
663 	/*
664 	 * At this point, the deadline really should be "in
665 	 * the future" with respect to rq->clock. If it's
666 	 * not, we are, for some reason, lagging too much!
667 	 * Anyway, after having warn userspace abut that,
668 	 * we still try to keep the things running by
669 	 * resetting the deadline and the budget of the
670 	 * entity.
671 	 */
672 	if (dl_time_before(dl_se->deadline, rq_clock(rq))) {
673 		printk_deferred_once("sched: DL replenish lagged too much\n");
674 		dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
675 		dl_se->runtime = pi_se->dl_runtime;
676 	}
677 
678 	if (dl_se->dl_yielded)
679 		dl_se->dl_yielded = 0;
680 	if (dl_se->dl_throttled)
681 		dl_se->dl_throttled = 0;
682 }
683 
684 /*
685  * Here we check if --at time t-- an entity (which is probably being
686  * [re]activated or, in general, enqueued) can use its remaining runtime
687  * and its current deadline _without_ exceeding the bandwidth it is
688  * assigned (function returns true if it can't). We are in fact applying
689  * one of the CBS rules: when a task wakes up, if the residual runtime
690  * over residual deadline fits within the allocated bandwidth, then we
691  * can keep the current (absolute) deadline and residual budget without
692  * disrupting the schedulability of the system. Otherwise, we should
693  * refill the runtime and set the deadline a period in the future,
694  * because keeping the current (absolute) deadline of the task would
695  * result in breaking guarantees promised to other tasks (refer to
696  * Documentation/scheduler/sched-deadline.txt for more informations).
697  *
698  * This function returns true if:
699  *
700  *   runtime / (deadline - t) > dl_runtime / dl_deadline ,
701  *
702  * IOW we can't recycle current parameters.
703  *
704  * Notice that the bandwidth check is done against the deadline. For
705  * task with deadline equal to period this is the same of using
706  * dl_period instead of dl_deadline in the equation above.
707  */
708 static bool dl_entity_overflow(struct sched_dl_entity *dl_se,
709 			       struct sched_dl_entity *pi_se, u64 t)
710 {
711 	u64 left, right;
712 
713 	/*
714 	 * left and right are the two sides of the equation above,
715 	 * after a bit of shuffling to use multiplications instead
716 	 * of divisions.
717 	 *
718 	 * Note that none of the time values involved in the two
719 	 * multiplications are absolute: dl_deadline and dl_runtime
720 	 * are the relative deadline and the maximum runtime of each
721 	 * instance, runtime is the runtime left for the last instance
722 	 * and (deadline - t), since t is rq->clock, is the time left
723 	 * to the (absolute) deadline. Even if overflowing the u64 type
724 	 * is very unlikely to occur in both cases, here we scale down
725 	 * as we want to avoid that risk at all. Scaling down by 10
726 	 * means that we reduce granularity to 1us. We are fine with it,
727 	 * since this is only a true/false check and, anyway, thinking
728 	 * of anything below microseconds resolution is actually fiction
729 	 * (but still we want to give the user that illusion >;).
730 	 */
731 	left = (pi_se->dl_deadline >> DL_SCALE) * (dl_se->runtime >> DL_SCALE);
732 	right = ((dl_se->deadline - t) >> DL_SCALE) *
733 		(pi_se->dl_runtime >> DL_SCALE);
734 
735 	return dl_time_before(right, left);
736 }
737 
738 /*
739  * Revised wakeup rule [1]: For self-suspending tasks, rather then
740  * re-initializing task's runtime and deadline, the revised wakeup
741  * rule adjusts the task's runtime to avoid the task to overrun its
742  * density.
743  *
744  * Reasoning: a task may overrun the density if:
745  *    runtime / (deadline - t) > dl_runtime / dl_deadline
746  *
747  * Therefore, runtime can be adjusted to:
748  *     runtime = (dl_runtime / dl_deadline) * (deadline - t)
749  *
750  * In such way that runtime will be equal to the maximum density
751  * the task can use without breaking any rule.
752  *
753  * [1] Luca Abeni, Giuseppe Lipari, and Juri Lelli. 2015. Constant
754  * bandwidth server revisited. SIGBED Rev. 11, 4 (January 2015), 19-24.
755  */
756 static void
757 update_dl_revised_wakeup(struct sched_dl_entity *dl_se, struct rq *rq)
758 {
759 	u64 laxity = dl_se->deadline - rq_clock(rq);
760 
761 	/*
762 	 * If the task has deadline < period, and the deadline is in the past,
763 	 * it should already be throttled before this check.
764 	 *
765 	 * See update_dl_entity() comments for further details.
766 	 */
767 	WARN_ON(dl_time_before(dl_se->deadline, rq_clock(rq)));
768 
769 	dl_se->runtime = (dl_se->dl_density * laxity) >> BW_SHIFT;
770 }
771 
772 /*
773  * Regarding the deadline, a task with implicit deadline has a relative
774  * deadline == relative period. A task with constrained deadline has a
775  * relative deadline <= relative period.
776  *
777  * We support constrained deadline tasks. However, there are some restrictions
778  * applied only for tasks which do not have an implicit deadline. See
779  * update_dl_entity() to know more about such restrictions.
780  *
781  * The dl_is_implicit() returns true if the task has an implicit deadline.
782  */
783 static inline bool dl_is_implicit(struct sched_dl_entity *dl_se)
784 {
785 	return dl_se->dl_deadline == dl_se->dl_period;
786 }
787 
788 /*
789  * When a deadline entity is placed in the runqueue, its runtime and deadline
790  * might need to be updated. This is done by a CBS wake up rule. There are two
791  * different rules: 1) the original CBS; and 2) the Revisited CBS.
792  *
793  * When the task is starting a new period, the Original CBS is used. In this
794  * case, the runtime is replenished and a new absolute deadline is set.
795  *
796  * When a task is queued before the begin of the next period, using the
797  * remaining runtime and deadline could make the entity to overflow, see
798  * dl_entity_overflow() to find more about runtime overflow. When such case
799  * is detected, the runtime and deadline need to be updated.
800  *
801  * If the task has an implicit deadline, i.e., deadline == period, the Original
802  * CBS is applied. the runtime is replenished and a new absolute deadline is
803  * set, as in the previous cases.
804  *
805  * However, the Original CBS does not work properly for tasks with
806  * deadline < period, which are said to have a constrained deadline. By
807  * applying the Original CBS, a constrained deadline task would be able to run
808  * runtime/deadline in a period. With deadline < period, the task would
809  * overrun the runtime/period allowed bandwidth, breaking the admission test.
810  *
811  * In order to prevent this misbehave, the Revisited CBS is used for
812  * constrained deadline tasks when a runtime overflow is detected. In the
813  * Revisited CBS, rather than replenishing & setting a new absolute deadline,
814  * the remaining runtime of the task is reduced to avoid runtime overflow.
815  * Please refer to the comments update_dl_revised_wakeup() function to find
816  * more about the Revised CBS rule.
817  */
818 static void update_dl_entity(struct sched_dl_entity *dl_se,
819 			     struct sched_dl_entity *pi_se)
820 {
821 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
822 	struct rq *rq = rq_of_dl_rq(dl_rq);
823 
824 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
825 	    dl_entity_overflow(dl_se, pi_se, rq_clock(rq))) {
826 
827 		if (unlikely(!dl_is_implicit(dl_se) &&
828 			     !dl_time_before(dl_se->deadline, rq_clock(rq)) &&
829 			     !dl_se->dl_boosted)){
830 			update_dl_revised_wakeup(dl_se, rq);
831 			return;
832 		}
833 
834 		dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
835 		dl_se->runtime = pi_se->dl_runtime;
836 	}
837 }
838 
839 static inline u64 dl_next_period(struct sched_dl_entity *dl_se)
840 {
841 	return dl_se->deadline - dl_se->dl_deadline + dl_se->dl_period;
842 }
843 
844 /*
845  * If the entity depleted all its runtime, and if we want it to sleep
846  * while waiting for some new execution time to become available, we
847  * set the bandwidth replenishment timer to the replenishment instant
848  * and try to activate it.
849  *
850  * Notice that it is important for the caller to know if the timer
851  * actually started or not (i.e., the replenishment instant is in
852  * the future or in the past).
853  */
854 static int start_dl_timer(struct task_struct *p)
855 {
856 	struct sched_dl_entity *dl_se = &p->dl;
857 	struct hrtimer *timer = &dl_se->dl_timer;
858 	struct rq *rq = task_rq(p);
859 	ktime_t now, act;
860 	s64 delta;
861 
862 	lockdep_assert_held(&rq->lock);
863 
864 	/*
865 	 * We want the timer to fire at the deadline, but considering
866 	 * that it is actually coming from rq->clock and not from
867 	 * hrtimer's time base reading.
868 	 */
869 	act = ns_to_ktime(dl_next_period(dl_se));
870 	now = hrtimer_cb_get_time(timer);
871 	delta = ktime_to_ns(now) - rq_clock(rq);
872 	act = ktime_add_ns(act, delta);
873 
874 	/*
875 	 * If the expiry time already passed, e.g., because the value
876 	 * chosen as the deadline is too small, don't even try to
877 	 * start the timer in the past!
878 	 */
879 	if (ktime_us_delta(act, now) < 0)
880 		return 0;
881 
882 	/*
883 	 * !enqueued will guarantee another callback; even if one is already in
884 	 * progress. This ensures a balanced {get,put}_task_struct().
885 	 *
886 	 * The race against __run_timer() clearing the enqueued state is
887 	 * harmless because we're holding task_rq()->lock, therefore the timer
888 	 * expiring after we've done the check will wait on its task_rq_lock()
889 	 * and observe our state.
890 	 */
891 	if (!hrtimer_is_queued(timer)) {
892 		get_task_struct(p);
893 		hrtimer_start(timer, act, HRTIMER_MODE_ABS);
894 	}
895 
896 	return 1;
897 }
898 
899 /*
900  * This is the bandwidth enforcement timer callback. If here, we know
901  * a task is not on its dl_rq, since the fact that the timer was running
902  * means the task is throttled and needs a runtime replenishment.
903  *
904  * However, what we actually do depends on the fact the task is active,
905  * (it is on its rq) or has been removed from there by a call to
906  * dequeue_task_dl(). In the former case we must issue the runtime
907  * replenishment and add the task back to the dl_rq; in the latter, we just
908  * do nothing but clearing dl_throttled, so that runtime and deadline
909  * updating (and the queueing back to dl_rq) will be done by the
910  * next call to enqueue_task_dl().
911  */
912 static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
913 {
914 	struct sched_dl_entity *dl_se = container_of(timer,
915 						     struct sched_dl_entity,
916 						     dl_timer);
917 	struct task_struct *p = dl_task_of(dl_se);
918 	struct rq_flags rf;
919 	struct rq *rq;
920 
921 	rq = task_rq_lock(p, &rf);
922 
923 	/*
924 	 * The task might have changed its scheduling policy to something
925 	 * different than SCHED_DEADLINE (through switched_from_dl()).
926 	 */
927 	if (!dl_task(p))
928 		goto unlock;
929 
930 	/*
931 	 * The task might have been boosted by someone else and might be in the
932 	 * boosting/deboosting path, its not throttled.
933 	 */
934 	if (dl_se->dl_boosted)
935 		goto unlock;
936 
937 	/*
938 	 * Spurious timer due to start_dl_timer() race; or we already received
939 	 * a replenishment from rt_mutex_setprio().
940 	 */
941 	if (!dl_se->dl_throttled)
942 		goto unlock;
943 
944 	sched_clock_tick();
945 	update_rq_clock(rq);
946 
947 	/*
948 	 * If the throttle happened during sched-out; like:
949 	 *
950 	 *   schedule()
951 	 *     deactivate_task()
952 	 *       dequeue_task_dl()
953 	 *         update_curr_dl()
954 	 *           start_dl_timer()
955 	 *         __dequeue_task_dl()
956 	 *     prev->on_rq = 0;
957 	 *
958 	 * We can be both throttled and !queued. Replenish the counter
959 	 * but do not enqueue -- wait for our wakeup to do that.
960 	 */
961 	if (!task_on_rq_queued(p)) {
962 		replenish_dl_entity(dl_se, dl_se);
963 		goto unlock;
964 	}
965 
966 #ifdef CONFIG_SMP
967 	if (unlikely(!rq->online)) {
968 		/*
969 		 * If the runqueue is no longer available, migrate the
970 		 * task elsewhere. This necessarily changes rq.
971 		 */
972 		lockdep_unpin_lock(&rq->lock, rf.cookie);
973 		rq = dl_task_offline_migration(rq, p);
974 		rf.cookie = lockdep_pin_lock(&rq->lock);
975 		update_rq_clock(rq);
976 
977 		/*
978 		 * Now that the task has been migrated to the new RQ and we
979 		 * have that locked, proceed as normal and enqueue the task
980 		 * there.
981 		 */
982 	}
983 #endif
984 
985 	enqueue_task_dl(rq, p, ENQUEUE_REPLENISH);
986 	if (dl_task(rq->curr))
987 		check_preempt_curr_dl(rq, p, 0);
988 	else
989 		resched_curr(rq);
990 
991 #ifdef CONFIG_SMP
992 	/*
993 	 * Queueing this task back might have overloaded rq, check if we need
994 	 * to kick someone away.
995 	 */
996 	if (has_pushable_dl_tasks(rq)) {
997 		/*
998 		 * Nothing relies on rq->lock after this, so its safe to drop
999 		 * rq->lock.
1000 		 */
1001 		rq_unpin_lock(rq, &rf);
1002 		push_dl_task(rq);
1003 		rq_repin_lock(rq, &rf);
1004 	}
1005 #endif
1006 
1007 unlock:
1008 	task_rq_unlock(rq, p, &rf);
1009 
1010 	/*
1011 	 * This can free the task_struct, including this hrtimer, do not touch
1012 	 * anything related to that after this.
1013 	 */
1014 	put_task_struct(p);
1015 
1016 	return HRTIMER_NORESTART;
1017 }
1018 
1019 void init_dl_task_timer(struct sched_dl_entity *dl_se)
1020 {
1021 	struct hrtimer *timer = &dl_se->dl_timer;
1022 
1023 	hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1024 	timer->function = dl_task_timer;
1025 }
1026 
1027 /*
1028  * During the activation, CBS checks if it can reuse the current task's
1029  * runtime and period. If the deadline of the task is in the past, CBS
1030  * cannot use the runtime, and so it replenishes the task. This rule
1031  * works fine for implicit deadline tasks (deadline == period), and the
1032  * CBS was designed for implicit deadline tasks. However, a task with
1033  * constrained deadline (deadine < period) might be awakened after the
1034  * deadline, but before the next period. In this case, replenishing the
1035  * task would allow it to run for runtime / deadline. As in this case
1036  * deadline < period, CBS enables a task to run for more than the
1037  * runtime / period. In a very loaded system, this can cause a domino
1038  * effect, making other tasks miss their deadlines.
1039  *
1040  * To avoid this problem, in the activation of a constrained deadline
1041  * task after the deadline but before the next period, throttle the
1042  * task and set the replenishing timer to the begin of the next period,
1043  * unless it is boosted.
1044  */
1045 static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
1046 {
1047 	struct task_struct *p = dl_task_of(dl_se);
1048 	struct rq *rq = rq_of_dl_rq(dl_rq_of_se(dl_se));
1049 
1050 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) &&
1051 	    dl_time_before(rq_clock(rq), dl_next_period(dl_se))) {
1052 		if (unlikely(dl_se->dl_boosted || !start_dl_timer(p)))
1053 			return;
1054 		dl_se->dl_throttled = 1;
1055 		if (dl_se->runtime > 0)
1056 			dl_se->runtime = 0;
1057 	}
1058 }
1059 
1060 static
1061 int dl_runtime_exceeded(struct sched_dl_entity *dl_se)
1062 {
1063 	return (dl_se->runtime <= 0);
1064 }
1065 
1066 extern bool sched_rt_bandwidth_account(struct rt_rq *rt_rq);
1067 
1068 /*
1069  * This function implements the GRUB accounting rule:
1070  * according to the GRUB reclaiming algorithm, the runtime is
1071  * not decreased as "dq = -dt", but as
1072  * "dq = -max{u / Umax, (1 - Uinact - Uextra)} dt",
1073  * where u is the utilization of the task, Umax is the maximum reclaimable
1074  * utilization, Uinact is the (per-runqueue) inactive utilization, computed
1075  * as the difference between the "total runqueue utilization" and the
1076  * runqueue active utilization, and Uextra is the (per runqueue) extra
1077  * reclaimable utilization.
1078  * Since rq->dl.running_bw and rq->dl.this_bw contain utilizations
1079  * multiplied by 2^BW_SHIFT, the result has to be shifted right by
1080  * BW_SHIFT.
1081  * Since rq->dl.bw_ratio contains 1 / Umax multipled by 2^RATIO_SHIFT,
1082  * dl_bw is multiped by rq->dl.bw_ratio and shifted right by RATIO_SHIFT.
1083  * Since delta is a 64 bit variable, to have an overflow its value
1084  * should be larger than 2^(64 - 20 - 8), which is more than 64 seconds.
1085  * So, overflow is not an issue here.
1086  */
1087 u64 grub_reclaim(u64 delta, struct rq *rq, struct sched_dl_entity *dl_se)
1088 {
1089 	u64 u_inact = rq->dl.this_bw - rq->dl.running_bw; /* Utot - Uact */
1090 	u64 u_act;
1091 	u64 u_act_min = (dl_se->dl_bw * rq->dl.bw_ratio) >> RATIO_SHIFT;
1092 
1093 	/*
1094 	 * Instead of computing max{u * bw_ratio, (1 - u_inact - u_extra)},
1095 	 * we compare u_inact + rq->dl.extra_bw with
1096 	 * 1 - (u * rq->dl.bw_ratio >> RATIO_SHIFT), because
1097 	 * u_inact + rq->dl.extra_bw can be larger than
1098 	 * 1 * (so, 1 - u_inact - rq->dl.extra_bw would be negative
1099 	 * leading to wrong results)
1100 	 */
1101 	if (u_inact + rq->dl.extra_bw > BW_UNIT - u_act_min)
1102 		u_act = u_act_min;
1103 	else
1104 		u_act = BW_UNIT - u_inact - rq->dl.extra_bw;
1105 
1106 	return (delta * u_act) >> BW_SHIFT;
1107 }
1108 
1109 /*
1110  * Update the current task's runtime statistics (provided it is still
1111  * a -deadline task and has not been removed from the dl_rq).
1112  */
1113 static void update_curr_dl(struct rq *rq)
1114 {
1115 	struct task_struct *curr = rq->curr;
1116 	struct sched_dl_entity *dl_se = &curr->dl;
1117 	u64 delta_exec;
1118 
1119 	if (!dl_task(curr) || !on_dl_rq(dl_se))
1120 		return;
1121 
1122 	/*
1123 	 * Consumed budget is computed considering the time as
1124 	 * observed by schedulable tasks (excluding time spent
1125 	 * in hardirq context, etc.). Deadlines are instead
1126 	 * computed using hard walltime. This seems to be the more
1127 	 * natural solution, but the full ramifications of this
1128 	 * approach need further study.
1129 	 */
1130 	delta_exec = rq_clock_task(rq) - curr->se.exec_start;
1131 	if (unlikely((s64)delta_exec <= 0)) {
1132 		if (unlikely(dl_se->dl_yielded))
1133 			goto throttle;
1134 		return;
1135 	}
1136 
1137 	/* kick cpufreq (see the comment in kernel/sched/sched.h). */
1138 	cpufreq_update_util(rq, SCHED_CPUFREQ_DL);
1139 
1140 	schedstat_set(curr->se.statistics.exec_max,
1141 		      max(curr->se.statistics.exec_max, delta_exec));
1142 
1143 	curr->se.sum_exec_runtime += delta_exec;
1144 	account_group_exec_runtime(curr, delta_exec);
1145 
1146 	curr->se.exec_start = rq_clock_task(rq);
1147 	cpuacct_charge(curr, delta_exec);
1148 
1149 	sched_rt_avg_update(rq, delta_exec);
1150 
1151 	if (unlikely(dl_se->flags & SCHED_FLAG_RECLAIM))
1152 		delta_exec = grub_reclaim(delta_exec, rq, &curr->dl);
1153 	dl_se->runtime -= delta_exec;
1154 
1155 throttle:
1156 	if (dl_runtime_exceeded(dl_se) || dl_se->dl_yielded) {
1157 		dl_se->dl_throttled = 1;
1158 		__dequeue_task_dl(rq, curr, 0);
1159 		if (unlikely(dl_se->dl_boosted || !start_dl_timer(curr)))
1160 			enqueue_task_dl(rq, curr, ENQUEUE_REPLENISH);
1161 
1162 		if (!is_leftmost(curr, &rq->dl))
1163 			resched_curr(rq);
1164 	}
1165 
1166 	/*
1167 	 * Because -- for now -- we share the rt bandwidth, we need to
1168 	 * account our runtime there too, otherwise actual rt tasks
1169 	 * would be able to exceed the shared quota.
1170 	 *
1171 	 * Account to the root rt group for now.
1172 	 *
1173 	 * The solution we're working towards is having the RT groups scheduled
1174 	 * using deadline servers -- however there's a few nasties to figure
1175 	 * out before that can happen.
1176 	 */
1177 	if (rt_bandwidth_enabled()) {
1178 		struct rt_rq *rt_rq = &rq->rt;
1179 
1180 		raw_spin_lock(&rt_rq->rt_runtime_lock);
1181 		/*
1182 		 * We'll let actual RT tasks worry about the overflow here, we
1183 		 * have our own CBS to keep us inline; only account when RT
1184 		 * bandwidth is relevant.
1185 		 */
1186 		if (sched_rt_bandwidth_account(rt_rq))
1187 			rt_rq->rt_time += delta_exec;
1188 		raw_spin_unlock(&rt_rq->rt_runtime_lock);
1189 	}
1190 }
1191 
1192 static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
1193 {
1194 	struct sched_dl_entity *dl_se = container_of(timer,
1195 						     struct sched_dl_entity,
1196 						     inactive_timer);
1197 	struct task_struct *p = dl_task_of(dl_se);
1198 	struct rq_flags rf;
1199 	struct rq *rq;
1200 
1201 	rq = task_rq_lock(p, &rf);
1202 
1203 	if (!dl_task(p) || p->state == TASK_DEAD) {
1204 		struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
1205 
1206 		if (p->state == TASK_DEAD && dl_se->dl_non_contending) {
1207 			sub_running_bw(p->dl.dl_bw, dl_rq_of_se(&p->dl));
1208 			sub_rq_bw(p->dl.dl_bw, dl_rq_of_se(&p->dl));
1209 			dl_se->dl_non_contending = 0;
1210 		}
1211 
1212 		raw_spin_lock(&dl_b->lock);
1213 		__dl_clear(dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
1214 		raw_spin_unlock(&dl_b->lock);
1215 		__dl_clear_params(p);
1216 
1217 		goto unlock;
1218 	}
1219 	if (dl_se->dl_non_contending == 0)
1220 		goto unlock;
1221 
1222 	sched_clock_tick();
1223 	update_rq_clock(rq);
1224 
1225 	sub_running_bw(dl_se->dl_bw, &rq->dl);
1226 	dl_se->dl_non_contending = 0;
1227 unlock:
1228 	task_rq_unlock(rq, p, &rf);
1229 	put_task_struct(p);
1230 
1231 	return HRTIMER_NORESTART;
1232 }
1233 
1234 void init_dl_inactive_task_timer(struct sched_dl_entity *dl_se)
1235 {
1236 	struct hrtimer *timer = &dl_se->inactive_timer;
1237 
1238 	hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1239 	timer->function = inactive_task_timer;
1240 }
1241 
1242 #ifdef CONFIG_SMP
1243 
1244 static void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
1245 {
1246 	struct rq *rq = rq_of_dl_rq(dl_rq);
1247 
1248 	if (dl_rq->earliest_dl.curr == 0 ||
1249 	    dl_time_before(deadline, dl_rq->earliest_dl.curr)) {
1250 		dl_rq->earliest_dl.curr = deadline;
1251 		cpudl_set(&rq->rd->cpudl, rq->cpu, deadline);
1252 	}
1253 }
1254 
1255 static void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
1256 {
1257 	struct rq *rq = rq_of_dl_rq(dl_rq);
1258 
1259 	/*
1260 	 * Since we may have removed our earliest (and/or next earliest)
1261 	 * task we must recompute them.
1262 	 */
1263 	if (!dl_rq->dl_nr_running) {
1264 		dl_rq->earliest_dl.curr = 0;
1265 		dl_rq->earliest_dl.next = 0;
1266 		cpudl_clear(&rq->rd->cpudl, rq->cpu);
1267 	} else {
1268 		struct rb_node *leftmost = dl_rq->root.rb_leftmost;
1269 		struct sched_dl_entity *entry;
1270 
1271 		entry = rb_entry(leftmost, struct sched_dl_entity, rb_node);
1272 		dl_rq->earliest_dl.curr = entry->deadline;
1273 		cpudl_set(&rq->rd->cpudl, rq->cpu, entry->deadline);
1274 	}
1275 }
1276 
1277 #else
1278 
1279 static inline void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
1280 static inline void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
1281 
1282 #endif /* CONFIG_SMP */
1283 
1284 static inline
1285 void inc_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
1286 {
1287 	int prio = dl_task_of(dl_se)->prio;
1288 	u64 deadline = dl_se->deadline;
1289 
1290 	WARN_ON(!dl_prio(prio));
1291 	dl_rq->dl_nr_running++;
1292 	add_nr_running(rq_of_dl_rq(dl_rq), 1);
1293 
1294 	inc_dl_deadline(dl_rq, deadline);
1295 	inc_dl_migration(dl_se, dl_rq);
1296 }
1297 
1298 static inline
1299 void dec_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
1300 {
1301 	int prio = dl_task_of(dl_se)->prio;
1302 
1303 	WARN_ON(!dl_prio(prio));
1304 	WARN_ON(!dl_rq->dl_nr_running);
1305 	dl_rq->dl_nr_running--;
1306 	sub_nr_running(rq_of_dl_rq(dl_rq), 1);
1307 
1308 	dec_dl_deadline(dl_rq, dl_se->deadline);
1309 	dec_dl_migration(dl_se, dl_rq);
1310 }
1311 
1312 static void __enqueue_dl_entity(struct sched_dl_entity *dl_se)
1313 {
1314 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
1315 	struct rb_node **link = &dl_rq->root.rb_root.rb_node;
1316 	struct rb_node *parent = NULL;
1317 	struct sched_dl_entity *entry;
1318 	int leftmost = 1;
1319 
1320 	BUG_ON(!RB_EMPTY_NODE(&dl_se->rb_node));
1321 
1322 	while (*link) {
1323 		parent = *link;
1324 		entry = rb_entry(parent, struct sched_dl_entity, rb_node);
1325 		if (dl_time_before(dl_se->deadline, entry->deadline))
1326 			link = &parent->rb_left;
1327 		else {
1328 			link = &parent->rb_right;
1329 			leftmost = 0;
1330 		}
1331 	}
1332 
1333 	rb_link_node(&dl_se->rb_node, parent, link);
1334 	rb_insert_color_cached(&dl_se->rb_node, &dl_rq->root, leftmost);
1335 
1336 	inc_dl_tasks(dl_se, dl_rq);
1337 }
1338 
1339 static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
1340 {
1341 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
1342 
1343 	if (RB_EMPTY_NODE(&dl_se->rb_node))
1344 		return;
1345 
1346 	rb_erase_cached(&dl_se->rb_node, &dl_rq->root);
1347 	RB_CLEAR_NODE(&dl_se->rb_node);
1348 
1349 	dec_dl_tasks(dl_se, dl_rq);
1350 }
1351 
1352 static void
1353 enqueue_dl_entity(struct sched_dl_entity *dl_se,
1354 		  struct sched_dl_entity *pi_se, int flags)
1355 {
1356 	BUG_ON(on_dl_rq(dl_se));
1357 
1358 	/*
1359 	 * If this is a wakeup or a new instance, the scheduling
1360 	 * parameters of the task might need updating. Otherwise,
1361 	 * we want a replenishment of its runtime.
1362 	 */
1363 	if (flags & ENQUEUE_WAKEUP) {
1364 		task_contending(dl_se, flags);
1365 		update_dl_entity(dl_se, pi_se);
1366 	} else if (flags & ENQUEUE_REPLENISH) {
1367 		replenish_dl_entity(dl_se, pi_se);
1368 	}
1369 
1370 	__enqueue_dl_entity(dl_se);
1371 }
1372 
1373 static void dequeue_dl_entity(struct sched_dl_entity *dl_se)
1374 {
1375 	__dequeue_dl_entity(dl_se);
1376 }
1377 
1378 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags)
1379 {
1380 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
1381 	struct sched_dl_entity *pi_se = &p->dl;
1382 
1383 	/*
1384 	 * Use the scheduling parameters of the top pi-waiter task if:
1385 	 * - we have a top pi-waiter which is a SCHED_DEADLINE task AND
1386 	 * - our dl_boosted is set (i.e. the pi-waiter's (absolute) deadline is
1387 	 *   smaller than our deadline OR we are a !SCHED_DEADLINE task getting
1388 	 *   boosted due to a SCHED_DEADLINE pi-waiter).
1389 	 * Otherwise we keep our runtime and deadline.
1390 	 */
1391 	if (pi_task && dl_prio(pi_task->normal_prio) && p->dl.dl_boosted) {
1392 		pi_se = &pi_task->dl;
1393 	} else if (!dl_prio(p->normal_prio)) {
1394 		/*
1395 		 * Special case in which we have a !SCHED_DEADLINE task
1396 		 * that is going to be deboosted, but exceeds its
1397 		 * runtime while doing so. No point in replenishing
1398 		 * it, as it's going to return back to its original
1399 		 * scheduling class after this.
1400 		 */
1401 		BUG_ON(!p->dl.dl_boosted || flags != ENQUEUE_REPLENISH);
1402 		return;
1403 	}
1404 
1405 	/*
1406 	 * Check if a constrained deadline task was activated
1407 	 * after the deadline but before the next period.
1408 	 * If that is the case, the task will be throttled and
1409 	 * the replenishment timer will be set to the next period.
1410 	 */
1411 	if (!p->dl.dl_throttled && !dl_is_implicit(&p->dl))
1412 		dl_check_constrained_dl(&p->dl);
1413 
1414 	if (p->on_rq == TASK_ON_RQ_MIGRATING || flags & ENQUEUE_RESTORE) {
1415 		add_rq_bw(p->dl.dl_bw, &rq->dl);
1416 		add_running_bw(p->dl.dl_bw, &rq->dl);
1417 	}
1418 
1419 	/*
1420 	 * If p is throttled, we do not enqueue it. In fact, if it exhausted
1421 	 * its budget it needs a replenishment and, since it now is on
1422 	 * its rq, the bandwidth timer callback (which clearly has not
1423 	 * run yet) will take care of this.
1424 	 * However, the active utilization does not depend on the fact
1425 	 * that the task is on the runqueue or not (but depends on the
1426 	 * task's state - in GRUB parlance, "inactive" vs "active contending").
1427 	 * In other words, even if a task is throttled its utilization must
1428 	 * be counted in the active utilization; hence, we need to call
1429 	 * add_running_bw().
1430 	 */
1431 	if (p->dl.dl_throttled && !(flags & ENQUEUE_REPLENISH)) {
1432 		if (flags & ENQUEUE_WAKEUP)
1433 			task_contending(&p->dl, flags);
1434 
1435 		return;
1436 	}
1437 
1438 	enqueue_dl_entity(&p->dl, pi_se, flags);
1439 
1440 	if (!task_current(rq, p) && p->nr_cpus_allowed > 1)
1441 		enqueue_pushable_dl_task(rq, p);
1442 }
1443 
1444 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
1445 {
1446 	dequeue_dl_entity(&p->dl);
1447 	dequeue_pushable_dl_task(rq, p);
1448 }
1449 
1450 static void dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
1451 {
1452 	update_curr_dl(rq);
1453 	__dequeue_task_dl(rq, p, flags);
1454 
1455 	if (p->on_rq == TASK_ON_RQ_MIGRATING || flags & DEQUEUE_SAVE) {
1456 		sub_running_bw(p->dl.dl_bw, &rq->dl);
1457 		sub_rq_bw(p->dl.dl_bw, &rq->dl);
1458 	}
1459 
1460 	/*
1461 	 * This check allows to start the inactive timer (or to immediately
1462 	 * decrease the active utilization, if needed) in two cases:
1463 	 * when the task blocks and when it is terminating
1464 	 * (p->state == TASK_DEAD). We can handle the two cases in the same
1465 	 * way, because from GRUB's point of view the same thing is happening
1466 	 * (the task moves from "active contending" to "active non contending"
1467 	 * or "inactive")
1468 	 */
1469 	if (flags & DEQUEUE_SLEEP)
1470 		task_non_contending(p);
1471 }
1472 
1473 /*
1474  * Yield task semantic for -deadline tasks is:
1475  *
1476  *   get off from the CPU until our next instance, with
1477  *   a new runtime. This is of little use now, since we
1478  *   don't have a bandwidth reclaiming mechanism. Anyway,
1479  *   bandwidth reclaiming is planned for the future, and
1480  *   yield_task_dl will indicate that some spare budget
1481  *   is available for other task instances to use it.
1482  */
1483 static void yield_task_dl(struct rq *rq)
1484 {
1485 	/*
1486 	 * We make the task go to sleep until its current deadline by
1487 	 * forcing its runtime to zero. This way, update_curr_dl() stops
1488 	 * it and the bandwidth timer will wake it up and will give it
1489 	 * new scheduling parameters (thanks to dl_yielded=1).
1490 	 */
1491 	rq->curr->dl.dl_yielded = 1;
1492 
1493 	update_rq_clock(rq);
1494 	update_curr_dl(rq);
1495 	/*
1496 	 * Tell update_rq_clock() that we've just updated,
1497 	 * so we don't do microscopic update in schedule()
1498 	 * and double the fastpath cost.
1499 	 */
1500 	rq_clock_skip_update(rq, true);
1501 }
1502 
1503 #ifdef CONFIG_SMP
1504 
1505 static int find_later_rq(struct task_struct *task);
1506 
1507 static int
1508 select_task_rq_dl(struct task_struct *p, int cpu, int sd_flag, int flags)
1509 {
1510 	struct task_struct *curr;
1511 	struct rq *rq;
1512 
1513 	if (sd_flag != SD_BALANCE_WAKE)
1514 		goto out;
1515 
1516 	rq = cpu_rq(cpu);
1517 
1518 	rcu_read_lock();
1519 	curr = READ_ONCE(rq->curr); /* unlocked access */
1520 
1521 	/*
1522 	 * If we are dealing with a -deadline task, we must
1523 	 * decide where to wake it up.
1524 	 * If it has a later deadline and the current task
1525 	 * on this rq can't move (provided the waking task
1526 	 * can!) we prefer to send it somewhere else. On the
1527 	 * other hand, if it has a shorter deadline, we
1528 	 * try to make it stay here, it might be important.
1529 	 */
1530 	if (unlikely(dl_task(curr)) &&
1531 	    (curr->nr_cpus_allowed < 2 ||
1532 	     !dl_entity_preempt(&p->dl, &curr->dl)) &&
1533 	    (p->nr_cpus_allowed > 1)) {
1534 		int target = find_later_rq(p);
1535 
1536 		if (target != -1 &&
1537 				(dl_time_before(p->dl.deadline,
1538 					cpu_rq(target)->dl.earliest_dl.curr) ||
1539 				(cpu_rq(target)->dl.dl_nr_running == 0)))
1540 			cpu = target;
1541 	}
1542 	rcu_read_unlock();
1543 
1544 out:
1545 	return cpu;
1546 }
1547 
1548 static void migrate_task_rq_dl(struct task_struct *p)
1549 {
1550 	struct rq *rq;
1551 
1552 	if (p->state != TASK_WAKING)
1553 		return;
1554 
1555 	rq = task_rq(p);
1556 	/*
1557 	 * Since p->state == TASK_WAKING, set_task_cpu() has been called
1558 	 * from try_to_wake_up(). Hence, p->pi_lock is locked, but
1559 	 * rq->lock is not... So, lock it
1560 	 */
1561 	raw_spin_lock(&rq->lock);
1562 	if (p->dl.dl_non_contending) {
1563 		sub_running_bw(p->dl.dl_bw, &rq->dl);
1564 		p->dl.dl_non_contending = 0;
1565 		/*
1566 		 * If the timer handler is currently running and the
1567 		 * timer cannot be cancelled, inactive_task_timer()
1568 		 * will see that dl_not_contending is not set, and
1569 		 * will not touch the rq's active utilization,
1570 		 * so we are still safe.
1571 		 */
1572 		if (hrtimer_try_to_cancel(&p->dl.inactive_timer) == 1)
1573 			put_task_struct(p);
1574 	}
1575 	sub_rq_bw(p->dl.dl_bw, &rq->dl);
1576 	raw_spin_unlock(&rq->lock);
1577 }
1578 
1579 static void check_preempt_equal_dl(struct rq *rq, struct task_struct *p)
1580 {
1581 	/*
1582 	 * Current can't be migrated, useless to reschedule,
1583 	 * let's hope p can move out.
1584 	 */
1585 	if (rq->curr->nr_cpus_allowed == 1 ||
1586 	    !cpudl_find(&rq->rd->cpudl, rq->curr, NULL))
1587 		return;
1588 
1589 	/*
1590 	 * p is migratable, so let's not schedule it and
1591 	 * see if it is pushed or pulled somewhere else.
1592 	 */
1593 	if (p->nr_cpus_allowed != 1 &&
1594 	    cpudl_find(&rq->rd->cpudl, p, NULL))
1595 		return;
1596 
1597 	resched_curr(rq);
1598 }
1599 
1600 #endif /* CONFIG_SMP */
1601 
1602 /*
1603  * Only called when both the current and waking task are -deadline
1604  * tasks.
1605  */
1606 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
1607 				  int flags)
1608 {
1609 	if (dl_entity_preempt(&p->dl, &rq->curr->dl)) {
1610 		resched_curr(rq);
1611 		return;
1612 	}
1613 
1614 #ifdef CONFIG_SMP
1615 	/*
1616 	 * In the unlikely case current and p have the same deadline
1617 	 * let us try to decide what's the best thing to do...
1618 	 */
1619 	if ((p->dl.deadline == rq->curr->dl.deadline) &&
1620 	    !test_tsk_need_resched(rq->curr))
1621 		check_preempt_equal_dl(rq, p);
1622 #endif /* CONFIG_SMP */
1623 }
1624 
1625 #ifdef CONFIG_SCHED_HRTICK
1626 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1627 {
1628 	hrtick_start(rq, p->dl.runtime);
1629 }
1630 #else /* !CONFIG_SCHED_HRTICK */
1631 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1632 {
1633 }
1634 #endif
1635 
1636 static struct sched_dl_entity *pick_next_dl_entity(struct rq *rq,
1637 						   struct dl_rq *dl_rq)
1638 {
1639 	struct rb_node *left = rb_first_cached(&dl_rq->root);
1640 
1641 	if (!left)
1642 		return NULL;
1643 
1644 	return rb_entry(left, struct sched_dl_entity, rb_node);
1645 }
1646 
1647 static struct task_struct *
1648 pick_next_task_dl(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
1649 {
1650 	struct sched_dl_entity *dl_se;
1651 	struct task_struct *p;
1652 	struct dl_rq *dl_rq;
1653 
1654 	dl_rq = &rq->dl;
1655 
1656 	if (need_pull_dl_task(rq, prev)) {
1657 		/*
1658 		 * This is OK, because current is on_cpu, which avoids it being
1659 		 * picked for load-balance and preemption/IRQs are still
1660 		 * disabled avoiding further scheduler activity on it and we're
1661 		 * being very careful to re-start the picking loop.
1662 		 */
1663 		rq_unpin_lock(rq, rf);
1664 		pull_dl_task(rq);
1665 		rq_repin_lock(rq, rf);
1666 		/*
1667 		 * pull_dl_task() can drop (and re-acquire) rq->lock; this
1668 		 * means a stop task can slip in, in which case we need to
1669 		 * re-start task selection.
1670 		 */
1671 		if (rq->stop && task_on_rq_queued(rq->stop))
1672 			return RETRY_TASK;
1673 	}
1674 
1675 	/*
1676 	 * When prev is DL, we may throttle it in put_prev_task().
1677 	 * So, we update time before we check for dl_nr_running.
1678 	 */
1679 	if (prev->sched_class == &dl_sched_class)
1680 		update_curr_dl(rq);
1681 
1682 	if (unlikely(!dl_rq->dl_nr_running))
1683 		return NULL;
1684 
1685 	put_prev_task(rq, prev);
1686 
1687 	dl_se = pick_next_dl_entity(rq, dl_rq);
1688 	BUG_ON(!dl_se);
1689 
1690 	p = dl_task_of(dl_se);
1691 	p->se.exec_start = rq_clock_task(rq);
1692 
1693 	/* Running task will never be pushed. */
1694        dequeue_pushable_dl_task(rq, p);
1695 
1696 	if (hrtick_enabled(rq))
1697 		start_hrtick_dl(rq, p);
1698 
1699 	queue_push_tasks(rq);
1700 
1701 	return p;
1702 }
1703 
1704 static void put_prev_task_dl(struct rq *rq, struct task_struct *p)
1705 {
1706 	update_curr_dl(rq);
1707 
1708 	if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1)
1709 		enqueue_pushable_dl_task(rq, p);
1710 }
1711 
1712 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued)
1713 {
1714 	update_curr_dl(rq);
1715 
1716 	/*
1717 	 * Even when we have runtime, update_curr_dl() might have resulted in us
1718 	 * not being the leftmost task anymore. In that case NEED_RESCHED will
1719 	 * be set and schedule() will start a new hrtick for the next task.
1720 	 */
1721 	if (hrtick_enabled(rq) && queued && p->dl.runtime > 0 &&
1722 	    is_leftmost(p, &rq->dl))
1723 		start_hrtick_dl(rq, p);
1724 }
1725 
1726 static void task_fork_dl(struct task_struct *p)
1727 {
1728 	/*
1729 	 * SCHED_DEADLINE tasks cannot fork and this is achieved through
1730 	 * sched_fork()
1731 	 */
1732 }
1733 
1734 static void set_curr_task_dl(struct rq *rq)
1735 {
1736 	struct task_struct *p = rq->curr;
1737 
1738 	p->se.exec_start = rq_clock_task(rq);
1739 
1740 	/* You can't push away the running task */
1741 	dequeue_pushable_dl_task(rq, p);
1742 }
1743 
1744 #ifdef CONFIG_SMP
1745 
1746 /* Only try algorithms three times */
1747 #define DL_MAX_TRIES 3
1748 
1749 static int pick_dl_task(struct rq *rq, struct task_struct *p, int cpu)
1750 {
1751 	if (!task_running(rq, p) &&
1752 	    cpumask_test_cpu(cpu, &p->cpus_allowed))
1753 		return 1;
1754 	return 0;
1755 }
1756 
1757 /*
1758  * Return the earliest pushable rq's task, which is suitable to be executed
1759  * on the CPU, NULL otherwise:
1760  */
1761 static struct task_struct *pick_earliest_pushable_dl_task(struct rq *rq, int cpu)
1762 {
1763 	struct rb_node *next_node = rq->dl.pushable_dl_tasks_root.rb_leftmost;
1764 	struct task_struct *p = NULL;
1765 
1766 	if (!has_pushable_dl_tasks(rq))
1767 		return NULL;
1768 
1769 next_node:
1770 	if (next_node) {
1771 		p = rb_entry(next_node, struct task_struct, pushable_dl_tasks);
1772 
1773 		if (pick_dl_task(rq, p, cpu))
1774 			return p;
1775 
1776 		next_node = rb_next(next_node);
1777 		goto next_node;
1778 	}
1779 
1780 	return NULL;
1781 }
1782 
1783 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
1784 
1785 static int find_later_rq(struct task_struct *task)
1786 {
1787 	struct sched_domain *sd;
1788 	struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
1789 	int this_cpu = smp_processor_id();
1790 	int cpu = task_cpu(task);
1791 
1792 	/* Make sure the mask is initialized first */
1793 	if (unlikely(!later_mask))
1794 		return -1;
1795 
1796 	if (task->nr_cpus_allowed == 1)
1797 		return -1;
1798 
1799 	/*
1800 	 * We have to consider system topology and task affinity
1801 	 * first, then we can look for a suitable cpu.
1802 	 */
1803 	if (!cpudl_find(&task_rq(task)->rd->cpudl, task, later_mask))
1804 		return -1;
1805 
1806 	/*
1807 	 * If we are here, some targets have been found, including
1808 	 * the most suitable which is, among the runqueues where the
1809 	 * current tasks have later deadlines than the task's one, the
1810 	 * rq with the latest possible one.
1811 	 *
1812 	 * Now we check how well this matches with task's
1813 	 * affinity and system topology.
1814 	 *
1815 	 * The last cpu where the task run is our first
1816 	 * guess, since it is most likely cache-hot there.
1817 	 */
1818 	if (cpumask_test_cpu(cpu, later_mask))
1819 		return cpu;
1820 	/*
1821 	 * Check if this_cpu is to be skipped (i.e., it is
1822 	 * not in the mask) or not.
1823 	 */
1824 	if (!cpumask_test_cpu(this_cpu, later_mask))
1825 		this_cpu = -1;
1826 
1827 	rcu_read_lock();
1828 	for_each_domain(cpu, sd) {
1829 		if (sd->flags & SD_WAKE_AFFINE) {
1830 			int best_cpu;
1831 
1832 			/*
1833 			 * If possible, preempting this_cpu is
1834 			 * cheaper than migrating.
1835 			 */
1836 			if (this_cpu != -1 &&
1837 			    cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
1838 				rcu_read_unlock();
1839 				return this_cpu;
1840 			}
1841 
1842 			best_cpu = cpumask_first_and(later_mask,
1843 							sched_domain_span(sd));
1844 			/*
1845 			 * Last chance: if a cpu being in both later_mask
1846 			 * and current sd span is valid, that becomes our
1847 			 * choice. Of course, the latest possible cpu is
1848 			 * already under consideration through later_mask.
1849 			 */
1850 			if (best_cpu < nr_cpu_ids) {
1851 				rcu_read_unlock();
1852 				return best_cpu;
1853 			}
1854 		}
1855 	}
1856 	rcu_read_unlock();
1857 
1858 	/*
1859 	 * At this point, all our guesses failed, we just return
1860 	 * 'something', and let the caller sort the things out.
1861 	 */
1862 	if (this_cpu != -1)
1863 		return this_cpu;
1864 
1865 	cpu = cpumask_any(later_mask);
1866 	if (cpu < nr_cpu_ids)
1867 		return cpu;
1868 
1869 	return -1;
1870 }
1871 
1872 /* Locks the rq it finds */
1873 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq)
1874 {
1875 	struct rq *later_rq = NULL;
1876 	int tries;
1877 	int cpu;
1878 
1879 	for (tries = 0; tries < DL_MAX_TRIES; tries++) {
1880 		cpu = find_later_rq(task);
1881 
1882 		if ((cpu == -1) || (cpu == rq->cpu))
1883 			break;
1884 
1885 		later_rq = cpu_rq(cpu);
1886 
1887 		if (later_rq->dl.dl_nr_running &&
1888 		    !dl_time_before(task->dl.deadline,
1889 					later_rq->dl.earliest_dl.curr)) {
1890 			/*
1891 			 * Target rq has tasks of equal or earlier deadline,
1892 			 * retrying does not release any lock and is unlikely
1893 			 * to yield a different result.
1894 			 */
1895 			later_rq = NULL;
1896 			break;
1897 		}
1898 
1899 		/* Retry if something changed. */
1900 		if (double_lock_balance(rq, later_rq)) {
1901 			if (unlikely(task_rq(task) != rq ||
1902 				     !cpumask_test_cpu(later_rq->cpu, &task->cpus_allowed) ||
1903 				     task_running(rq, task) ||
1904 				     !dl_task(task) ||
1905 				     !task_on_rq_queued(task))) {
1906 				double_unlock_balance(rq, later_rq);
1907 				later_rq = NULL;
1908 				break;
1909 			}
1910 		}
1911 
1912 		/*
1913 		 * If the rq we found has no -deadline task, or
1914 		 * its earliest one has a later deadline than our
1915 		 * task, the rq is a good one.
1916 		 */
1917 		if (!later_rq->dl.dl_nr_running ||
1918 		    dl_time_before(task->dl.deadline,
1919 				   later_rq->dl.earliest_dl.curr))
1920 			break;
1921 
1922 		/* Otherwise we try again. */
1923 		double_unlock_balance(rq, later_rq);
1924 		later_rq = NULL;
1925 	}
1926 
1927 	return later_rq;
1928 }
1929 
1930 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq)
1931 {
1932 	struct task_struct *p;
1933 
1934 	if (!has_pushable_dl_tasks(rq))
1935 		return NULL;
1936 
1937 	p = rb_entry(rq->dl.pushable_dl_tasks_root.rb_leftmost,
1938 		     struct task_struct, pushable_dl_tasks);
1939 
1940 	BUG_ON(rq->cpu != task_cpu(p));
1941 	BUG_ON(task_current(rq, p));
1942 	BUG_ON(p->nr_cpus_allowed <= 1);
1943 
1944 	BUG_ON(!task_on_rq_queued(p));
1945 	BUG_ON(!dl_task(p));
1946 
1947 	return p;
1948 }
1949 
1950 /*
1951  * See if the non running -deadline tasks on this rq
1952  * can be sent to some other CPU where they can preempt
1953  * and start executing.
1954  */
1955 static int push_dl_task(struct rq *rq)
1956 {
1957 	struct task_struct *next_task;
1958 	struct rq *later_rq;
1959 	int ret = 0;
1960 
1961 	if (!rq->dl.overloaded)
1962 		return 0;
1963 
1964 	next_task = pick_next_pushable_dl_task(rq);
1965 	if (!next_task)
1966 		return 0;
1967 
1968 retry:
1969 	if (unlikely(next_task == rq->curr)) {
1970 		WARN_ON(1);
1971 		return 0;
1972 	}
1973 
1974 	/*
1975 	 * If next_task preempts rq->curr, and rq->curr
1976 	 * can move away, it makes sense to just reschedule
1977 	 * without going further in pushing next_task.
1978 	 */
1979 	if (dl_task(rq->curr) &&
1980 	    dl_time_before(next_task->dl.deadline, rq->curr->dl.deadline) &&
1981 	    rq->curr->nr_cpus_allowed > 1) {
1982 		resched_curr(rq);
1983 		return 0;
1984 	}
1985 
1986 	/* We might release rq lock */
1987 	get_task_struct(next_task);
1988 
1989 	/* Will lock the rq it'll find */
1990 	later_rq = find_lock_later_rq(next_task, rq);
1991 	if (!later_rq) {
1992 		struct task_struct *task;
1993 
1994 		/*
1995 		 * We must check all this again, since
1996 		 * find_lock_later_rq releases rq->lock and it is
1997 		 * then possible that next_task has migrated.
1998 		 */
1999 		task = pick_next_pushable_dl_task(rq);
2000 		if (task == next_task) {
2001 			/*
2002 			 * The task is still there. We don't try
2003 			 * again, some other cpu will pull it when ready.
2004 			 */
2005 			goto out;
2006 		}
2007 
2008 		if (!task)
2009 			/* No more tasks */
2010 			goto out;
2011 
2012 		put_task_struct(next_task);
2013 		next_task = task;
2014 		goto retry;
2015 	}
2016 
2017 	deactivate_task(rq, next_task, 0);
2018 	sub_running_bw(next_task->dl.dl_bw, &rq->dl);
2019 	sub_rq_bw(next_task->dl.dl_bw, &rq->dl);
2020 	set_task_cpu(next_task, later_rq->cpu);
2021 	add_rq_bw(next_task->dl.dl_bw, &later_rq->dl);
2022 	add_running_bw(next_task->dl.dl_bw, &later_rq->dl);
2023 	activate_task(later_rq, next_task, 0);
2024 	ret = 1;
2025 
2026 	resched_curr(later_rq);
2027 
2028 	double_unlock_balance(rq, later_rq);
2029 
2030 out:
2031 	put_task_struct(next_task);
2032 
2033 	return ret;
2034 }
2035 
2036 static void push_dl_tasks(struct rq *rq)
2037 {
2038 	/* push_dl_task() will return true if it moved a -deadline task */
2039 	while (push_dl_task(rq))
2040 		;
2041 }
2042 
2043 static void pull_dl_task(struct rq *this_rq)
2044 {
2045 	int this_cpu = this_rq->cpu, cpu;
2046 	struct task_struct *p;
2047 	bool resched = false;
2048 	struct rq *src_rq;
2049 	u64 dmin = LONG_MAX;
2050 
2051 	if (likely(!dl_overloaded(this_rq)))
2052 		return;
2053 
2054 	/*
2055 	 * Match the barrier from dl_set_overloaded; this guarantees that if we
2056 	 * see overloaded we must also see the dlo_mask bit.
2057 	 */
2058 	smp_rmb();
2059 
2060 	for_each_cpu(cpu, this_rq->rd->dlo_mask) {
2061 		if (this_cpu == cpu)
2062 			continue;
2063 
2064 		src_rq = cpu_rq(cpu);
2065 
2066 		/*
2067 		 * It looks racy, abd it is! However, as in sched_rt.c,
2068 		 * we are fine with this.
2069 		 */
2070 		if (this_rq->dl.dl_nr_running &&
2071 		    dl_time_before(this_rq->dl.earliest_dl.curr,
2072 				   src_rq->dl.earliest_dl.next))
2073 			continue;
2074 
2075 		/* Might drop this_rq->lock */
2076 		double_lock_balance(this_rq, src_rq);
2077 
2078 		/*
2079 		 * If there are no more pullable tasks on the
2080 		 * rq, we're done with it.
2081 		 */
2082 		if (src_rq->dl.dl_nr_running <= 1)
2083 			goto skip;
2084 
2085 		p = pick_earliest_pushable_dl_task(src_rq, this_cpu);
2086 
2087 		/*
2088 		 * We found a task to be pulled if:
2089 		 *  - it preempts our current (if there's one),
2090 		 *  - it will preempt the last one we pulled (if any).
2091 		 */
2092 		if (p && dl_time_before(p->dl.deadline, dmin) &&
2093 		    (!this_rq->dl.dl_nr_running ||
2094 		     dl_time_before(p->dl.deadline,
2095 				    this_rq->dl.earliest_dl.curr))) {
2096 			WARN_ON(p == src_rq->curr);
2097 			WARN_ON(!task_on_rq_queued(p));
2098 
2099 			/*
2100 			 * Then we pull iff p has actually an earlier
2101 			 * deadline than the current task of its runqueue.
2102 			 */
2103 			if (dl_time_before(p->dl.deadline,
2104 					   src_rq->curr->dl.deadline))
2105 				goto skip;
2106 
2107 			resched = true;
2108 
2109 			deactivate_task(src_rq, p, 0);
2110 			sub_running_bw(p->dl.dl_bw, &src_rq->dl);
2111 			sub_rq_bw(p->dl.dl_bw, &src_rq->dl);
2112 			set_task_cpu(p, this_cpu);
2113 			add_rq_bw(p->dl.dl_bw, &this_rq->dl);
2114 			add_running_bw(p->dl.dl_bw, &this_rq->dl);
2115 			activate_task(this_rq, p, 0);
2116 			dmin = p->dl.deadline;
2117 
2118 			/* Is there any other task even earlier? */
2119 		}
2120 skip:
2121 		double_unlock_balance(this_rq, src_rq);
2122 	}
2123 
2124 	if (resched)
2125 		resched_curr(this_rq);
2126 }
2127 
2128 /*
2129  * Since the task is not running and a reschedule is not going to happen
2130  * anytime soon on its runqueue, we try pushing it away now.
2131  */
2132 static void task_woken_dl(struct rq *rq, struct task_struct *p)
2133 {
2134 	if (!task_running(rq, p) &&
2135 	    !test_tsk_need_resched(rq->curr) &&
2136 	    p->nr_cpus_allowed > 1 &&
2137 	    dl_task(rq->curr) &&
2138 	    (rq->curr->nr_cpus_allowed < 2 ||
2139 	     !dl_entity_preempt(&p->dl, &rq->curr->dl))) {
2140 		push_dl_tasks(rq);
2141 	}
2142 }
2143 
2144 static void set_cpus_allowed_dl(struct task_struct *p,
2145 				const struct cpumask *new_mask)
2146 {
2147 	struct root_domain *src_rd;
2148 	struct rq *rq;
2149 
2150 	BUG_ON(!dl_task(p));
2151 
2152 	rq = task_rq(p);
2153 	src_rd = rq->rd;
2154 	/*
2155 	 * Migrating a SCHED_DEADLINE task between exclusive
2156 	 * cpusets (different root_domains) entails a bandwidth
2157 	 * update. We already made space for us in the destination
2158 	 * domain (see cpuset_can_attach()).
2159 	 */
2160 	if (!cpumask_intersects(src_rd->span, new_mask)) {
2161 		struct dl_bw *src_dl_b;
2162 
2163 		src_dl_b = dl_bw_of(cpu_of(rq));
2164 		/*
2165 		 * We now free resources of the root_domain we are migrating
2166 		 * off. In the worst case, sched_setattr() may temporary fail
2167 		 * until we complete the update.
2168 		 */
2169 		raw_spin_lock(&src_dl_b->lock);
2170 		__dl_clear(src_dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
2171 		raw_spin_unlock(&src_dl_b->lock);
2172 	}
2173 
2174 	set_cpus_allowed_common(p, new_mask);
2175 }
2176 
2177 /* Assumes rq->lock is held */
2178 static void rq_online_dl(struct rq *rq)
2179 {
2180 	if (rq->dl.overloaded)
2181 		dl_set_overload(rq);
2182 
2183 	cpudl_set_freecpu(&rq->rd->cpudl, rq->cpu);
2184 	if (rq->dl.dl_nr_running > 0)
2185 		cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr);
2186 }
2187 
2188 /* Assumes rq->lock is held */
2189 static void rq_offline_dl(struct rq *rq)
2190 {
2191 	if (rq->dl.overloaded)
2192 		dl_clear_overload(rq);
2193 
2194 	cpudl_clear(&rq->rd->cpudl, rq->cpu);
2195 	cpudl_clear_freecpu(&rq->rd->cpudl, rq->cpu);
2196 }
2197 
2198 void __init init_sched_dl_class(void)
2199 {
2200 	unsigned int i;
2201 
2202 	for_each_possible_cpu(i)
2203 		zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
2204 					GFP_KERNEL, cpu_to_node(i));
2205 }
2206 
2207 #endif /* CONFIG_SMP */
2208 
2209 static void switched_from_dl(struct rq *rq, struct task_struct *p)
2210 {
2211 	/*
2212 	 * task_non_contending() can start the "inactive timer" (if the 0-lag
2213 	 * time is in the future). If the task switches back to dl before
2214 	 * the "inactive timer" fires, it can continue to consume its current
2215 	 * runtime using its current deadline. If it stays outside of
2216 	 * SCHED_DEADLINE until the 0-lag time passes, inactive_task_timer()
2217 	 * will reset the task parameters.
2218 	 */
2219 	if (task_on_rq_queued(p) && p->dl.dl_runtime)
2220 		task_non_contending(p);
2221 
2222 	if (!task_on_rq_queued(p))
2223 		sub_rq_bw(p->dl.dl_bw, &rq->dl);
2224 
2225 	/*
2226 	 * We cannot use inactive_task_timer() to invoke sub_running_bw()
2227 	 * at the 0-lag time, because the task could have been migrated
2228 	 * while SCHED_OTHER in the meanwhile.
2229 	 */
2230 	if (p->dl.dl_non_contending)
2231 		p->dl.dl_non_contending = 0;
2232 
2233 	/*
2234 	 * Since this might be the only -deadline task on the rq,
2235 	 * this is the right place to try to pull some other one
2236 	 * from an overloaded cpu, if any.
2237 	 */
2238 	if (!task_on_rq_queued(p) || rq->dl.dl_nr_running)
2239 		return;
2240 
2241 	queue_pull_task(rq);
2242 }
2243 
2244 /*
2245  * When switching to -deadline, we may overload the rq, then
2246  * we try to push someone off, if possible.
2247  */
2248 static void switched_to_dl(struct rq *rq, struct task_struct *p)
2249 {
2250 	if (hrtimer_try_to_cancel(&p->dl.inactive_timer) == 1)
2251 		put_task_struct(p);
2252 
2253 	/* If p is not queued we will update its parameters at next wakeup. */
2254 	if (!task_on_rq_queued(p)) {
2255 		add_rq_bw(p->dl.dl_bw, &rq->dl);
2256 
2257 		return;
2258 	}
2259 	/*
2260 	 * If p is boosted we already updated its params in
2261 	 * rt_mutex_setprio()->enqueue_task(..., ENQUEUE_REPLENISH),
2262 	 * p's deadline being now already after rq_clock(rq).
2263 	 */
2264 	if (dl_time_before(p->dl.deadline, rq_clock(rq)))
2265 		setup_new_dl_entity(&p->dl);
2266 
2267 	if (rq->curr != p) {
2268 #ifdef CONFIG_SMP
2269 		if (p->nr_cpus_allowed > 1 && rq->dl.overloaded)
2270 			queue_push_tasks(rq);
2271 #endif
2272 		if (dl_task(rq->curr))
2273 			check_preempt_curr_dl(rq, p, 0);
2274 		else
2275 			resched_curr(rq);
2276 	}
2277 }
2278 
2279 /*
2280  * If the scheduling parameters of a -deadline task changed,
2281  * a push or pull operation might be needed.
2282  */
2283 static void prio_changed_dl(struct rq *rq, struct task_struct *p,
2284 			    int oldprio)
2285 {
2286 	if (task_on_rq_queued(p) || rq->curr == p) {
2287 #ifdef CONFIG_SMP
2288 		/*
2289 		 * This might be too much, but unfortunately
2290 		 * we don't have the old deadline value, and
2291 		 * we can't argue if the task is increasing
2292 		 * or lowering its prio, so...
2293 		 */
2294 		if (!rq->dl.overloaded)
2295 			queue_pull_task(rq);
2296 
2297 		/*
2298 		 * If we now have a earlier deadline task than p,
2299 		 * then reschedule, provided p is still on this
2300 		 * runqueue.
2301 		 */
2302 		if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline))
2303 			resched_curr(rq);
2304 #else
2305 		/*
2306 		 * Again, we don't know if p has a earlier
2307 		 * or later deadline, so let's blindly set a
2308 		 * (maybe not needed) rescheduling point.
2309 		 */
2310 		resched_curr(rq);
2311 #endif /* CONFIG_SMP */
2312 	}
2313 }
2314 
2315 const struct sched_class dl_sched_class = {
2316 	.next			= &rt_sched_class,
2317 	.enqueue_task		= enqueue_task_dl,
2318 	.dequeue_task		= dequeue_task_dl,
2319 	.yield_task		= yield_task_dl,
2320 
2321 	.check_preempt_curr	= check_preempt_curr_dl,
2322 
2323 	.pick_next_task		= pick_next_task_dl,
2324 	.put_prev_task		= put_prev_task_dl,
2325 
2326 #ifdef CONFIG_SMP
2327 	.select_task_rq		= select_task_rq_dl,
2328 	.migrate_task_rq	= migrate_task_rq_dl,
2329 	.set_cpus_allowed       = set_cpus_allowed_dl,
2330 	.rq_online              = rq_online_dl,
2331 	.rq_offline             = rq_offline_dl,
2332 	.task_woken		= task_woken_dl,
2333 #endif
2334 
2335 	.set_curr_task		= set_curr_task_dl,
2336 	.task_tick		= task_tick_dl,
2337 	.task_fork              = task_fork_dl,
2338 
2339 	.prio_changed           = prio_changed_dl,
2340 	.switched_from		= switched_from_dl,
2341 	.switched_to		= switched_to_dl,
2342 
2343 	.update_curr		= update_curr_dl,
2344 };
2345 
2346 int sched_dl_global_validate(void)
2347 {
2348 	u64 runtime = global_rt_runtime();
2349 	u64 period = global_rt_period();
2350 	u64 new_bw = to_ratio(period, runtime);
2351 	struct dl_bw *dl_b;
2352 	int cpu, ret = 0;
2353 	unsigned long flags;
2354 
2355 	/*
2356 	 * Here we want to check the bandwidth not being set to some
2357 	 * value smaller than the currently allocated bandwidth in
2358 	 * any of the root_domains.
2359 	 *
2360 	 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
2361 	 * cycling on root_domains... Discussion on different/better
2362 	 * solutions is welcome!
2363 	 */
2364 	for_each_possible_cpu(cpu) {
2365 		rcu_read_lock_sched();
2366 		dl_b = dl_bw_of(cpu);
2367 
2368 		raw_spin_lock_irqsave(&dl_b->lock, flags);
2369 		if (new_bw < dl_b->total_bw)
2370 			ret = -EBUSY;
2371 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2372 
2373 		rcu_read_unlock_sched();
2374 
2375 		if (ret)
2376 			break;
2377 	}
2378 
2379 	return ret;
2380 }
2381 
2382 void init_dl_rq_bw_ratio(struct dl_rq *dl_rq)
2383 {
2384 	if (global_rt_runtime() == RUNTIME_INF) {
2385 		dl_rq->bw_ratio = 1 << RATIO_SHIFT;
2386 		dl_rq->extra_bw = 1 << BW_SHIFT;
2387 	} else {
2388 		dl_rq->bw_ratio = to_ratio(global_rt_runtime(),
2389 			  global_rt_period()) >> (BW_SHIFT - RATIO_SHIFT);
2390 		dl_rq->extra_bw = to_ratio(global_rt_period(),
2391 						    global_rt_runtime());
2392 	}
2393 }
2394 
2395 void sched_dl_do_global(void)
2396 {
2397 	u64 new_bw = -1;
2398 	struct dl_bw *dl_b;
2399 	int cpu;
2400 	unsigned long flags;
2401 
2402 	def_dl_bandwidth.dl_period = global_rt_period();
2403 	def_dl_bandwidth.dl_runtime = global_rt_runtime();
2404 
2405 	if (global_rt_runtime() != RUNTIME_INF)
2406 		new_bw = to_ratio(global_rt_period(), global_rt_runtime());
2407 
2408 	/*
2409 	 * FIXME: As above...
2410 	 */
2411 	for_each_possible_cpu(cpu) {
2412 		rcu_read_lock_sched();
2413 		dl_b = dl_bw_of(cpu);
2414 
2415 		raw_spin_lock_irqsave(&dl_b->lock, flags);
2416 		dl_b->bw = new_bw;
2417 		raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2418 
2419 		rcu_read_unlock_sched();
2420 		init_dl_rq_bw_ratio(&cpu_rq(cpu)->dl);
2421 	}
2422 }
2423 
2424 /*
2425  * We must be sure that accepting a new task (or allowing changing the
2426  * parameters of an existing one) is consistent with the bandwidth
2427  * constraints. If yes, this function also accordingly updates the currently
2428  * allocated bandwidth to reflect the new situation.
2429  *
2430  * This function is called while holding p's rq->lock.
2431  */
2432 int sched_dl_overflow(struct task_struct *p, int policy,
2433 		      const struct sched_attr *attr)
2434 {
2435 	struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2436 	u64 period = attr->sched_period ?: attr->sched_deadline;
2437 	u64 runtime = attr->sched_runtime;
2438 	u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2439 	int cpus, err = -1;
2440 
2441 	/* !deadline task may carry old deadline bandwidth */
2442 	if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2443 		return 0;
2444 
2445 	/*
2446 	 * Either if a task, enters, leave, or stays -deadline but changes
2447 	 * its parameters, we may need to update accordingly the total
2448 	 * allocated bandwidth of the container.
2449 	 */
2450 	raw_spin_lock(&dl_b->lock);
2451 	cpus = dl_bw_cpus(task_cpu(p));
2452 	if (dl_policy(policy) && !task_has_dl_policy(p) &&
2453 	    !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2454 		if (hrtimer_active(&p->dl.inactive_timer))
2455 			__dl_clear(dl_b, p->dl.dl_bw, cpus);
2456 		__dl_add(dl_b, new_bw, cpus);
2457 		err = 0;
2458 	} else if (dl_policy(policy) && task_has_dl_policy(p) &&
2459 		   !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2460 		/*
2461 		 * XXX this is slightly incorrect: when the task
2462 		 * utilization decreases, we should delay the total
2463 		 * utilization change until the task's 0-lag point.
2464 		 * But this would require to set the task's "inactive
2465 		 * timer" when the task is not inactive.
2466 		 */
2467 		__dl_clear(dl_b, p->dl.dl_bw, cpus);
2468 		__dl_add(dl_b, new_bw, cpus);
2469 		dl_change_utilization(p, new_bw);
2470 		err = 0;
2471 	} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2472 		/*
2473 		 * Do not decrease the total deadline utilization here,
2474 		 * switched_from_dl() will take care to do it at the correct
2475 		 * (0-lag) time.
2476 		 */
2477 		err = 0;
2478 	}
2479 	raw_spin_unlock(&dl_b->lock);
2480 
2481 	return err;
2482 }
2483 
2484 /*
2485  * This function initializes the sched_dl_entity of a newly becoming
2486  * SCHED_DEADLINE task.
2487  *
2488  * Only the static values are considered here, the actual runtime and the
2489  * absolute deadline will be properly calculated when the task is enqueued
2490  * for the first time with its new policy.
2491  */
2492 void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
2493 {
2494 	struct sched_dl_entity *dl_se = &p->dl;
2495 
2496 	dl_se->dl_runtime = attr->sched_runtime;
2497 	dl_se->dl_deadline = attr->sched_deadline;
2498 	dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
2499 	dl_se->flags = attr->sched_flags;
2500 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
2501 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
2502 }
2503 
2504 void __getparam_dl(struct task_struct *p, struct sched_attr *attr)
2505 {
2506 	struct sched_dl_entity *dl_se = &p->dl;
2507 
2508 	attr->sched_priority = p->rt_priority;
2509 	attr->sched_runtime = dl_se->dl_runtime;
2510 	attr->sched_deadline = dl_se->dl_deadline;
2511 	attr->sched_period = dl_se->dl_period;
2512 	attr->sched_flags = dl_se->flags;
2513 }
2514 
2515 /*
2516  * This function validates the new parameters of a -deadline task.
2517  * We ask for the deadline not being zero, and greater or equal
2518  * than the runtime, as well as the period of being zero or
2519  * greater than deadline. Furthermore, we have to be sure that
2520  * user parameters are above the internal resolution of 1us (we
2521  * check sched_runtime only since it is always the smaller one) and
2522  * below 2^63 ns (we have to check both sched_deadline and
2523  * sched_period, as the latter can be zero).
2524  */
2525 bool __checkparam_dl(const struct sched_attr *attr)
2526 {
2527 	/* deadline != 0 */
2528 	if (attr->sched_deadline == 0)
2529 		return false;
2530 
2531 	/*
2532 	 * Since we truncate DL_SCALE bits, make sure we're at least
2533 	 * that big.
2534 	 */
2535 	if (attr->sched_runtime < (1ULL << DL_SCALE))
2536 		return false;
2537 
2538 	/*
2539 	 * Since we use the MSB for wrap-around and sign issues, make
2540 	 * sure it's not set (mind that period can be equal to zero).
2541 	 */
2542 	if (attr->sched_deadline & (1ULL << 63) ||
2543 	    attr->sched_period & (1ULL << 63))
2544 		return false;
2545 
2546 	/* runtime <= deadline <= period (if period != 0) */
2547 	if ((attr->sched_period != 0 &&
2548 	     attr->sched_period < attr->sched_deadline) ||
2549 	    attr->sched_deadline < attr->sched_runtime)
2550 		return false;
2551 
2552 	return true;
2553 }
2554 
2555 /*
2556  * This function clears the sched_dl_entity static params.
2557  */
2558 void __dl_clear_params(struct task_struct *p)
2559 {
2560 	struct sched_dl_entity *dl_se = &p->dl;
2561 
2562 	dl_se->dl_runtime = 0;
2563 	dl_se->dl_deadline = 0;
2564 	dl_se->dl_period = 0;
2565 	dl_se->flags = 0;
2566 	dl_se->dl_bw = 0;
2567 	dl_se->dl_density = 0;
2568 
2569 	dl_se->dl_throttled = 0;
2570 	dl_se->dl_yielded = 0;
2571 	dl_se->dl_non_contending = 0;
2572 }
2573 
2574 bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
2575 {
2576 	struct sched_dl_entity *dl_se = &p->dl;
2577 
2578 	if (dl_se->dl_runtime != attr->sched_runtime ||
2579 	    dl_se->dl_deadline != attr->sched_deadline ||
2580 	    dl_se->dl_period != attr->sched_period ||
2581 	    dl_se->flags != attr->sched_flags)
2582 		return true;
2583 
2584 	return false;
2585 }
2586 
2587 #ifdef CONFIG_SMP
2588 int dl_task_can_attach(struct task_struct *p, const struct cpumask *cs_cpus_allowed)
2589 {
2590 	unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
2591 							cs_cpus_allowed);
2592 	struct dl_bw *dl_b;
2593 	bool overflow;
2594 	int cpus, ret;
2595 	unsigned long flags;
2596 
2597 	rcu_read_lock_sched();
2598 	dl_b = dl_bw_of(dest_cpu);
2599 	raw_spin_lock_irqsave(&dl_b->lock, flags);
2600 	cpus = dl_bw_cpus(dest_cpu);
2601 	overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
2602 	if (overflow)
2603 		ret = -EBUSY;
2604 	else {
2605 		/*
2606 		 * We reserve space for this task in the destination
2607 		 * root_domain, as we can't fail after this point.
2608 		 * We will free resources in the source root_domain
2609 		 * later on (see set_cpus_allowed_dl()).
2610 		 */
2611 		__dl_add(dl_b, p->dl.dl_bw, cpus);
2612 		ret = 0;
2613 	}
2614 	raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2615 	rcu_read_unlock_sched();
2616 	return ret;
2617 }
2618 
2619 int dl_cpuset_cpumask_can_shrink(const struct cpumask *cur,
2620 				 const struct cpumask *trial)
2621 {
2622 	int ret = 1, trial_cpus;
2623 	struct dl_bw *cur_dl_b;
2624 	unsigned long flags;
2625 
2626 	rcu_read_lock_sched();
2627 	cur_dl_b = dl_bw_of(cpumask_any(cur));
2628 	trial_cpus = cpumask_weight(trial);
2629 
2630 	raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
2631 	if (cur_dl_b->bw != -1 &&
2632 	    cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
2633 		ret = 0;
2634 	raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
2635 	rcu_read_unlock_sched();
2636 	return ret;
2637 }
2638 
2639 bool dl_cpu_busy(unsigned int cpu)
2640 {
2641 	unsigned long flags;
2642 	struct dl_bw *dl_b;
2643 	bool overflow;
2644 	int cpus;
2645 
2646 	rcu_read_lock_sched();
2647 	dl_b = dl_bw_of(cpu);
2648 	raw_spin_lock_irqsave(&dl_b->lock, flags);
2649 	cpus = dl_bw_cpus(cpu);
2650 	overflow = __dl_overflow(dl_b, cpus, 0, 0);
2651 	raw_spin_unlock_irqrestore(&dl_b->lock, flags);
2652 	rcu_read_unlock_sched();
2653 	return overflow;
2654 }
2655 #endif
2656 
2657 #ifdef CONFIG_SCHED_DEBUG
2658 extern void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq);
2659 
2660 void print_dl_stats(struct seq_file *m, int cpu)
2661 {
2662 	print_dl_rq(m, cpu, &cpu_rq(cpu)->dl);
2663 }
2664 #endif /* CONFIG_SCHED_DEBUG */
2665