Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / kernel / sched / deadline.c
1 /*
2  * Deadline Scheduling Class (SCHED_DEADLINE)
3  *
4  * Earliest Deadline First (EDF) + Constant Bandwidth Server (CBS).
5  *
6  * Tasks that periodically executes their instances for less than their
7  * runtime won't miss any of their deadlines.
8  * Tasks that are not periodic or sporadic or that tries to execute more
9  * than their reserved bandwidth will be slowed down (and may potentially
10  * miss some of their deadlines), and won't affect any other task.
11  *
12  * Copyright (C) 2012 Dario Faggioli <raistlin@linux.it>,
13  *                    Juri Lelli <juri.lelli@gmail.com>,
14  *                    Michael Trimarchi <michael@amarulasolutions.com>,
15  *                    Fabio Checconi <fchecconi@gmail.com>
16  */
17 #include "sched.h"
18
19 #include <linux/slab.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 static inline int is_leftmost(struct task_struct *p, struct dl_rq *dl_rq)
47 {
48         struct sched_dl_entity *dl_se = &p->dl;
49
50         return dl_rq->rb_leftmost == &dl_se->rb_node;
51 }
52
53 void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime)
54 {
55         raw_spin_lock_init(&dl_b->dl_runtime_lock);
56         dl_b->dl_period = period;
57         dl_b->dl_runtime = runtime;
58 }
59
60 void init_dl_bw(struct dl_bw *dl_b)
61 {
62         raw_spin_lock_init(&dl_b->lock);
63         raw_spin_lock(&def_dl_bandwidth.dl_runtime_lock);
64         if (global_rt_runtime() == RUNTIME_INF)
65                 dl_b->bw = -1;
66         else
67                 dl_b->bw = to_ratio(global_rt_period(), global_rt_runtime());
68         raw_spin_unlock(&def_dl_bandwidth.dl_runtime_lock);
69         dl_b->total_bw = 0;
70 }
71
72 void init_dl_rq(struct dl_rq *dl_rq)
73 {
74         dl_rq->rb_root = RB_ROOT;
75
76 #ifdef CONFIG_SMP
77         /* zero means no -deadline tasks */
78         dl_rq->earliest_dl.curr = dl_rq->earliest_dl.next = 0;
79
80         dl_rq->dl_nr_migratory = 0;
81         dl_rq->overloaded = 0;
82         dl_rq->pushable_dl_tasks_root = RB_ROOT;
83 #else
84         init_dl_bw(&dl_rq->dl_bw);
85 #endif
86 }
87
88 #ifdef CONFIG_SMP
89
90 static inline int dl_overloaded(struct rq *rq)
91 {
92         return atomic_read(&rq->rd->dlo_count);
93 }
94
95 static inline void dl_set_overload(struct rq *rq)
96 {
97         if (!rq->online)
98                 return;
99
100         cpumask_set_cpu(rq->cpu, rq->rd->dlo_mask);
101         /*
102          * Must be visible before the overload count is
103          * set (as in sched_rt.c).
104          *
105          * Matched by the barrier in pull_dl_task().
106          */
107         smp_wmb();
108         atomic_inc(&rq->rd->dlo_count);
109 }
110
111 static inline void dl_clear_overload(struct rq *rq)
112 {
113         if (!rq->online)
114                 return;
115
116         atomic_dec(&rq->rd->dlo_count);
117         cpumask_clear_cpu(rq->cpu, rq->rd->dlo_mask);
118 }
119
120 static void update_dl_migration(struct dl_rq *dl_rq)
121 {
122         if (dl_rq->dl_nr_migratory && dl_rq->dl_nr_running > 1) {
123                 if (!dl_rq->overloaded) {
124                         dl_set_overload(rq_of_dl_rq(dl_rq));
125                         dl_rq->overloaded = 1;
126                 }
127         } else if (dl_rq->overloaded) {
128                 dl_clear_overload(rq_of_dl_rq(dl_rq));
129                 dl_rq->overloaded = 0;
130         }
131 }
132
133 static void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
134 {
135         struct task_struct *p = dl_task_of(dl_se);
136
137         if (p->nr_cpus_allowed > 1)
138                 dl_rq->dl_nr_migratory++;
139
140         update_dl_migration(dl_rq);
141 }
142
143 static void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
144 {
145         struct task_struct *p = dl_task_of(dl_se);
146
147         if (p->nr_cpus_allowed > 1)
148                 dl_rq->dl_nr_migratory--;
149
150         update_dl_migration(dl_rq);
151 }
152
153 /*
154  * The list of pushable -deadline task is not a plist, like in
155  * sched_rt.c, it is an rb-tree with tasks ordered by deadline.
156  */
157 static void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
158 {
159         struct dl_rq *dl_rq = &rq->dl;
160         struct rb_node **link = &dl_rq->pushable_dl_tasks_root.rb_node;
161         struct rb_node *parent = NULL;
162         struct task_struct *entry;
163         int leftmost = 1;
164
165         BUG_ON(!RB_EMPTY_NODE(&p->pushable_dl_tasks));
166
167         while (*link) {
168                 parent = *link;
169                 entry = rb_entry(parent, struct task_struct,
170                                  pushable_dl_tasks);
171                 if (dl_entity_preempt(&p->dl, &entry->dl))
172                         link = &parent->rb_left;
173                 else {
174                         link = &parent->rb_right;
175                         leftmost = 0;
176                 }
177         }
178
179         if (leftmost)
180                 dl_rq->pushable_dl_tasks_leftmost = &p->pushable_dl_tasks;
181
182         rb_link_node(&p->pushable_dl_tasks, parent, link);
183         rb_insert_color(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root);
184 }
185
186 static void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
187 {
188         struct dl_rq *dl_rq = &rq->dl;
189
190         if (RB_EMPTY_NODE(&p->pushable_dl_tasks))
191                 return;
192
193         if (dl_rq->pushable_dl_tasks_leftmost == &p->pushable_dl_tasks) {
194                 struct rb_node *next_node;
195
196                 next_node = rb_next(&p->pushable_dl_tasks);
197                 dl_rq->pushable_dl_tasks_leftmost = next_node;
198         }
199
200         rb_erase(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root);
201         RB_CLEAR_NODE(&p->pushable_dl_tasks);
202 }
203
204 static inline int has_pushable_dl_tasks(struct rq *rq)
205 {
206         return !RB_EMPTY_ROOT(&rq->dl.pushable_dl_tasks_root);
207 }
208
209 static int push_dl_task(struct rq *rq);
210
211 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
212 {
213         return dl_task(prev);
214 }
215
216 static inline void set_post_schedule(struct rq *rq)
217 {
218         rq->post_schedule = has_pushable_dl_tasks(rq);
219 }
220
221 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq);
222
223 static void dl_task_offline_migration(struct rq *rq, struct task_struct *p)
224 {
225         struct rq *later_rq = NULL;
226         bool fallback = false;
227
228         later_rq = find_lock_later_rq(p, rq);
229
230         if (!later_rq) {
231                 int cpu;
232
233                 /*
234                  * If we cannot preempt any rq, fall back to pick any
235                  * online cpu.
236                  */
237                 fallback = true;
238                 cpu = cpumask_any_and(cpu_active_mask, tsk_cpus_allowed(p));
239                 if (cpu >= nr_cpu_ids) {
240                         /*
241                          * Fail to find any suitable cpu.
242                          * The task will never come back!
243                          */
244                         BUG_ON(dl_bandwidth_enabled());
245
246                         /*
247                          * If admission control is disabled we
248                          * try a little harder to let the task
249                          * run.
250                          */
251                         cpu = cpumask_any(cpu_active_mask);
252                 }
253                 later_rq = cpu_rq(cpu);
254                 double_lock_balance(rq, later_rq);
255         }
256
257         deactivate_task(rq, p, 0);
258         set_task_cpu(p, later_rq->cpu);
259         activate_task(later_rq, p, ENQUEUE_REPLENISH);
260
261         if (!fallback)
262                 resched_curr(later_rq);
263
264         double_unlock_balance(rq, later_rq);
265 }
266
267 #else
268
269 static inline
270 void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
271 {
272 }
273
274 static inline
275 void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
276 {
277 }
278
279 static inline
280 void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
281 {
282 }
283
284 static inline
285 void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
286 {
287 }
288
289 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
290 {
291         return false;
292 }
293
294 static inline int pull_dl_task(struct rq *rq)
295 {
296         return 0;
297 }
298
299 static inline void set_post_schedule(struct rq *rq)
300 {
301 }
302 #endif /* CONFIG_SMP */
303
304 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags);
305 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags);
306 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
307                                   int flags);
308
309 /*
310  * We are being explicitly informed that a new instance is starting,
311  * and this means that:
312  *  - the absolute deadline of the entity has to be placed at
313  *    current time + relative deadline;
314  *  - the runtime of the entity has to be set to the maximum value.
315  *
316  * The capability of specifying such event is useful whenever a -deadline
317  * entity wants to (try to!) synchronize its behaviour with the scheduler's
318  * one, and to (try to!) reconcile itself with its own scheduling
319  * parameters.
320  */
321 static inline void setup_new_dl_entity(struct sched_dl_entity *dl_se,
322                                        struct sched_dl_entity *pi_se)
323 {
324         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
325         struct rq *rq = rq_of_dl_rq(dl_rq);
326
327         WARN_ON(!dl_se->dl_new || dl_se->dl_throttled);
328
329         /*
330          * We use the regular wall clock time to set deadlines in the
331          * future; in fact, we must consider execution overheads (time
332          * spent on hardirq context, etc.).
333          */
334         dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
335         dl_se->runtime = pi_se->dl_runtime;
336         dl_se->dl_new = 0;
337 }
338
339 /*
340  * Pure Earliest Deadline First (EDF) scheduling does not deal with the
341  * possibility of a entity lasting more than what it declared, and thus
342  * exhausting its runtime.
343  *
344  * Here we are interested in making runtime overrun possible, but we do
345  * not want a entity which is misbehaving to affect the scheduling of all
346  * other entities.
347  * Therefore, a budgeting strategy called Constant Bandwidth Server (CBS)
348  * is used, in order to confine each entity within its own bandwidth.
349  *
350  * This function deals exactly with that, and ensures that when the runtime
351  * of a entity is replenished, its deadline is also postponed. That ensures
352  * the overrunning entity can't interfere with other entity in the system and
353  * can't make them miss their deadlines. Reasons why this kind of overruns
354  * could happen are, typically, a entity voluntarily trying to overcome its
355  * runtime, or it just underestimated it during sched_setattr().
356  */
357 static void replenish_dl_entity(struct sched_dl_entity *dl_se,
358                                 struct sched_dl_entity *pi_se)
359 {
360         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
361         struct rq *rq = rq_of_dl_rq(dl_rq);
362
363         BUG_ON(pi_se->dl_runtime <= 0);
364
365         /*
366          * This could be the case for a !-dl task that is boosted.
367          * Just go with full inherited parameters.
368          */
369         if (dl_se->dl_deadline == 0) {
370                 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
371                 dl_se->runtime = pi_se->dl_runtime;
372         }
373
374         /*
375          * We keep moving the deadline away until we get some
376          * available runtime for the entity. This ensures correct
377          * handling of situations where the runtime overrun is
378          * arbitrary large.
379          */
380         while (dl_se->runtime <= 0) {
381                 dl_se->deadline += pi_se->dl_period;
382                 dl_se->runtime += pi_se->dl_runtime;
383         }
384
385         /*
386          * At this point, the deadline really should be "in
387          * the future" with respect to rq->clock. If it's
388          * not, we are, for some reason, lagging too much!
389          * Anyway, after having warn userspace abut that,
390          * we still try to keep the things running by
391          * resetting the deadline and the budget of the
392          * entity.
393          */
394         if (dl_time_before(dl_se->deadline, rq_clock(rq))) {
395                 printk_deferred_once("sched: DL replenish lagged to much\n");
396                 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
397                 dl_se->runtime = pi_se->dl_runtime;
398         }
399
400         if (dl_se->dl_yielded)
401                 dl_se->dl_yielded = 0;
402         if (dl_se->dl_throttled)
403                 dl_se->dl_throttled = 0;
404 }
405
406 /*
407  * Here we check if --at time t-- an entity (which is probably being
408  * [re]activated or, in general, enqueued) can use its remaining runtime
409  * and its current deadline _without_ exceeding the bandwidth it is
410  * assigned (function returns true if it can't). We are in fact applying
411  * one of the CBS rules: when a task wakes up, if the residual runtime
412  * over residual deadline fits within the allocated bandwidth, then we
413  * can keep the current (absolute) deadline and residual budget without
414  * disrupting the schedulability of the system. Otherwise, we should
415  * refill the runtime and set the deadline a period in the future,
416  * because keeping the current (absolute) deadline of the task would
417  * result in breaking guarantees promised to other tasks (refer to
418  * Documentation/scheduler/sched-deadline.txt for more informations).
419  *
420  * This function returns true if:
421  *
422  *   runtime / (deadline - t) > dl_runtime / dl_period ,
423  *
424  * IOW we can't recycle current parameters.
425  *
426  * Notice that the bandwidth check is done against the period. For
427  * task with deadline equal to period this is the same of using
428  * dl_deadline instead of dl_period in the equation above.
429  */
430 static bool dl_entity_overflow(struct sched_dl_entity *dl_se,
431                                struct sched_dl_entity *pi_se, u64 t)
432 {
433         u64 left, right;
434
435         /*
436          * left and right are the two sides of the equation above,
437          * after a bit of shuffling to use multiplications instead
438          * of divisions.
439          *
440          * Note that none of the time values involved in the two
441          * multiplications are absolute: dl_deadline and dl_runtime
442          * are the relative deadline and the maximum runtime of each
443          * instance, runtime is the runtime left for the last instance
444          * and (deadline - t), since t is rq->clock, is the time left
445          * to the (absolute) deadline. Even if overflowing the u64 type
446          * is very unlikely to occur in both cases, here we scale down
447          * as we want to avoid that risk at all. Scaling down by 10
448          * means that we reduce granularity to 1us. We are fine with it,
449          * since this is only a true/false check and, anyway, thinking
450          * of anything below microseconds resolution is actually fiction
451          * (but still we want to give the user that illusion >;).
452          */
453         left = (pi_se->dl_period >> DL_SCALE) * (dl_se->runtime >> DL_SCALE);
454         right = ((dl_se->deadline - t) >> DL_SCALE) *
455                 (pi_se->dl_runtime >> DL_SCALE);
456
457         return dl_time_before(right, left);
458 }
459
460 /*
461  * When a -deadline entity is queued back on the runqueue, its runtime and
462  * deadline might need updating.
463  *
464  * The policy here is that we update the deadline of the entity only if:
465  *  - the current deadline is in the past,
466  *  - using the remaining runtime with the current deadline would make
467  *    the entity exceed its bandwidth.
468  */
469 static void update_dl_entity(struct sched_dl_entity *dl_se,
470                              struct sched_dl_entity *pi_se)
471 {
472         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
473         struct rq *rq = rq_of_dl_rq(dl_rq);
474
475         /*
476          * The arrival of a new instance needs special treatment, i.e.,
477          * the actual scheduling parameters have to be "renewed".
478          */
479         if (dl_se->dl_new) {
480                 setup_new_dl_entity(dl_se, pi_se);
481                 return;
482         }
483
484         if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
485             dl_entity_overflow(dl_se, pi_se, rq_clock(rq))) {
486                 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
487                 dl_se->runtime = pi_se->dl_runtime;
488         }
489 }
490
491 /*
492  * If the entity depleted all its runtime, and if we want it to sleep
493  * while waiting for some new execution time to become available, we
494  * set the bandwidth enforcement timer to the replenishment instant
495  * and try to activate it.
496  *
497  * Notice that it is important for the caller to know if the timer
498  * actually started or not (i.e., the replenishment instant is in
499  * the future or in the past).
500  */
501 static int start_dl_timer(struct sched_dl_entity *dl_se, bool boosted)
502 {
503         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
504         struct rq *rq = rq_of_dl_rq(dl_rq);
505         ktime_t now, act;
506         ktime_t soft, hard;
507         unsigned long range;
508         s64 delta;
509
510         if (boosted)
511                 return 0;
512         /*
513          * We want the timer to fire at the deadline, but considering
514          * that it is actually coming from rq->clock and not from
515          * hrtimer's time base reading.
516          */
517         act = ns_to_ktime(dl_se->deadline);
518         now = hrtimer_cb_get_time(&dl_se->dl_timer);
519         delta = ktime_to_ns(now) - rq_clock(rq);
520         act = ktime_add_ns(act, delta);
521
522         /*
523          * If the expiry time already passed, e.g., because the value
524          * chosen as the deadline is too small, don't even try to
525          * start the timer in the past!
526          */
527         if (ktime_us_delta(act, now) < 0)
528                 return 0;
529
530         hrtimer_set_expires(&dl_se->dl_timer, act);
531
532         soft = hrtimer_get_softexpires(&dl_se->dl_timer);
533         hard = hrtimer_get_expires(&dl_se->dl_timer);
534         range = ktime_to_ns(ktime_sub(hard, soft));
535         __hrtimer_start_range_ns(&dl_se->dl_timer, soft,
536                                  range, HRTIMER_MODE_ABS, 0);
537
538         return hrtimer_active(&dl_se->dl_timer);
539 }
540
541 /*
542  * This is the bandwidth enforcement timer callback. If here, we know
543  * a task is not on its dl_rq, since the fact that the timer was running
544  * means the task is throttled and needs a runtime replenishment.
545  *
546  * However, what we actually do depends on the fact the task is active,
547  * (it is on its rq) or has been removed from there by a call to
548  * dequeue_task_dl(). In the former case we must issue the runtime
549  * replenishment and add the task back to the dl_rq; in the latter, we just
550  * do nothing but clearing dl_throttled, so that runtime and deadline
551  * updating (and the queueing back to dl_rq) will be done by the
552  * next call to enqueue_task_dl().
553  */
554 static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
555 {
556         struct sched_dl_entity *dl_se = container_of(timer,
557                                                      struct sched_dl_entity,
558                                                      dl_timer);
559         struct task_struct *p = dl_task_of(dl_se);
560         unsigned long flags;
561         struct rq *rq;
562
563         rq = task_rq_lock(p, &flags);
564
565         /*
566          * We need to take care of several possible races here:
567          *
568          *   - the task might have changed its scheduling policy
569          *     to something different than SCHED_DEADLINE
570          *   - the task might have changed its reservation parameters
571          *     (through sched_setattr())
572          *   - the task might have been boosted by someone else and
573          *     might be in the boosting/deboosting path
574          *
575          * In all this cases we bail out, as the task is already
576          * in the runqueue or is going to be enqueued back anyway.
577          */
578         if (!dl_task(p) || dl_se->dl_new ||
579             dl_se->dl_boosted || !dl_se->dl_throttled)
580                 goto unlock;
581
582         sched_clock_tick();
583         update_rq_clock(rq);
584
585 #ifdef CONFIG_SMP
586         /*
587          * If we find that the rq the task was on is no longer
588          * available, we need to select a new rq.
589          */
590         if (unlikely(!rq->online)) {
591                 dl_task_offline_migration(rq, p);
592                 goto unlock;
593         }
594 #endif
595
596         /*
597          * If the throttle happened during sched-out; like:
598          *
599          *   schedule()
600          *     deactivate_task()
601          *       dequeue_task_dl()
602          *         update_curr_dl()
603          *           start_dl_timer()
604          *         __dequeue_task_dl()
605          *     prev->on_rq = 0;
606          *
607          * We can be both throttled and !queued. Replenish the counter
608          * but do not enqueue -- wait for our wakeup to do that.
609          */
610         if (!task_on_rq_queued(p)) {
611                 replenish_dl_entity(dl_se, dl_se);
612                 goto unlock;
613         }
614
615         enqueue_task_dl(rq, p, ENQUEUE_REPLENISH);
616         if (dl_task(rq->curr))
617                 check_preempt_curr_dl(rq, p, 0);
618         else
619                 resched_curr(rq);
620 #ifdef CONFIG_SMP
621         /*
622          * Queueing this task back might have overloaded rq,
623          * check if we need to kick someone away.
624          */
625         if (has_pushable_dl_tasks(rq))
626                 push_dl_task(rq);
627 #endif
628 unlock:
629         task_rq_unlock(rq, p, &flags);
630
631         return HRTIMER_NORESTART;
632 }
633
634 void init_dl_task_timer(struct sched_dl_entity *dl_se)
635 {
636         struct hrtimer *timer = &dl_se->dl_timer;
637
638         hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
639         timer->function = dl_task_timer;
640         timer->irqsafe = 1;
641 }
642
643 static
644 int dl_runtime_exceeded(struct rq *rq, struct sched_dl_entity *dl_se)
645 {
646         return (dl_se->runtime <= 0);
647 }
648
649 extern bool sched_rt_bandwidth_account(struct rt_rq *rt_rq);
650
651 /*
652  * Update the current task's runtime statistics (provided it is still
653  * a -deadline task and has not been removed from the dl_rq).
654  */
655 static void update_curr_dl(struct rq *rq)
656 {
657         struct task_struct *curr = rq->curr;
658         struct sched_dl_entity *dl_se = &curr->dl;
659         u64 delta_exec;
660
661         if (!dl_task(curr) || !on_dl_rq(dl_se))
662                 return;
663
664         /*
665          * Consumed budget is computed considering the time as
666          * observed by schedulable tasks (excluding time spent
667          * in hardirq context, etc.). Deadlines are instead
668          * computed using hard walltime. This seems to be the more
669          * natural solution, but the full ramifications of this
670          * approach need further study.
671          */
672         delta_exec = rq_clock_task(rq) - curr->se.exec_start;
673         if (unlikely((s64)delta_exec <= 0))
674                 return;
675
676         schedstat_set(curr->se.statistics.exec_max,
677                       max(curr->se.statistics.exec_max, delta_exec));
678
679         curr->se.sum_exec_runtime += delta_exec;
680         account_group_exec_runtime(curr, delta_exec);
681
682         curr->se.exec_start = rq_clock_task(rq);
683         cpuacct_charge(curr, delta_exec);
684
685         sched_rt_avg_update(rq, delta_exec);
686
687         dl_se->runtime -= dl_se->dl_yielded ? 0 : delta_exec;
688         if (dl_runtime_exceeded(rq, dl_se)) {
689                 dl_se->dl_throttled = 1;
690                 __dequeue_task_dl(rq, curr, 0);
691                 if (unlikely(!start_dl_timer(dl_se, curr->dl.dl_boosted)))
692                         enqueue_task_dl(rq, curr, ENQUEUE_REPLENISH);
693
694                 if (!is_leftmost(curr, &rq->dl))
695                         resched_curr(rq);
696         }
697
698         /*
699          * Because -- for now -- we share the rt bandwidth, we need to
700          * account our runtime there too, otherwise actual rt tasks
701          * would be able to exceed the shared quota.
702          *
703          * Account to the root rt group for now.
704          *
705          * The solution we're working towards is having the RT groups scheduled
706          * using deadline servers -- however there's a few nasties to figure
707          * out before that can happen.
708          */
709         if (rt_bandwidth_enabled()) {
710                 struct rt_rq *rt_rq = &rq->rt;
711
712                 raw_spin_lock(&rt_rq->rt_runtime_lock);
713                 /*
714                  * We'll let actual RT tasks worry about the overflow here, we
715                  * have our own CBS to keep us inline; only account when RT
716                  * bandwidth is relevant.
717                  */
718                 if (sched_rt_bandwidth_account(rt_rq))
719                         rt_rq->rt_time += delta_exec;
720                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
721         }
722 }
723
724 #ifdef CONFIG_SMP
725
726 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu);
727
728 static inline u64 next_deadline(struct rq *rq)
729 {
730         struct task_struct *next = pick_next_earliest_dl_task(rq, rq->cpu);
731
732         if (next && dl_prio(next->prio))
733                 return next->dl.deadline;
734         else
735                 return 0;
736 }
737
738 static void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
739 {
740         struct rq *rq = rq_of_dl_rq(dl_rq);
741
742         if (dl_rq->earliest_dl.curr == 0 ||
743             dl_time_before(deadline, dl_rq->earliest_dl.curr)) {
744                 /*
745                  * If the dl_rq had no -deadline tasks, or if the new task
746                  * has shorter deadline than the current one on dl_rq, we
747                  * know that the previous earliest becomes our next earliest,
748                  * as the new task becomes the earliest itself.
749                  */
750                 dl_rq->earliest_dl.next = dl_rq->earliest_dl.curr;
751                 dl_rq->earliest_dl.curr = deadline;
752                 cpudl_set(&rq->rd->cpudl, rq->cpu, deadline, 1);
753         } else if (dl_rq->earliest_dl.next == 0 ||
754                    dl_time_before(deadline, dl_rq->earliest_dl.next)) {
755                 /*
756                  * On the other hand, if the new -deadline task has a
757                  * a later deadline than the earliest one on dl_rq, but
758                  * it is earlier than the next (if any), we must
759                  * recompute the next-earliest.
760                  */
761                 dl_rq->earliest_dl.next = next_deadline(rq);
762         }
763 }
764
765 static void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
766 {
767         struct rq *rq = rq_of_dl_rq(dl_rq);
768
769         /*
770          * Since we may have removed our earliest (and/or next earliest)
771          * task we must recompute them.
772          */
773         if (!dl_rq->dl_nr_running) {
774                 dl_rq->earliest_dl.curr = 0;
775                 dl_rq->earliest_dl.next = 0;
776                 cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0);
777         } else {
778                 struct rb_node *leftmost = dl_rq->rb_leftmost;
779                 struct sched_dl_entity *entry;
780
781                 entry = rb_entry(leftmost, struct sched_dl_entity, rb_node);
782                 dl_rq->earliest_dl.curr = entry->deadline;
783                 dl_rq->earliest_dl.next = next_deadline(rq);
784                 cpudl_set(&rq->rd->cpudl, rq->cpu, entry->deadline, 1);
785         }
786 }
787
788 #else
789
790 static inline void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
791 static inline void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
792
793 #endif /* CONFIG_SMP */
794
795 static inline
796 void inc_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
797 {
798         int prio = dl_task_of(dl_se)->prio;
799         u64 deadline = dl_se->deadline;
800
801         WARN_ON(!dl_prio(prio));
802         dl_rq->dl_nr_running++;
803         add_nr_running(rq_of_dl_rq(dl_rq), 1);
804
805         inc_dl_deadline(dl_rq, deadline);
806         inc_dl_migration(dl_se, dl_rq);
807 }
808
809 static inline
810 void dec_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
811 {
812         int prio = dl_task_of(dl_se)->prio;
813
814         WARN_ON(!dl_prio(prio));
815         WARN_ON(!dl_rq->dl_nr_running);
816         dl_rq->dl_nr_running--;
817         sub_nr_running(rq_of_dl_rq(dl_rq), 1);
818
819         dec_dl_deadline(dl_rq, dl_se->deadline);
820         dec_dl_migration(dl_se, dl_rq);
821 }
822
823 static void __enqueue_dl_entity(struct sched_dl_entity *dl_se)
824 {
825         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
826         struct rb_node **link = &dl_rq->rb_root.rb_node;
827         struct rb_node *parent = NULL;
828         struct sched_dl_entity *entry;
829         int leftmost = 1;
830
831         BUG_ON(!RB_EMPTY_NODE(&dl_se->rb_node));
832
833         while (*link) {
834                 parent = *link;
835                 entry = rb_entry(parent, struct sched_dl_entity, rb_node);
836                 if (dl_time_before(dl_se->deadline, entry->deadline))
837                         link = &parent->rb_left;
838                 else {
839                         link = &parent->rb_right;
840                         leftmost = 0;
841                 }
842         }
843
844         if (leftmost)
845                 dl_rq->rb_leftmost = &dl_se->rb_node;
846
847         rb_link_node(&dl_se->rb_node, parent, link);
848         rb_insert_color(&dl_se->rb_node, &dl_rq->rb_root);
849
850         inc_dl_tasks(dl_se, dl_rq);
851 }
852
853 static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
854 {
855         struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
856
857         if (RB_EMPTY_NODE(&dl_se->rb_node))
858                 return;
859
860         if (dl_rq->rb_leftmost == &dl_se->rb_node) {
861                 struct rb_node *next_node;
862
863                 next_node = rb_next(&dl_se->rb_node);
864                 dl_rq->rb_leftmost = next_node;
865         }
866
867         rb_erase(&dl_se->rb_node, &dl_rq->rb_root);
868         RB_CLEAR_NODE(&dl_se->rb_node);
869
870         dec_dl_tasks(dl_se, dl_rq);
871 }
872
873 static void
874 enqueue_dl_entity(struct sched_dl_entity *dl_se,
875                   struct sched_dl_entity *pi_se, int flags)
876 {
877         BUG_ON(on_dl_rq(dl_se));
878
879         /*
880          * If this is a wakeup or a new instance, the scheduling
881          * parameters of the task might need updating. Otherwise,
882          * we want a replenishment of its runtime.
883          */
884         if (dl_se->dl_new || flags & ENQUEUE_WAKEUP)
885                 update_dl_entity(dl_se, pi_se);
886         else if (flags & ENQUEUE_REPLENISH)
887                 replenish_dl_entity(dl_se, pi_se);
888
889         __enqueue_dl_entity(dl_se);
890 }
891
892 static void dequeue_dl_entity(struct sched_dl_entity *dl_se)
893 {
894         __dequeue_dl_entity(dl_se);
895 }
896
897 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags)
898 {
899         struct task_struct *pi_task = rt_mutex_get_top_task(p);
900         struct sched_dl_entity *pi_se = &p->dl;
901
902         /*
903          * Use the scheduling parameters of the top pi-waiter
904          * task if we have one and its (relative) deadline is
905          * smaller than our one... OTW we keep our runtime and
906          * deadline.
907          */
908         if (pi_task && p->dl.dl_boosted && dl_prio(pi_task->normal_prio)) {
909                 pi_se = &pi_task->dl;
910         } else if (!dl_prio(p->normal_prio)) {
911                 /*
912                  * Special case in which we have a !SCHED_DEADLINE task
913                  * that is going to be deboosted, but exceedes its
914                  * runtime while doing so. No point in replenishing
915                  * it, as it's going to return back to its original
916                  * scheduling class after this.
917                  */
918                 BUG_ON(!p->dl.dl_boosted || flags != ENQUEUE_REPLENISH);
919                 return;
920         }
921
922         /*
923          * If p is throttled, we do nothing. In fact, if it exhausted
924          * its budget it needs a replenishment and, since it now is on
925          * its rq, the bandwidth timer callback (which clearly has not
926          * run yet) will take care of this.
927          */
928         if (p->dl.dl_throttled && !(flags & ENQUEUE_REPLENISH))
929                 return;
930
931         enqueue_dl_entity(&p->dl, pi_se, flags);
932
933         if (!task_current(rq, p) && p->nr_cpus_allowed > 1)
934                 enqueue_pushable_dl_task(rq, p);
935 }
936
937 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
938 {
939         dequeue_dl_entity(&p->dl);
940         dequeue_pushable_dl_task(rq, p);
941 }
942
943 static void dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
944 {
945         update_curr_dl(rq);
946         __dequeue_task_dl(rq, p, flags);
947 }
948
949 /*
950  * Yield task semantic for -deadline tasks is:
951  *
952  *   get off from the CPU until our next instance, with
953  *   a new runtime. This is of little use now, since we
954  *   don't have a bandwidth reclaiming mechanism. Anyway,
955  *   bandwidth reclaiming is planned for the future, and
956  *   yield_task_dl will indicate that some spare budget
957  *   is available for other task instances to use it.
958  */
959 static void yield_task_dl(struct rq *rq)
960 {
961         struct task_struct *p = rq->curr;
962
963         /*
964          * We make the task go to sleep until its current deadline by
965          * forcing its runtime to zero. This way, update_curr_dl() stops
966          * it and the bandwidth timer will wake it up and will give it
967          * new scheduling parameters (thanks to dl_yielded=1).
968          */
969         if (p->dl.runtime > 0) {
970                 rq->curr->dl.dl_yielded = 1;
971                 p->dl.runtime = 0;
972         }
973         update_rq_clock(rq);
974         update_curr_dl(rq);
975         /*
976          * Tell update_rq_clock() that we've just updated,
977          * so we don't do microscopic update in schedule()
978          * and double the fastpath cost.
979          */
980         rq_clock_skip_update(rq, true);
981 }
982
983 #ifdef CONFIG_SMP
984
985 static int find_later_rq(struct task_struct *task);
986
987 static int
988 select_task_rq_dl(struct task_struct *p, int cpu, int sd_flag, int flags)
989 {
990         struct task_struct *curr;
991         struct rq *rq;
992
993         if (sd_flag != SD_BALANCE_WAKE)
994                 goto out;
995
996         rq = cpu_rq(cpu);
997
998         rcu_read_lock();
999         curr = ACCESS_ONCE(rq->curr); /* unlocked access */
1000
1001         /*
1002          * If we are dealing with a -deadline task, we must
1003          * decide where to wake it up.
1004          * If it has a later deadline and the current task
1005          * on this rq can't move (provided the waking task
1006          * can!) we prefer to send it somewhere else. On the
1007          * other hand, if it has a shorter deadline, we
1008          * try to make it stay here, it might be important.
1009          */
1010         if (unlikely(dl_task(curr)) &&
1011             (curr->nr_cpus_allowed < 2 ||
1012              !dl_entity_preempt(&p->dl, &curr->dl)) &&
1013             (p->nr_cpus_allowed > 1)) {
1014                 int target = find_later_rq(p);
1015
1016                 if (target != -1)
1017                         cpu = target;
1018         }
1019         rcu_read_unlock();
1020
1021 out:
1022         return cpu;
1023 }
1024
1025 static void check_preempt_equal_dl(struct rq *rq, struct task_struct *p)
1026 {
1027         /*
1028          * Current can't be migrated, useless to reschedule,
1029          * let's hope p can move out.
1030          */
1031         if (rq->curr->nr_cpus_allowed == 1 ||
1032             cpudl_find(&rq->rd->cpudl, rq->curr, NULL) == -1)
1033                 return;
1034
1035         /*
1036          * p is migratable, so let's not schedule it and
1037          * see if it is pushed or pulled somewhere else.
1038          */
1039         if (p->nr_cpus_allowed != 1 &&
1040             cpudl_find(&rq->rd->cpudl, p, NULL) != -1)
1041                 return;
1042
1043         resched_curr(rq);
1044 }
1045
1046 static int pull_dl_task(struct rq *this_rq);
1047
1048 #endif /* CONFIG_SMP */
1049
1050 /*
1051  * Only called when both the current and waking task are -deadline
1052  * tasks.
1053  */
1054 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
1055                                   int flags)
1056 {
1057         if (dl_entity_preempt(&p->dl, &rq->curr->dl)) {
1058                 resched_curr(rq);
1059                 return;
1060         }
1061
1062 #ifdef CONFIG_SMP
1063         /*
1064          * In the unlikely case current and p have the same deadline
1065          * let us try to decide what's the best thing to do...
1066          */
1067         if ((p->dl.deadline == rq->curr->dl.deadline) &&
1068             !test_tsk_need_resched(rq->curr))
1069                 check_preempt_equal_dl(rq, p);
1070 #endif /* CONFIG_SMP */
1071 }
1072
1073 #ifdef CONFIG_SCHED_HRTICK
1074 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1075 {
1076         hrtick_start(rq, p->dl.runtime);
1077 }
1078 #else /* !CONFIG_SCHED_HRTICK */
1079 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1080 {
1081 }
1082 #endif
1083
1084 static struct sched_dl_entity *pick_next_dl_entity(struct rq *rq,
1085                                                    struct dl_rq *dl_rq)
1086 {
1087         struct rb_node *left = dl_rq->rb_leftmost;
1088
1089         if (!left)
1090                 return NULL;
1091
1092         return rb_entry(left, struct sched_dl_entity, rb_node);
1093 }
1094
1095 struct task_struct *pick_next_task_dl(struct rq *rq, struct task_struct *prev)
1096 {
1097         struct sched_dl_entity *dl_se;
1098         struct task_struct *p;
1099         struct dl_rq *dl_rq;
1100
1101         dl_rq = &rq->dl;
1102
1103         if (need_pull_dl_task(rq, prev)) {
1104                 pull_dl_task(rq);
1105                 /*
1106                  * pull_rt_task() can drop (and re-acquire) rq->lock; this
1107                  * means a stop task can slip in, in which case we need to
1108                  * re-start task selection.
1109                  */
1110                 if (rq->stop && task_on_rq_queued(rq->stop))
1111                         return RETRY_TASK;
1112         }
1113
1114         /*
1115          * When prev is DL, we may throttle it in put_prev_task().
1116          * So, we update time before we check for dl_nr_running.
1117          */
1118         if (prev->sched_class == &dl_sched_class)
1119                 update_curr_dl(rq);
1120
1121         if (unlikely(!dl_rq->dl_nr_running))
1122                 return NULL;
1123
1124         put_prev_task(rq, prev);
1125
1126         dl_se = pick_next_dl_entity(rq, dl_rq);
1127         BUG_ON(!dl_se);
1128
1129         p = dl_task_of(dl_se);
1130         p->se.exec_start = rq_clock_task(rq);
1131
1132         /* Running task will never be pushed. */
1133        dequeue_pushable_dl_task(rq, p);
1134
1135         if (hrtick_enabled(rq))
1136                 start_hrtick_dl(rq, p);
1137
1138         set_post_schedule(rq);
1139
1140         return p;
1141 }
1142
1143 static void put_prev_task_dl(struct rq *rq, struct task_struct *p)
1144 {
1145         update_curr_dl(rq);
1146
1147         if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1)
1148                 enqueue_pushable_dl_task(rq, p);
1149 }
1150
1151 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued)
1152 {
1153         update_curr_dl(rq);
1154
1155         /*
1156          * Even when we have runtime, update_curr_dl() might have resulted in us
1157          * not being the leftmost task anymore. In that case NEED_RESCHED will
1158          * be set and schedule() will start a new hrtick for the next task.
1159          */
1160         if (hrtick_enabled(rq) && queued && p->dl.runtime > 0 &&
1161             is_leftmost(p, &rq->dl))
1162                 start_hrtick_dl(rq, p);
1163 }
1164
1165 static void task_fork_dl(struct task_struct *p)
1166 {
1167         /*
1168          * SCHED_DEADLINE tasks cannot fork and this is achieved through
1169          * sched_fork()
1170          */
1171 }
1172
1173 static void task_dead_dl(struct task_struct *p)
1174 {
1175         struct hrtimer *timer = &p->dl.dl_timer;
1176         struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
1177
1178         /*
1179          * Since we are TASK_DEAD we won't slip out of the domain!
1180          */
1181         raw_spin_lock_irq(&dl_b->lock);
1182         /* XXX we should retain the bw until 0-lag */
1183         dl_b->total_bw -= p->dl.dl_bw;
1184         raw_spin_unlock_irq(&dl_b->lock);
1185
1186         hrtimer_cancel(timer);
1187 }
1188
1189 static void set_curr_task_dl(struct rq *rq)
1190 {
1191         struct task_struct *p = rq->curr;
1192
1193         p->se.exec_start = rq_clock_task(rq);
1194
1195         /* You can't push away the running task */
1196         dequeue_pushable_dl_task(rq, p);
1197 }
1198
1199 #ifdef CONFIG_SMP
1200
1201 /* Only try algorithms three times */
1202 #define DL_MAX_TRIES 3
1203
1204 static int pick_dl_task(struct rq *rq, struct task_struct *p, int cpu)
1205 {
1206         if (!task_running(rq, p) &&
1207             cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
1208                 return 1;
1209         return 0;
1210 }
1211
1212 /* Returns the second earliest -deadline task, NULL otherwise */
1213 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu)
1214 {
1215         struct rb_node *next_node = rq->dl.rb_leftmost;
1216         struct sched_dl_entity *dl_se;
1217         struct task_struct *p = NULL;
1218
1219 next_node:
1220         next_node = rb_next(next_node);
1221         if (next_node) {
1222                 dl_se = rb_entry(next_node, struct sched_dl_entity, rb_node);
1223                 p = dl_task_of(dl_se);
1224
1225                 if (pick_dl_task(rq, p, cpu))
1226                         return p;
1227
1228                 goto next_node;
1229         }
1230
1231         return NULL;
1232 }
1233
1234 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
1235
1236 static int find_later_rq(struct task_struct *task)
1237 {
1238         struct sched_domain *sd;
1239         struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
1240         int this_cpu = smp_processor_id();
1241         int best_cpu, cpu = task_cpu(task);
1242
1243         /* Make sure the mask is initialized first */
1244         if (unlikely(!later_mask))
1245                 return -1;
1246
1247         if (task->nr_cpus_allowed == 1)
1248                 return -1;
1249
1250         /*
1251          * We have to consider system topology and task affinity
1252          * first, then we can look for a suitable cpu.
1253          */
1254         best_cpu = cpudl_find(&task_rq(task)->rd->cpudl,
1255                         task, later_mask);
1256         if (best_cpu == -1)
1257                 return -1;
1258
1259         /*
1260          * If we are here, some target has been found,
1261          * the most suitable of which is cached in best_cpu.
1262          * This is, among the runqueues where the current tasks
1263          * have later deadlines than the task's one, the rq
1264          * with the latest possible one.
1265          *
1266          * Now we check how well this matches with task's
1267          * affinity and system topology.
1268          *
1269          * The last cpu where the task run is our first
1270          * guess, since it is most likely cache-hot there.
1271          */
1272         if (cpumask_test_cpu(cpu, later_mask))
1273                 return cpu;
1274         /*
1275          * Check if this_cpu is to be skipped (i.e., it is
1276          * not in the mask) or not.
1277          */
1278         if (!cpumask_test_cpu(this_cpu, later_mask))
1279                 this_cpu = -1;
1280
1281         rcu_read_lock();
1282         for_each_domain(cpu, sd) {
1283                 if (sd->flags & SD_WAKE_AFFINE) {
1284
1285                         /*
1286                          * If possible, preempting this_cpu is
1287                          * cheaper than migrating.
1288                          */
1289                         if (this_cpu != -1 &&
1290                             cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
1291                                 rcu_read_unlock();
1292                                 return this_cpu;
1293                         }
1294
1295                         /*
1296                          * Last chance: if best_cpu is valid and is
1297                          * in the mask, that becomes our choice.
1298                          */
1299                         if (best_cpu < nr_cpu_ids &&
1300                             cpumask_test_cpu(best_cpu, sched_domain_span(sd))) {
1301                                 rcu_read_unlock();
1302                                 return best_cpu;
1303                         }
1304                 }
1305         }
1306         rcu_read_unlock();
1307
1308         /*
1309          * At this point, all our guesses failed, we just return
1310          * 'something', and let the caller sort the things out.
1311          */
1312         if (this_cpu != -1)
1313                 return this_cpu;
1314
1315         cpu = cpumask_any(later_mask);
1316         if (cpu < nr_cpu_ids)
1317                 return cpu;
1318
1319         return -1;
1320 }
1321
1322 /* Locks the rq it finds */
1323 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq)
1324 {
1325         struct rq *later_rq = NULL;
1326         int tries;
1327         int cpu;
1328
1329         for (tries = 0; tries < DL_MAX_TRIES; tries++) {
1330                 cpu = find_later_rq(task);
1331
1332                 if ((cpu == -1) || (cpu == rq->cpu))
1333                         break;
1334
1335                 later_rq = cpu_rq(cpu);
1336
1337                 /* Retry if something changed. */
1338                 if (double_lock_balance(rq, later_rq)) {
1339                         if (unlikely(task_rq(task) != rq ||
1340                                      !cpumask_test_cpu(later_rq->cpu,
1341                                                        &task->cpus_allowed) ||
1342                                      task_running(rq, task) ||
1343                                      !task_on_rq_queued(task))) {
1344                                 double_unlock_balance(rq, later_rq);
1345                                 later_rq = NULL;
1346                                 break;
1347                         }
1348                 }
1349
1350                 /*
1351                  * If the rq we found has no -deadline task, or
1352                  * its earliest one has a later deadline than our
1353                  * task, the rq is a good one.
1354                  */
1355                 if (!later_rq->dl.dl_nr_running ||
1356                     dl_time_before(task->dl.deadline,
1357                                    later_rq->dl.earliest_dl.curr))
1358                         break;
1359
1360                 /* Otherwise we try again. */
1361                 double_unlock_balance(rq, later_rq);
1362                 later_rq = NULL;
1363         }
1364
1365         return later_rq;
1366 }
1367
1368 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq)
1369 {
1370         struct task_struct *p;
1371
1372         if (!has_pushable_dl_tasks(rq))
1373                 return NULL;
1374
1375         p = rb_entry(rq->dl.pushable_dl_tasks_leftmost,
1376                      struct task_struct, pushable_dl_tasks);
1377
1378         BUG_ON(rq->cpu != task_cpu(p));
1379         BUG_ON(task_current(rq, p));
1380         BUG_ON(p->nr_cpus_allowed <= 1);
1381
1382         BUG_ON(!task_on_rq_queued(p));
1383         BUG_ON(!dl_task(p));
1384
1385         return p;
1386 }
1387
1388 /*
1389  * See if the non running -deadline tasks on this rq
1390  * can be sent to some other CPU where they can preempt
1391  * and start executing.
1392  */
1393 static int push_dl_task(struct rq *rq)
1394 {
1395         struct task_struct *next_task;
1396         struct rq *later_rq;
1397         int ret = 0;
1398
1399         if (!rq->dl.overloaded)
1400                 return 0;
1401
1402         next_task = pick_next_pushable_dl_task(rq);
1403         if (!next_task)
1404                 return 0;
1405
1406 retry:
1407         if (unlikely(next_task == rq->curr)) {
1408                 WARN_ON(1);
1409                 return 0;
1410         }
1411
1412         /*
1413          * If next_task preempts rq->curr, and rq->curr
1414          * can move away, it makes sense to just reschedule
1415          * without going further in pushing next_task.
1416          */
1417         if (dl_task(rq->curr) &&
1418             dl_time_before(next_task->dl.deadline, rq->curr->dl.deadline) &&
1419             rq->curr->nr_cpus_allowed > 1) {
1420                 resched_curr(rq);
1421                 return 0;
1422         }
1423
1424         /* We might release rq lock */
1425         get_task_struct(next_task);
1426
1427         /* Will lock the rq it'll find */
1428         later_rq = find_lock_later_rq(next_task, rq);
1429         if (!later_rq) {
1430                 struct task_struct *task;
1431
1432                 /*
1433                  * We must check all this again, since
1434                  * find_lock_later_rq releases rq->lock and it is
1435                  * then possible that next_task has migrated.
1436                  */
1437                 task = pick_next_pushable_dl_task(rq);
1438                 if (task_cpu(next_task) == rq->cpu && task == next_task) {
1439                         /*
1440                          * The task is still there. We don't try
1441                          * again, some other cpu will pull it when ready.
1442                          */
1443                         goto out;
1444                 }
1445
1446                 if (!task)
1447                         /* No more tasks */
1448                         goto out;
1449
1450                 put_task_struct(next_task);
1451                 next_task = task;
1452                 goto retry;
1453         }
1454
1455         deactivate_task(rq, next_task, 0);
1456         set_task_cpu(next_task, later_rq->cpu);
1457         activate_task(later_rq, next_task, 0);
1458         ret = 1;
1459
1460         resched_curr(later_rq);
1461
1462         double_unlock_balance(rq, later_rq);
1463
1464 out:
1465         put_task_struct(next_task);
1466
1467         return ret;
1468 }
1469
1470 static void push_dl_tasks(struct rq *rq)
1471 {
1472         /* Terminates as it moves a -deadline task */
1473         while (push_dl_task(rq))
1474                 ;
1475 }
1476
1477 static int pull_dl_task(struct rq *this_rq)
1478 {
1479         int this_cpu = this_rq->cpu, ret = 0, cpu;
1480         struct task_struct *p;
1481         struct rq *src_rq;
1482         u64 dmin = LONG_MAX;
1483
1484         if (likely(!dl_overloaded(this_rq)))
1485                 return 0;
1486
1487         /*
1488          * Match the barrier from dl_set_overloaded; this guarantees that if we
1489          * see overloaded we must also see the dlo_mask bit.
1490          */
1491         smp_rmb();
1492
1493         for_each_cpu(cpu, this_rq->rd->dlo_mask) {
1494                 if (this_cpu == cpu)
1495                         continue;
1496
1497                 src_rq = cpu_rq(cpu);
1498
1499                 /*
1500                  * It looks racy, abd it is! However, as in sched_rt.c,
1501                  * we are fine with this.
1502                  */
1503                 if (this_rq->dl.dl_nr_running &&
1504                     dl_time_before(this_rq->dl.earliest_dl.curr,
1505                                    src_rq->dl.earliest_dl.next))
1506                         continue;
1507
1508                 /* Might drop this_rq->lock */
1509                 double_lock_balance(this_rq, src_rq);
1510
1511                 /*
1512                  * If there are no more pullable tasks on the
1513                  * rq, we're done with it.
1514                  */
1515                 if (src_rq->dl.dl_nr_running <= 1)
1516                         goto skip;
1517
1518                 p = pick_next_earliest_dl_task(src_rq, this_cpu);
1519
1520                 /*
1521                  * We found a task to be pulled if:
1522                  *  - it preempts our current (if there's one),
1523                  *  - it will preempt the last one we pulled (if any).
1524                  */
1525                 if (p && dl_time_before(p->dl.deadline, dmin) &&
1526                     (!this_rq->dl.dl_nr_running ||
1527                      dl_time_before(p->dl.deadline,
1528                                     this_rq->dl.earliest_dl.curr))) {
1529                         WARN_ON(p == src_rq->curr);
1530                         WARN_ON(!task_on_rq_queued(p));
1531
1532                         /*
1533                          * Then we pull iff p has actually an earlier
1534                          * deadline than the current task of its runqueue.
1535                          */
1536                         if (dl_time_before(p->dl.deadline,
1537                                            src_rq->curr->dl.deadline))
1538                                 goto skip;
1539
1540                         ret = 1;
1541
1542                         deactivate_task(src_rq, p, 0);
1543                         set_task_cpu(p, this_cpu);
1544                         activate_task(this_rq, p, 0);
1545                         dmin = p->dl.deadline;
1546
1547                         /* Is there any other task even earlier? */
1548                 }
1549 skip:
1550                 double_unlock_balance(this_rq, src_rq);
1551         }
1552
1553         return ret;
1554 }
1555
1556 static void post_schedule_dl(struct rq *rq)
1557 {
1558         push_dl_tasks(rq);
1559 }
1560
1561 /*
1562  * Since the task is not running and a reschedule is not going to happen
1563  * anytime soon on its runqueue, we try pushing it away now.
1564  */
1565 static void task_woken_dl(struct rq *rq, struct task_struct *p)
1566 {
1567         if (!task_running(rq, p) &&
1568             !test_tsk_need_resched(rq->curr) &&
1569             has_pushable_dl_tasks(rq) &&
1570             p->nr_cpus_allowed > 1 &&
1571             dl_task(rq->curr) &&
1572             (rq->curr->nr_cpus_allowed < 2 ||
1573              !dl_entity_preempt(&p->dl, &rq->curr->dl))) {
1574                 push_dl_tasks(rq);
1575         }
1576 }
1577
1578 static void set_cpus_allowed_dl(struct task_struct *p,
1579                                 const struct cpumask *new_mask)
1580 {
1581         struct rq *rq;
1582         struct root_domain *src_rd;
1583         int weight;
1584
1585         BUG_ON(!dl_task(p));
1586
1587         rq = task_rq(p);
1588         src_rd = rq->rd;
1589         /*
1590          * Migrating a SCHED_DEADLINE task between exclusive
1591          * cpusets (different root_domains) entails a bandwidth
1592          * update. We already made space for us in the destination
1593          * domain (see cpuset_can_attach()).
1594          */
1595         if (!cpumask_intersects(src_rd->span, new_mask)) {
1596                 struct dl_bw *src_dl_b;
1597
1598                 src_dl_b = dl_bw_of(cpu_of(rq));
1599                 /*
1600                  * We now free resources of the root_domain we are migrating
1601                  * off. In the worst case, sched_setattr() may temporary fail
1602                  * until we complete the update.
1603                  */
1604                 raw_spin_lock(&src_dl_b->lock);
1605                 __dl_clear(src_dl_b, p->dl.dl_bw);
1606                 raw_spin_unlock(&src_dl_b->lock);
1607         }
1608
1609         /*
1610          * Update only if the task is actually running (i.e.,
1611          * it is on the rq AND it is not throttled).
1612          */
1613         if (!on_dl_rq(&p->dl))
1614                 return;
1615
1616         weight = cpumask_weight(new_mask);
1617
1618         /*
1619          * Only update if the process changes its state from whether it
1620          * can migrate or not.
1621          */
1622         if ((p->nr_cpus_allowed > 1) == (weight > 1))
1623                 return;
1624
1625         /*
1626          * The process used to be able to migrate OR it can now migrate
1627          */
1628         if (weight <= 1) {
1629                 if (!task_current(rq, p))
1630                         dequeue_pushable_dl_task(rq, p);
1631                 BUG_ON(!rq->dl.dl_nr_migratory);
1632                 rq->dl.dl_nr_migratory--;
1633         } else {
1634                 if (!task_current(rq, p))
1635                         enqueue_pushable_dl_task(rq, p);
1636                 rq->dl.dl_nr_migratory++;
1637         }
1638
1639         update_dl_migration(&rq->dl);
1640 }
1641
1642 /* Assumes rq->lock is held */
1643 static void rq_online_dl(struct rq *rq)
1644 {
1645         if (rq->dl.overloaded)
1646                 dl_set_overload(rq);
1647
1648         cpudl_set_freecpu(&rq->rd->cpudl, rq->cpu);
1649         if (rq->dl.dl_nr_running > 0)
1650                 cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr, 1);
1651 }
1652
1653 /* Assumes rq->lock is held */
1654 static void rq_offline_dl(struct rq *rq)
1655 {
1656         if (rq->dl.overloaded)
1657                 dl_clear_overload(rq);
1658
1659         cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0);
1660         cpudl_clear_freecpu(&rq->rd->cpudl, rq->cpu);
1661 }
1662
1663 void init_sched_dl_class(void)
1664 {
1665         unsigned int i;
1666
1667         for_each_possible_cpu(i)
1668                 zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
1669                                         GFP_KERNEL, cpu_to_node(i));
1670 }
1671
1672 #endif /* CONFIG_SMP */
1673
1674 /*
1675  *  Ensure p's dl_timer is cancelled. May drop rq->lock for a while.
1676  */
1677 static void cancel_dl_timer(struct rq *rq, struct task_struct *p)
1678 {
1679         struct hrtimer *dl_timer = &p->dl.dl_timer;
1680
1681         /* Nobody will change task's class if pi_lock is held */
1682         lockdep_assert_held(&p->pi_lock);
1683
1684         if (hrtimer_active(dl_timer)) {
1685                 int ret = hrtimer_try_to_cancel(dl_timer);
1686
1687                 if (unlikely(ret == -1)) {
1688                         /*
1689                          * Note, p may migrate OR new deadline tasks
1690                          * may appear in rq when we are unlocking it.
1691                          * A caller of us must be fine with that.
1692                          */
1693                         raw_spin_unlock(&rq->lock);
1694                         hrtimer_cancel(dl_timer);
1695                         raw_spin_lock(&rq->lock);
1696                 }
1697         }
1698 }
1699
1700 static void switched_from_dl(struct rq *rq, struct task_struct *p)
1701 {
1702         /* XXX we should retain the bw until 0-lag */
1703         cancel_dl_timer(rq, p);
1704         __dl_clear_params(p);
1705
1706         /*
1707          * Since this might be the only -deadline task on the rq,
1708          * this is the right place to try to pull some other one
1709          * from an overloaded cpu, if any.
1710          */
1711         if (!task_on_rq_queued(p) || rq->dl.dl_nr_running)
1712                 return;
1713
1714         if (pull_dl_task(rq))
1715                 resched_curr(rq);
1716 }
1717
1718 /*
1719  * When switching to -deadline, we may overload the rq, then
1720  * we try to push someone off, if possible.
1721  */
1722 static void switched_to_dl(struct rq *rq, struct task_struct *p)
1723 {
1724         int check_resched = 1;
1725
1726         if (task_on_rq_queued(p) && rq->curr != p) {
1727 #ifdef CONFIG_SMP
1728                 if (p->nr_cpus_allowed > 1 && rq->dl.overloaded &&
1729                         push_dl_task(rq) && rq != task_rq(p))
1730                         /* Only reschedule if pushing failed */
1731                         check_resched = 0;
1732 #endif /* CONFIG_SMP */
1733                 if (check_resched) {
1734                         if (dl_task(rq->curr))
1735                                 check_preempt_curr_dl(rq, p, 0);
1736                         else
1737                                 resched_curr(rq);
1738                 }
1739         }
1740 }
1741
1742 /*
1743  * If the scheduling parameters of a -deadline task changed,
1744  * a push or pull operation might be needed.
1745  */
1746 static void prio_changed_dl(struct rq *rq, struct task_struct *p,
1747                             int oldprio)
1748 {
1749         if (task_on_rq_queued(p) || rq->curr == p) {
1750 #ifdef CONFIG_SMP
1751                 /*
1752                  * This might be too much, but unfortunately
1753                  * we don't have the old deadline value, and
1754                  * we can't argue if the task is increasing
1755                  * or lowering its prio, so...
1756                  */
1757                 if (!rq->dl.overloaded)
1758                         pull_dl_task(rq);
1759
1760                 /*
1761                  * If we now have a earlier deadline task than p,
1762                  * then reschedule, provided p is still on this
1763                  * runqueue.
1764                  */
1765                 if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline) &&
1766                     rq->curr == p)
1767                         resched_curr(rq);
1768 #else
1769                 /*
1770                  * Again, we don't know if p has a earlier
1771                  * or later deadline, so let's blindly set a
1772                  * (maybe not needed) rescheduling point.
1773                  */
1774                 resched_curr(rq);
1775 #endif /* CONFIG_SMP */
1776         } else
1777                 switched_to_dl(rq, p);
1778 }
1779
1780 const struct sched_class dl_sched_class = {
1781         .next                   = &rt_sched_class,
1782         .enqueue_task           = enqueue_task_dl,
1783         .dequeue_task           = dequeue_task_dl,
1784         .yield_task             = yield_task_dl,
1785
1786         .check_preempt_curr     = check_preempt_curr_dl,
1787
1788         .pick_next_task         = pick_next_task_dl,
1789         .put_prev_task          = put_prev_task_dl,
1790
1791 #ifdef CONFIG_SMP
1792         .select_task_rq         = select_task_rq_dl,
1793         .set_cpus_allowed       = set_cpus_allowed_dl,
1794         .rq_online              = rq_online_dl,
1795         .rq_offline             = rq_offline_dl,
1796         .post_schedule          = post_schedule_dl,
1797         .task_woken             = task_woken_dl,
1798 #endif
1799
1800         .set_curr_task          = set_curr_task_dl,
1801         .task_tick              = task_tick_dl,
1802         .task_fork              = task_fork_dl,
1803         .task_dead              = task_dead_dl,
1804
1805         .prio_changed           = prio_changed_dl,
1806         .switched_from          = switched_from_dl,
1807         .switched_to            = switched_to_dl,
1808
1809         .update_curr            = update_curr_dl,
1810 };
1811
1812 #ifdef CONFIG_SCHED_DEBUG
1813 extern void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq);
1814
1815 void print_dl_stats(struct seq_file *m, int cpu)
1816 {
1817         print_dl_rq(m, cpu, &cpu_rq(cpu)->dl);
1818 }
1819 #endif /* CONFIG_SCHED_DEBUG */