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