Merge branch 'linux-linaro-lsk' into linux-linaro-lsk-android
[firefly-linux-kernel-4.4.55.git] / kernel / sched / core.c
1 /*
2  *  kernel/sched/core.c
3  *
4  *  Kernel scheduler and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  *
8  *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
9  *              make semaphores SMP safe
10  *  1998-11-19  Implemented schedule_timeout() and related stuff
11  *              by Andrea Arcangeli
12  *  2002-01-04  New ultra-scalable O(1) scheduler by Ingo Molnar:
13  *              hybrid priority-list and round-robin design with
14  *              an array-switch method of distributing timeslices
15  *              and per-CPU runqueues.  Cleanups and useful suggestions
16  *              by Davide Libenzi, preemptible kernel bits by Robert Love.
17  *  2003-09-03  Interactivity tuning by Con Kolivas.
18  *  2004-04-02  Scheduler domains code by Nick Piggin
19  *  2007-04-15  Work begun on replacing all interactivity tuning with a
20  *              fair scheduling design by Con Kolivas.
21  *  2007-05-05  Load balancing (smp-nice) and other improvements
22  *              by Peter Williams
23  *  2007-05-06  Interactivity improvements to CFS by Mike Galbraith
24  *  2007-07-01  Group scheduling enhancements by Srivatsa Vaddagiri
25  *  2007-11-29  RT balancing improvements by Steven Rostedt, Gregory Haskins,
26  *              Thomas Gleixner, Mike Kravetz
27  */
28
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <asm/mmu_context.h>
36 #include <linux/interrupt.h>
37 #include <linux/capability.h>
38 #include <linux/completion.h>
39 #include <linux/kernel_stat.h>
40 #include <linux/debug_locks.h>
41 #include <linux/perf_event.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/proc_fs.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/unistd.h>
66 #include <linux/pagemap.h>
67 #include <linux/hrtimer.h>
68 #include <linux/tick.h>
69 #include <linux/debugfs.h>
70 #include <linux/ctype.h>
71 #include <linux/ftrace.h>
72 #include <linux/slab.h>
73 #include <linux/init_task.h>
74 #include <linux/binfmts.h>
75 #include <linux/context_tracking.h>
76
77 #include <asm/switch_to.h>
78 #include <asm/tlb.h>
79 #include <asm/irq_regs.h>
80 #include <asm/mutex.h>
81 #ifdef CONFIG_PARAVIRT
82 #include <asm/paravirt.h>
83 #endif
84
85 #include "sched.h"
86 #include "../workqueue_internal.h"
87 #include "../smpboot.h"
88
89 #define CREATE_TRACE_POINTS
90 #include <trace/events/sched.h>
91
92 void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
93 {
94         unsigned long delta;
95         ktime_t soft, hard, now;
96
97         for (;;) {
98                 if (hrtimer_active(period_timer))
99                         break;
100
101                 now = hrtimer_cb_get_time(period_timer);
102                 hrtimer_forward(period_timer, now, period);
103
104                 soft = hrtimer_get_softexpires(period_timer);
105                 hard = hrtimer_get_expires(period_timer);
106                 delta = ktime_to_ns(ktime_sub(hard, soft));
107                 __hrtimer_start_range_ns(period_timer, soft, delta,
108                                          HRTIMER_MODE_ABS_PINNED, 0);
109         }
110 }
111
112 DEFINE_MUTEX(sched_domains_mutex);
113 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
114
115 static void update_rq_clock_task(struct rq *rq, s64 delta);
116
117 void update_rq_clock(struct rq *rq)
118 {
119         s64 delta;
120
121         if (rq->skip_clock_update > 0)
122                 return;
123
124         delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
125         rq->clock += delta;
126         update_rq_clock_task(rq, delta);
127 }
128
129 /*
130  * Debugging: various feature bits
131  */
132
133 #define SCHED_FEAT(name, enabled)       \
134         (1UL << __SCHED_FEAT_##name) * enabled |
135
136 const_debug unsigned int sysctl_sched_features =
137 #include "features.h"
138         0;
139
140 #undef SCHED_FEAT
141
142 #ifdef CONFIG_SCHED_DEBUG
143 #define SCHED_FEAT(name, enabled)       \
144         #name ,
145
146 static const char * const sched_feat_names[] = {
147 #include "features.h"
148 };
149
150 #undef SCHED_FEAT
151
152 static int sched_feat_show(struct seq_file *m, void *v)
153 {
154         int i;
155
156         for (i = 0; i < __SCHED_FEAT_NR; i++) {
157                 if (!(sysctl_sched_features & (1UL << i)))
158                         seq_puts(m, "NO_");
159                 seq_printf(m, "%s ", sched_feat_names[i]);
160         }
161         seq_puts(m, "\n");
162
163         return 0;
164 }
165
166 #ifdef HAVE_JUMP_LABEL
167
168 #define jump_label_key__true  STATIC_KEY_INIT_TRUE
169 #define jump_label_key__false STATIC_KEY_INIT_FALSE
170
171 #define SCHED_FEAT(name, enabled)       \
172         jump_label_key__##enabled ,
173
174 struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
175 #include "features.h"
176 };
177
178 #undef SCHED_FEAT
179
180 static void sched_feat_disable(int i)
181 {
182         if (static_key_enabled(&sched_feat_keys[i]))
183                 static_key_slow_dec(&sched_feat_keys[i]);
184 }
185
186 static void sched_feat_enable(int i)
187 {
188         if (!static_key_enabled(&sched_feat_keys[i]))
189                 static_key_slow_inc(&sched_feat_keys[i]);
190 }
191 #else
192 static void sched_feat_disable(int i) { };
193 static void sched_feat_enable(int i) { };
194 #endif /* HAVE_JUMP_LABEL */
195
196 static int sched_feat_set(char *cmp)
197 {
198         int i;
199         int neg = 0;
200
201         if (strncmp(cmp, "NO_", 3) == 0) {
202                 neg = 1;
203                 cmp += 3;
204         }
205
206         for (i = 0; i < __SCHED_FEAT_NR; i++) {
207                 if (strcmp(cmp, sched_feat_names[i]) == 0) {
208                         if (neg) {
209                                 sysctl_sched_features &= ~(1UL << i);
210                                 sched_feat_disable(i);
211                         } else {
212                                 sysctl_sched_features |= (1UL << i);
213                                 sched_feat_enable(i);
214                         }
215                         break;
216                 }
217         }
218
219         return i;
220 }
221
222 static ssize_t
223 sched_feat_write(struct file *filp, const char __user *ubuf,
224                 size_t cnt, loff_t *ppos)
225 {
226         char buf[64];
227         char *cmp;
228         int i;
229
230         if (cnt > 63)
231                 cnt = 63;
232
233         if (copy_from_user(&buf, ubuf, cnt))
234                 return -EFAULT;
235
236         buf[cnt] = 0;
237         cmp = strstrip(buf);
238
239         i = sched_feat_set(cmp);
240         if (i == __SCHED_FEAT_NR)
241                 return -EINVAL;
242
243         *ppos += cnt;
244
245         return cnt;
246 }
247
248 static int sched_feat_open(struct inode *inode, struct file *filp)
249 {
250         return single_open(filp, sched_feat_show, NULL);
251 }
252
253 static const struct file_operations sched_feat_fops = {
254         .open           = sched_feat_open,
255         .write          = sched_feat_write,
256         .read           = seq_read,
257         .llseek         = seq_lseek,
258         .release        = single_release,
259 };
260
261 static __init int sched_init_debug(void)
262 {
263         debugfs_create_file("sched_features", 0644, NULL, NULL,
264                         &sched_feat_fops);
265
266         return 0;
267 }
268 late_initcall(sched_init_debug);
269 #endif /* CONFIG_SCHED_DEBUG */
270
271 /*
272  * Number of tasks to iterate in a single balance run.
273  * Limited because this is done with IRQs disabled.
274  */
275 const_debug unsigned int sysctl_sched_nr_migrate = 32;
276
277 /*
278  * period over which we average the RT time consumption, measured
279  * in ms.
280  *
281  * default: 1s
282  */
283 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
284
285 /*
286  * period over which we measure -rt task cpu usage in us.
287  * default: 1s
288  */
289 unsigned int sysctl_sched_rt_period = 1000000;
290
291 __read_mostly int scheduler_running;
292
293 /*
294  * part of the period that we allow rt tasks to run in us.
295  * default: 0.95s
296  */
297 int sysctl_sched_rt_runtime = 950000;
298
299
300
301 /*
302  * __task_rq_lock - lock the rq @p resides on.
303  */
304 static inline struct rq *__task_rq_lock(struct task_struct *p)
305         __acquires(rq->lock)
306 {
307         struct rq *rq;
308
309         lockdep_assert_held(&p->pi_lock);
310
311         for (;;) {
312                 rq = task_rq(p);
313                 raw_spin_lock(&rq->lock);
314                 if (likely(rq == task_rq(p)))
315                         return rq;
316                 raw_spin_unlock(&rq->lock);
317         }
318 }
319
320 /*
321  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
322  */
323 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
324         __acquires(p->pi_lock)
325         __acquires(rq->lock)
326 {
327         struct rq *rq;
328
329         for (;;) {
330                 raw_spin_lock_irqsave(&p->pi_lock, *flags);
331                 rq = task_rq(p);
332                 raw_spin_lock(&rq->lock);
333                 if (likely(rq == task_rq(p)))
334                         return rq;
335                 raw_spin_unlock(&rq->lock);
336                 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
337         }
338 }
339
340 static void __task_rq_unlock(struct rq *rq)
341         __releases(rq->lock)
342 {
343         raw_spin_unlock(&rq->lock);
344 }
345
346 static inline void
347 task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
348         __releases(rq->lock)
349         __releases(p->pi_lock)
350 {
351         raw_spin_unlock(&rq->lock);
352         raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
353 }
354
355 /*
356  * this_rq_lock - lock this runqueue and disable interrupts.
357  */
358 static struct rq *this_rq_lock(void)
359         __acquires(rq->lock)
360 {
361         struct rq *rq;
362
363         local_irq_disable();
364         rq = this_rq();
365         raw_spin_lock(&rq->lock);
366
367         return rq;
368 }
369
370 #ifdef CONFIG_SCHED_HRTICK
371 /*
372  * Use HR-timers to deliver accurate preemption points.
373  *
374  * Its all a bit involved since we cannot program an hrt while holding the
375  * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
376  * reschedule event.
377  *
378  * When we get rescheduled we reprogram the hrtick_timer outside of the
379  * rq->lock.
380  */
381
382 static void hrtick_clear(struct rq *rq)
383 {
384         if (hrtimer_active(&rq->hrtick_timer))
385                 hrtimer_cancel(&rq->hrtick_timer);
386 }
387
388 /*
389  * High-resolution timer tick.
390  * Runs from hardirq context with interrupts disabled.
391  */
392 static enum hrtimer_restart hrtick(struct hrtimer *timer)
393 {
394         struct rq *rq = container_of(timer, struct rq, hrtick_timer);
395
396         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
397
398         raw_spin_lock(&rq->lock);
399         update_rq_clock(rq);
400         rq->curr->sched_class->task_tick(rq, rq->curr, 1);
401         raw_spin_unlock(&rq->lock);
402
403         return HRTIMER_NORESTART;
404 }
405
406 #ifdef CONFIG_SMP
407 /*
408  * called from hardirq (IPI) context
409  */
410 static void __hrtick_start(void *arg)
411 {
412         struct rq *rq = arg;
413
414         raw_spin_lock(&rq->lock);
415         hrtimer_restart(&rq->hrtick_timer);
416         rq->hrtick_csd_pending = 0;
417         raw_spin_unlock(&rq->lock);
418 }
419
420 /*
421  * Called to set the hrtick timer state.
422  *
423  * called with rq->lock held and irqs disabled
424  */
425 void hrtick_start(struct rq *rq, u64 delay)
426 {
427         struct hrtimer *timer = &rq->hrtick_timer;
428         ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
429
430         hrtimer_set_expires(timer, time);
431
432         if (rq == this_rq()) {
433                 hrtimer_restart(timer);
434         } else if (!rq->hrtick_csd_pending) {
435                 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
436                 rq->hrtick_csd_pending = 1;
437         }
438 }
439
440 static int
441 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
442 {
443         int cpu = (int)(long)hcpu;
444
445         switch (action) {
446         case CPU_UP_CANCELED:
447         case CPU_UP_CANCELED_FROZEN:
448         case CPU_DOWN_PREPARE:
449         case CPU_DOWN_PREPARE_FROZEN:
450         case CPU_DEAD:
451         case CPU_DEAD_FROZEN:
452                 hrtick_clear(cpu_rq(cpu));
453                 return NOTIFY_OK;
454         }
455
456         return NOTIFY_DONE;
457 }
458
459 static __init void init_hrtick(void)
460 {
461         hotcpu_notifier(hotplug_hrtick, 0);
462 }
463 #else
464 /*
465  * Called to set the hrtick timer state.
466  *
467  * called with rq->lock held and irqs disabled
468  */
469 void hrtick_start(struct rq *rq, u64 delay)
470 {
471         __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
472                         HRTIMER_MODE_REL_PINNED, 0);
473 }
474
475 static inline void init_hrtick(void)
476 {
477 }
478 #endif /* CONFIG_SMP */
479
480 static void init_rq_hrtick(struct rq *rq)
481 {
482 #ifdef CONFIG_SMP
483         rq->hrtick_csd_pending = 0;
484
485         rq->hrtick_csd.flags = 0;
486         rq->hrtick_csd.func = __hrtick_start;
487         rq->hrtick_csd.info = rq;
488 #endif
489
490         hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
491         rq->hrtick_timer.function = hrtick;
492 }
493 #else   /* CONFIG_SCHED_HRTICK */
494 static inline void hrtick_clear(struct rq *rq)
495 {
496 }
497
498 static inline void init_rq_hrtick(struct rq *rq)
499 {
500 }
501
502 static inline void init_hrtick(void)
503 {
504 }
505 #endif  /* CONFIG_SCHED_HRTICK */
506
507 /*
508  * resched_task - mark a task 'to be rescheduled now'.
509  *
510  * On UP this means the setting of the need_resched flag, on SMP it
511  * might also involve a cross-CPU call to trigger the scheduler on
512  * the target CPU.
513  */
514 #ifdef CONFIG_SMP
515 void resched_task(struct task_struct *p)
516 {
517         int cpu;
518
519         assert_raw_spin_locked(&task_rq(p)->lock);
520
521         if (test_tsk_need_resched(p))
522                 return;
523
524         set_tsk_need_resched(p);
525
526         cpu = task_cpu(p);
527         if (cpu == smp_processor_id())
528                 return;
529
530         /* NEED_RESCHED must be visible before we test polling */
531         smp_mb();
532         if (!tsk_is_polling(p))
533                 smp_send_reschedule(cpu);
534 }
535
536 void resched_cpu(int cpu)
537 {
538         struct rq *rq = cpu_rq(cpu);
539         unsigned long flags;
540
541         if (!raw_spin_trylock_irqsave(&rq->lock, flags))
542                 return;
543         resched_task(cpu_curr(cpu));
544         raw_spin_unlock_irqrestore(&rq->lock, flags);
545 }
546
547 #ifdef CONFIG_NO_HZ_COMMON
548 /*
549  * In the semi idle case, use the nearest busy cpu for migrating timers
550  * from an idle cpu.  This is good for power-savings.
551  *
552  * We don't do similar optimization for completely idle system, as
553  * selecting an idle cpu will add more delays to the timers than intended
554  * (as that cpu's timer base may not be uptodate wrt jiffies etc).
555  */
556 int get_nohz_timer_target(void)
557 {
558         int cpu = smp_processor_id();
559         int i;
560         struct sched_domain *sd;
561
562         rcu_read_lock();
563         for_each_domain(cpu, sd) {
564                 for_each_cpu(i, sched_domain_span(sd)) {
565                         if (!idle_cpu(i)) {
566                                 cpu = i;
567                                 goto unlock;
568                         }
569                 }
570         }
571 unlock:
572         rcu_read_unlock();
573         return cpu;
574 }
575 /*
576  * When add_timer_on() enqueues a timer into the timer wheel of an
577  * idle CPU then this timer might expire before the next timer event
578  * which is scheduled to wake up that CPU. In case of a completely
579  * idle system the next event might even be infinite time into the
580  * future. wake_up_idle_cpu() ensures that the CPU is woken up and
581  * leaves the inner idle loop so the newly added timer is taken into
582  * account when the CPU goes back to idle and evaluates the timer
583  * wheel for the next timer event.
584  */
585 static void wake_up_idle_cpu(int cpu)
586 {
587         struct rq *rq = cpu_rq(cpu);
588
589         if (cpu == smp_processor_id())
590                 return;
591
592         /*
593          * This is safe, as this function is called with the timer
594          * wheel base lock of (cpu) held. When the CPU is on the way
595          * to idle and has not yet set rq->curr to idle then it will
596          * be serialized on the timer wheel base lock and take the new
597          * timer into account automatically.
598          */
599         if (rq->curr != rq->idle)
600                 return;
601
602         /*
603          * We can set TIF_RESCHED on the idle task of the other CPU
604          * lockless. The worst case is that the other CPU runs the
605          * idle task through an additional NOOP schedule()
606          */
607         set_tsk_need_resched(rq->idle);
608
609         /* NEED_RESCHED must be visible before we test polling */
610         smp_mb();
611         if (!tsk_is_polling(rq->idle))
612                 smp_send_reschedule(cpu);
613 }
614
615 static bool wake_up_full_nohz_cpu(int cpu)
616 {
617         if (tick_nohz_full_cpu(cpu)) {
618                 if (cpu != smp_processor_id() ||
619                     tick_nohz_tick_stopped())
620                         smp_send_reschedule(cpu);
621                 return true;
622         }
623
624         return false;
625 }
626
627 void wake_up_nohz_cpu(int cpu)
628 {
629         if (!wake_up_full_nohz_cpu(cpu))
630                 wake_up_idle_cpu(cpu);
631 }
632
633 static inline bool got_nohz_idle_kick(void)
634 {
635         int cpu = smp_processor_id();
636
637         if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
638                 return false;
639
640         if (idle_cpu(cpu) && !need_resched())
641                 return true;
642
643         /*
644          * We can't run Idle Load Balance on this CPU for this time so we
645          * cancel it and clear NOHZ_BALANCE_KICK
646          */
647         clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
648         return false;
649 }
650
651 #else /* CONFIG_NO_HZ_COMMON */
652
653 static inline bool got_nohz_idle_kick(void)
654 {
655         return false;
656 }
657
658 #endif /* CONFIG_NO_HZ_COMMON */
659
660 #ifdef CONFIG_NO_HZ_FULL
661 bool sched_can_stop_tick(void)
662 {
663        struct rq *rq;
664
665        rq = this_rq();
666
667        /* Make sure rq->nr_running update is visible after the IPI */
668        smp_rmb();
669
670        /* More than one running task need preemption */
671        if (rq->nr_running > 1)
672                return false;
673
674        return true;
675 }
676 #endif /* CONFIG_NO_HZ_FULL */
677
678 void sched_avg_update(struct rq *rq)
679 {
680         s64 period = sched_avg_period();
681
682         while ((s64)(rq->clock - rq->age_stamp) > period) {
683                 /*
684                  * Inline assembly required to prevent the compiler
685                  * optimising this loop into a divmod call.
686                  * See __iter_div_u64_rem() for another example of this.
687                  */
688                 asm("" : "+rm" (rq->age_stamp));
689                 rq->age_stamp += period;
690                 rq->rt_avg /= 2;
691         }
692 }
693
694 #else /* !CONFIG_SMP */
695 void resched_task(struct task_struct *p)
696 {
697         assert_raw_spin_locked(&task_rq(p)->lock);
698         set_tsk_need_resched(p);
699 }
700 #endif /* CONFIG_SMP */
701
702 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
703                         (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
704 /*
705  * Iterate task_group tree rooted at *from, calling @down when first entering a
706  * node and @up when leaving it for the final time.
707  *
708  * Caller must hold rcu_lock or sufficient equivalent.
709  */
710 int walk_tg_tree_from(struct task_group *from,
711                              tg_visitor down, tg_visitor up, void *data)
712 {
713         struct task_group *parent, *child;
714         int ret;
715
716         parent = from;
717
718 down:
719         ret = (*down)(parent, data);
720         if (ret)
721                 goto out;
722         list_for_each_entry_rcu(child, &parent->children, siblings) {
723                 parent = child;
724                 goto down;
725
726 up:
727                 continue;
728         }
729         ret = (*up)(parent, data);
730         if (ret || parent == from)
731                 goto out;
732
733         child = parent;
734         parent = parent->parent;
735         if (parent)
736                 goto up;
737 out:
738         return ret;
739 }
740
741 int tg_nop(struct task_group *tg, void *data)
742 {
743         return 0;
744 }
745 #endif
746
747 static void set_load_weight(struct task_struct *p)
748 {
749         int prio = p->static_prio - MAX_RT_PRIO;
750         struct load_weight *load = &p->se.load;
751
752         /*
753          * SCHED_IDLE tasks get minimal weight:
754          */
755         if (p->policy == SCHED_IDLE) {
756                 load->weight = scale_load(WEIGHT_IDLEPRIO);
757                 load->inv_weight = WMULT_IDLEPRIO;
758                 return;
759         }
760
761         load->weight = scale_load(prio_to_weight[prio]);
762         load->inv_weight = prio_to_wmult[prio];
763 }
764
765 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
766 {
767         update_rq_clock(rq);
768         sched_info_queued(p);
769         p->sched_class->enqueue_task(rq, p, flags);
770 }
771
772 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
773 {
774         update_rq_clock(rq);
775         sched_info_dequeued(p);
776         p->sched_class->dequeue_task(rq, p, flags);
777 }
778
779 void activate_task(struct rq *rq, struct task_struct *p, int flags)
780 {
781         if (task_contributes_to_load(p))
782                 rq->nr_uninterruptible--;
783
784         enqueue_task(rq, p, flags);
785 }
786
787 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
788 {
789         if (task_contributes_to_load(p))
790                 rq->nr_uninterruptible++;
791
792         dequeue_task(rq, p, flags);
793 }
794
795 static void update_rq_clock_task(struct rq *rq, s64 delta)
796 {
797 /*
798  * In theory, the compile should just see 0 here, and optimize out the call
799  * to sched_rt_avg_update. But I don't trust it...
800  */
801 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
802         s64 steal = 0, irq_delta = 0;
803 #endif
804 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
805         irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
806
807         /*
808          * Since irq_time is only updated on {soft,}irq_exit, we might run into
809          * this case when a previous update_rq_clock() happened inside a
810          * {soft,}irq region.
811          *
812          * When this happens, we stop ->clock_task and only update the
813          * prev_irq_time stamp to account for the part that fit, so that a next
814          * update will consume the rest. This ensures ->clock_task is
815          * monotonic.
816          *
817          * It does however cause some slight miss-attribution of {soft,}irq
818          * time, a more accurate solution would be to update the irq_time using
819          * the current rq->clock timestamp, except that would require using
820          * atomic ops.
821          */
822         if (irq_delta > delta)
823                 irq_delta = delta;
824
825         rq->prev_irq_time += irq_delta;
826         delta -= irq_delta;
827 #endif
828 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
829         if (static_key_false((&paravirt_steal_rq_enabled))) {
830                 u64 st;
831
832                 steal = paravirt_steal_clock(cpu_of(rq));
833                 steal -= rq->prev_steal_time_rq;
834
835                 if (unlikely(steal > delta))
836                         steal = delta;
837
838                 st = steal_ticks(steal);
839                 steal = st * TICK_NSEC;
840
841                 rq->prev_steal_time_rq += steal;
842
843                 delta -= steal;
844         }
845 #endif
846
847         rq->clock_task += delta;
848
849 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
850         if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
851                 sched_rt_avg_update(rq, irq_delta + steal);
852 #endif
853 }
854
855 void sched_set_stop_task(int cpu, struct task_struct *stop)
856 {
857         struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
858         struct task_struct *old_stop = cpu_rq(cpu)->stop;
859
860         if (stop) {
861                 /*
862                  * Make it appear like a SCHED_FIFO task, its something
863                  * userspace knows about and won't get confused about.
864                  *
865                  * Also, it will make PI more or less work without too
866                  * much confusion -- but then, stop work should not
867                  * rely on PI working anyway.
868                  */
869                 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
870
871                 stop->sched_class = &stop_sched_class;
872         }
873
874         cpu_rq(cpu)->stop = stop;
875
876         if (old_stop) {
877                 /*
878                  * Reset it back to a normal scheduling class so that
879                  * it can die in pieces.
880                  */
881                 old_stop->sched_class = &rt_sched_class;
882         }
883 }
884
885 /*
886  * __normal_prio - return the priority that is based on the static prio
887  */
888 static inline int __normal_prio(struct task_struct *p)
889 {
890         return p->static_prio;
891 }
892
893 /*
894  * Calculate the expected normal priority: i.e. priority
895  * without taking RT-inheritance into account. Might be
896  * boosted by interactivity modifiers. Changes upon fork,
897  * setprio syscalls, and whenever the interactivity
898  * estimator recalculates.
899  */
900 static inline int normal_prio(struct task_struct *p)
901 {
902         int prio;
903
904         if (task_has_rt_policy(p))
905                 prio = MAX_RT_PRIO-1 - p->rt_priority;
906         else
907                 prio = __normal_prio(p);
908         return prio;
909 }
910
911 /*
912  * Calculate the current priority, i.e. the priority
913  * taken into account by the scheduler. This value might
914  * be boosted by RT tasks, or might be boosted by
915  * interactivity modifiers. Will be RT if the task got
916  * RT-boosted. If not then it returns p->normal_prio.
917  */
918 static int effective_prio(struct task_struct *p)
919 {
920         p->normal_prio = normal_prio(p);
921         /*
922          * If we are RT tasks or we were boosted to RT priority,
923          * keep the priority unchanged. Otherwise, update priority
924          * to the normal priority:
925          */
926         if (!rt_prio(p->prio))
927                 return p->normal_prio;
928         return p->prio;
929 }
930
931 /**
932  * task_curr - is this task currently executing on a CPU?
933  * @p: the task in question.
934  */
935 inline int task_curr(const struct task_struct *p)
936 {
937         return cpu_curr(task_cpu(p)) == p;
938 }
939
940 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
941                                        const struct sched_class *prev_class,
942                                        int oldprio)
943 {
944         if (prev_class != p->sched_class) {
945                 if (prev_class->switched_from)
946                         prev_class->switched_from(rq, p);
947                 p->sched_class->switched_to(rq, p);
948         } else if (oldprio != p->prio)
949                 p->sched_class->prio_changed(rq, p, oldprio);
950 }
951
952 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
953 {
954         const struct sched_class *class;
955
956         if (p->sched_class == rq->curr->sched_class) {
957                 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
958         } else {
959                 for_each_class(class) {
960                         if (class == rq->curr->sched_class)
961                                 break;
962                         if (class == p->sched_class) {
963                                 resched_task(rq->curr);
964                                 break;
965                         }
966                 }
967         }
968
969         /*
970          * A queue event has occurred, and we're going to schedule.  In
971          * this case, we can save a useless back to back clock update.
972          */
973         if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
974                 rq->skip_clock_update = 1;
975 }
976
977 static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
978
979 void register_task_migration_notifier(struct notifier_block *n)
980 {
981         atomic_notifier_chain_register(&task_migration_notifier, n);
982 }
983
984 #ifdef CONFIG_SMP
985 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
986 {
987 #ifdef CONFIG_SCHED_DEBUG
988         /*
989          * We should never call set_task_cpu() on a blocked task,
990          * ttwu() will sort out the placement.
991          */
992         WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
993                         !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
994
995 #ifdef CONFIG_LOCKDEP
996         /*
997          * The caller should hold either p->pi_lock or rq->lock, when changing
998          * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
999          *
1000          * sched_move_task() holds both and thus holding either pins the cgroup,
1001          * see task_group().
1002          *
1003          * Furthermore, all task_rq users should acquire both locks, see
1004          * task_rq_lock().
1005          */
1006         WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1007                                       lockdep_is_held(&task_rq(p)->lock)));
1008 #endif
1009 #endif
1010
1011         trace_sched_migrate_task(p, new_cpu);
1012
1013         if (task_cpu(p) != new_cpu) {
1014                 struct task_migration_notifier tmn;
1015
1016                 if (p->sched_class->migrate_task_rq)
1017                         p->sched_class->migrate_task_rq(p, new_cpu);
1018                 p->se.nr_migrations++;
1019                 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
1020
1021                 tmn.task = p;
1022                 tmn.from_cpu = task_cpu(p);
1023                 tmn.to_cpu = new_cpu;
1024
1025                 atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
1026         }
1027
1028         __set_task_cpu(p, new_cpu);
1029 }
1030
1031 struct migration_arg {
1032         struct task_struct *task;
1033         int dest_cpu;
1034 };
1035
1036 static int migration_cpu_stop(void *data);
1037
1038 /*
1039  * wait_task_inactive - wait for a thread to unschedule.
1040  *
1041  * If @match_state is nonzero, it's the @p->state value just checked and
1042  * not expected to change.  If it changes, i.e. @p might have woken up,
1043  * then return zero.  When we succeed in waiting for @p to be off its CPU,
1044  * we return a positive number (its total switch count).  If a second call
1045  * a short while later returns the same number, the caller can be sure that
1046  * @p has remained unscheduled the whole time.
1047  *
1048  * The caller must ensure that the task *will* unschedule sometime soon,
1049  * else this function might spin for a *long* time. This function can't
1050  * be called with interrupts off, or it may introduce deadlock with
1051  * smp_call_function() if an IPI is sent by the same process we are
1052  * waiting to become inactive.
1053  */
1054 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1055 {
1056         unsigned long flags;
1057         int running, on_rq;
1058         unsigned long ncsw;
1059         struct rq *rq;
1060
1061         for (;;) {
1062                 /*
1063                  * We do the initial early heuristics without holding
1064                  * any task-queue locks at all. We'll only try to get
1065                  * the runqueue lock when things look like they will
1066                  * work out!
1067                  */
1068                 rq = task_rq(p);
1069
1070                 /*
1071                  * If the task is actively running on another CPU
1072                  * still, just relax and busy-wait without holding
1073                  * any locks.
1074                  *
1075                  * NOTE! Since we don't hold any locks, it's not
1076                  * even sure that "rq" stays as the right runqueue!
1077                  * But we don't care, since "task_running()" will
1078                  * return false if the runqueue has changed and p
1079                  * is actually now running somewhere else!
1080                  */
1081                 while (task_running(rq, p)) {
1082                         if (match_state && unlikely(p->state != match_state))
1083                                 return 0;
1084                         cpu_relax();
1085                 }
1086
1087                 /*
1088                  * Ok, time to look more closely! We need the rq
1089                  * lock now, to be *sure*. If we're wrong, we'll
1090                  * just go back and repeat.
1091                  */
1092                 rq = task_rq_lock(p, &flags);
1093                 trace_sched_wait_task(p);
1094                 running = task_running(rq, p);
1095                 on_rq = p->on_rq;
1096                 ncsw = 0;
1097                 if (!match_state || p->state == match_state)
1098                         ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1099                 task_rq_unlock(rq, p, &flags);
1100
1101                 /*
1102                  * If it changed from the expected state, bail out now.
1103                  */
1104                 if (unlikely(!ncsw))
1105                         break;
1106
1107                 /*
1108                  * Was it really running after all now that we
1109                  * checked with the proper locks actually held?
1110                  *
1111                  * Oops. Go back and try again..
1112                  */
1113                 if (unlikely(running)) {
1114                         cpu_relax();
1115                         continue;
1116                 }
1117
1118                 /*
1119                  * It's not enough that it's not actively running,
1120                  * it must be off the runqueue _entirely_, and not
1121                  * preempted!
1122                  *
1123                  * So if it was still runnable (but just not actively
1124                  * running right now), it's preempted, and we should
1125                  * yield - it could be a while.
1126                  */
1127                 if (unlikely(on_rq)) {
1128                         ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1129
1130                         set_current_state(TASK_UNINTERRUPTIBLE);
1131                         schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1132                         continue;
1133                 }
1134
1135                 /*
1136                  * Ahh, all good. It wasn't running, and it wasn't
1137                  * runnable, which means that it will never become
1138                  * running in the future either. We're all done!
1139                  */
1140                 break;
1141         }
1142
1143         return ncsw;
1144 }
1145
1146 /***
1147  * kick_process - kick a running thread to enter/exit the kernel
1148  * @p: the to-be-kicked thread
1149  *
1150  * Cause a process which is running on another CPU to enter
1151  * kernel-mode, without any delay. (to get signals handled.)
1152  *
1153  * NOTE: this function doesn't have to take the runqueue lock,
1154  * because all it wants to ensure is that the remote task enters
1155  * the kernel. If the IPI races and the task has been migrated
1156  * to another CPU then no harm is done and the purpose has been
1157  * achieved as well.
1158  */
1159 void kick_process(struct task_struct *p)
1160 {
1161         int cpu;
1162
1163         preempt_disable();
1164         cpu = task_cpu(p);
1165         if ((cpu != smp_processor_id()) && task_curr(p))
1166                 smp_send_reschedule(cpu);
1167         preempt_enable();
1168 }
1169 EXPORT_SYMBOL_GPL(kick_process);
1170 #endif /* CONFIG_SMP */
1171
1172 #ifdef CONFIG_SMP
1173 /*
1174  * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1175  */
1176 static int select_fallback_rq(int cpu, struct task_struct *p)
1177 {
1178         int nid = cpu_to_node(cpu);
1179         const struct cpumask *nodemask = NULL;
1180         enum { cpuset, possible, fail } state = cpuset;
1181         int dest_cpu;
1182
1183         /*
1184          * If the node that the cpu is on has been offlined, cpu_to_node()
1185          * will return -1. There is no cpu on the node, and we should
1186          * select the cpu on the other node.
1187          */
1188         if (nid != -1) {
1189                 nodemask = cpumask_of_node(nid);
1190
1191                 /* Look for allowed, online CPU in same node. */
1192                 for_each_cpu(dest_cpu, nodemask) {
1193                         if (!cpu_online(dest_cpu))
1194                                 continue;
1195                         if (!cpu_active(dest_cpu))
1196                                 continue;
1197                         if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1198                                 return dest_cpu;
1199                 }
1200         }
1201
1202         for (;;) {
1203                 /* Any allowed, online CPU? */
1204                 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1205                         if (!cpu_online(dest_cpu))
1206                                 continue;
1207                         if (!cpu_active(dest_cpu))
1208                                 continue;
1209                         goto out;
1210                 }
1211
1212                 switch (state) {
1213                 case cpuset:
1214                         /* No more Mr. Nice Guy. */
1215                         cpuset_cpus_allowed_fallback(p);
1216                         state = possible;
1217                         break;
1218
1219                 case possible:
1220                         do_set_cpus_allowed(p, cpu_possible_mask);
1221                         state = fail;
1222                         break;
1223
1224                 case fail:
1225                         BUG();
1226                         break;
1227                 }
1228         }
1229
1230 out:
1231         if (state != cpuset) {
1232                 /*
1233                  * Don't tell them about moving exiting tasks or
1234                  * kernel threads (both mm NULL), since they never
1235                  * leave kernel.
1236                  */
1237                 if (p->mm && printk_ratelimit()) {
1238                         printk_sched("process %d (%s) no longer affine to cpu%d\n",
1239                                         task_pid_nr(p), p->comm, cpu);
1240                 }
1241         }
1242
1243         return dest_cpu;
1244 }
1245
1246 /*
1247  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1248  */
1249 static inline
1250 int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
1251 {
1252         int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
1253
1254         /*
1255          * In order not to call set_task_cpu() on a blocking task we need
1256          * to rely on ttwu() to place the task on a valid ->cpus_allowed
1257          * cpu.
1258          *
1259          * Since this is common to all placement strategies, this lives here.
1260          *
1261          * [ this allows ->select_task() to simply return task_cpu(p) and
1262          *   not worry about this generic constraint ]
1263          */
1264         if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1265                      !cpu_online(cpu)))
1266                 cpu = select_fallback_rq(task_cpu(p), p);
1267
1268         return cpu;
1269 }
1270
1271 static void update_avg(u64 *avg, u64 sample)
1272 {
1273         s64 diff = sample - *avg;
1274         *avg += diff >> 3;
1275 }
1276 #endif
1277
1278 static void
1279 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1280 {
1281 #ifdef CONFIG_SCHEDSTATS
1282         struct rq *rq = this_rq();
1283
1284 #ifdef CONFIG_SMP
1285         int this_cpu = smp_processor_id();
1286
1287         if (cpu == this_cpu) {
1288                 schedstat_inc(rq, ttwu_local);
1289                 schedstat_inc(p, se.statistics.nr_wakeups_local);
1290         } else {
1291                 struct sched_domain *sd;
1292
1293                 schedstat_inc(p, se.statistics.nr_wakeups_remote);
1294                 rcu_read_lock();
1295                 for_each_domain(this_cpu, sd) {
1296                         if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1297                                 schedstat_inc(sd, ttwu_wake_remote);
1298                                 break;
1299                         }
1300                 }
1301                 rcu_read_unlock();
1302         }
1303
1304         if (wake_flags & WF_MIGRATED)
1305                 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1306
1307 #endif /* CONFIG_SMP */
1308
1309         schedstat_inc(rq, ttwu_count);
1310         schedstat_inc(p, se.statistics.nr_wakeups);
1311
1312         if (wake_flags & WF_SYNC)
1313                 schedstat_inc(p, se.statistics.nr_wakeups_sync);
1314
1315 #endif /* CONFIG_SCHEDSTATS */
1316 }
1317
1318 static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1319 {
1320         activate_task(rq, p, en_flags);
1321         p->on_rq = 1;
1322
1323         /* if a worker is waking up, notify workqueue */
1324         if (p->flags & PF_WQ_WORKER)
1325                 wq_worker_waking_up(p, cpu_of(rq));
1326 }
1327
1328 /*
1329  * Mark the task runnable and perform wakeup-preemption.
1330  */
1331 static void
1332 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
1333 {
1334         check_preempt_curr(rq, p, wake_flags);
1335         trace_sched_wakeup(p, true);
1336
1337         p->state = TASK_RUNNING;
1338 #ifdef CONFIG_SMP
1339         if (p->sched_class->task_woken)
1340                 p->sched_class->task_woken(rq, p);
1341
1342         if (rq->idle_stamp) {
1343                 u64 delta = rq->clock - rq->idle_stamp;
1344                 u64 max = 2*sysctl_sched_migration_cost;
1345
1346                 if (delta > max)
1347                         rq->avg_idle = max;
1348                 else
1349                         update_avg(&rq->avg_idle, delta);
1350                 rq->idle_stamp = 0;
1351         }
1352 #endif
1353 }
1354
1355 static void
1356 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1357 {
1358 #ifdef CONFIG_SMP
1359         if (p->sched_contributes_to_load)
1360                 rq->nr_uninterruptible--;
1361 #endif
1362
1363         ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1364         ttwu_do_wakeup(rq, p, wake_flags);
1365 }
1366
1367 /*
1368  * Called in case the task @p isn't fully descheduled from its runqueue,
1369  * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1370  * since all we need to do is flip p->state to TASK_RUNNING, since
1371  * the task is still ->on_rq.
1372  */
1373 static int ttwu_remote(struct task_struct *p, int wake_flags)
1374 {
1375         struct rq *rq;
1376         int ret = 0;
1377
1378         rq = __task_rq_lock(p);
1379         if (p->on_rq) {
1380                 ttwu_do_wakeup(rq, p, wake_flags);
1381                 ret = 1;
1382         }
1383         __task_rq_unlock(rq);
1384
1385         return ret;
1386 }
1387
1388 #ifdef CONFIG_SMP
1389 static void sched_ttwu_pending(void)
1390 {
1391         struct rq *rq = this_rq();
1392         struct llist_node *llist = llist_del_all(&rq->wake_list);
1393         struct task_struct *p;
1394
1395         raw_spin_lock(&rq->lock);
1396
1397         while (llist) {
1398                 p = llist_entry(llist, struct task_struct, wake_entry);
1399                 llist = llist_next(llist);
1400                 ttwu_do_activate(rq, p, 0);
1401         }
1402
1403         raw_spin_unlock(&rq->lock);
1404 }
1405
1406 void scheduler_ipi(void)
1407 {
1408         if (llist_empty(&this_rq()->wake_list)
1409                         && !tick_nohz_full_cpu(smp_processor_id())
1410                         && !got_nohz_idle_kick())
1411                 return;
1412
1413         /*
1414          * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1415          * traditionally all their work was done from the interrupt return
1416          * path. Now that we actually do some work, we need to make sure
1417          * we do call them.
1418          *
1419          * Some archs already do call them, luckily irq_enter/exit nest
1420          * properly.
1421          *
1422          * Arguably we should visit all archs and update all handlers,
1423          * however a fair share of IPIs are still resched only so this would
1424          * somewhat pessimize the simple resched case.
1425          */
1426         irq_enter();
1427         tick_nohz_full_check();
1428         sched_ttwu_pending();
1429
1430         /*
1431          * Check if someone kicked us for doing the nohz idle load balance.
1432          */
1433         if (unlikely(got_nohz_idle_kick())) {
1434                 this_rq()->idle_balance = 1;
1435                 raise_softirq_irqoff(SCHED_SOFTIRQ);
1436         }
1437         irq_exit();
1438 }
1439
1440 static void ttwu_queue_remote(struct task_struct *p, int cpu)
1441 {
1442         if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
1443                 smp_send_reschedule(cpu);
1444 }
1445
1446 bool cpus_share_cache(int this_cpu, int that_cpu)
1447 {
1448         return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1449 }
1450 #endif /* CONFIG_SMP */
1451
1452 static void ttwu_queue(struct task_struct *p, int cpu)
1453 {
1454         struct rq *rq = cpu_rq(cpu);
1455
1456 #if defined(CONFIG_SMP)
1457         if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1458                 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1459                 ttwu_queue_remote(p, cpu);
1460                 return;
1461         }
1462 #endif
1463
1464         raw_spin_lock(&rq->lock);
1465         ttwu_do_activate(rq, p, 0);
1466         raw_spin_unlock(&rq->lock);
1467 }
1468
1469 /**
1470  * try_to_wake_up - wake up a thread
1471  * @p: the thread to be awakened
1472  * @state: the mask of task states that can be woken
1473  * @wake_flags: wake modifier flags (WF_*)
1474  *
1475  * Put it on the run-queue if it's not already there. The "current"
1476  * thread is always on the run-queue (except when the actual
1477  * re-schedule is in progress), and as such you're allowed to do
1478  * the simpler "current->state = TASK_RUNNING" to mark yourself
1479  * runnable without the overhead of this.
1480  *
1481  * Returns %true if @p was woken up, %false if it was already running
1482  * or @state didn't match @p's state.
1483  */
1484 static int
1485 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1486 {
1487         unsigned long flags;
1488         int cpu, success = 0;
1489
1490         smp_wmb();
1491         raw_spin_lock_irqsave(&p->pi_lock, flags);
1492         if (!(p->state & state))
1493                 goto out;
1494
1495         success = 1; /* we're going to change ->state */
1496         cpu = task_cpu(p);
1497
1498         if (p->on_rq && ttwu_remote(p, wake_flags))
1499                 goto stat;
1500
1501 #ifdef CONFIG_SMP
1502         /*
1503          * If the owning (remote) cpu is still in the middle of schedule() with
1504          * this task as prev, wait until its done referencing the task.
1505          */
1506         while (p->on_cpu)
1507                 cpu_relax();
1508         /*
1509          * Pairs with the smp_wmb() in finish_lock_switch().
1510          */
1511         smp_rmb();
1512
1513         p->sched_contributes_to_load = !!task_contributes_to_load(p);
1514         p->state = TASK_WAKING;
1515
1516         if (p->sched_class->task_waking)
1517                 p->sched_class->task_waking(p);
1518
1519         cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
1520         if (task_cpu(p) != cpu) {
1521                 wake_flags |= WF_MIGRATED;
1522                 set_task_cpu(p, cpu);
1523         }
1524 #endif /* CONFIG_SMP */
1525
1526         ttwu_queue(p, cpu);
1527 stat:
1528         ttwu_stat(p, cpu, wake_flags);
1529 out:
1530         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1531
1532         return success;
1533 }
1534
1535 /**
1536  * try_to_wake_up_local - try to wake up a local task with rq lock held
1537  * @p: the thread to be awakened
1538  *
1539  * Put @p on the run-queue if it's not already there. The caller must
1540  * ensure that this_rq() is locked, @p is bound to this_rq() and not
1541  * the current task.
1542  */
1543 static void try_to_wake_up_local(struct task_struct *p)
1544 {
1545         struct rq *rq = task_rq(p);
1546
1547         if (WARN_ON_ONCE(rq != this_rq()) ||
1548             WARN_ON_ONCE(p == current))
1549                 return;
1550
1551         lockdep_assert_held(&rq->lock);
1552
1553         if (!raw_spin_trylock(&p->pi_lock)) {
1554                 raw_spin_unlock(&rq->lock);
1555                 raw_spin_lock(&p->pi_lock);
1556                 raw_spin_lock(&rq->lock);
1557         }
1558
1559         if (!(p->state & TASK_NORMAL))
1560                 goto out;
1561
1562         if (!p->on_rq)
1563                 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
1564
1565         ttwu_do_wakeup(rq, p, 0);
1566         ttwu_stat(p, smp_processor_id(), 0);
1567 out:
1568         raw_spin_unlock(&p->pi_lock);
1569 }
1570
1571 /**
1572  * wake_up_process - Wake up a specific process
1573  * @p: The process to be woken up.
1574  *
1575  * Attempt to wake up the nominated process and move it to the set of runnable
1576  * processes.  Returns 1 if the process was woken up, 0 if it was already
1577  * running.
1578  *
1579  * It may be assumed that this function implies a write memory barrier before
1580  * changing the task state if and only if any tasks are woken up.
1581  */
1582 int wake_up_process(struct task_struct *p)
1583 {
1584         WARN_ON(task_is_stopped_or_traced(p));
1585         return try_to_wake_up(p, TASK_NORMAL, 0);
1586 }
1587 EXPORT_SYMBOL(wake_up_process);
1588
1589 int wake_up_state(struct task_struct *p, unsigned int state)
1590 {
1591         return try_to_wake_up(p, state, 0);
1592 }
1593
1594 /*
1595  * Perform scheduler related setup for a newly forked process p.
1596  * p is forked by current.
1597  *
1598  * __sched_fork() is basic setup used by init_idle() too:
1599  */
1600 static void __sched_fork(struct task_struct *p)
1601 {
1602         p->on_rq                        = 0;
1603
1604         p->se.on_rq                     = 0;
1605         p->se.exec_start                = 0;
1606         p->se.sum_exec_runtime          = 0;
1607         p->se.prev_sum_exec_runtime     = 0;
1608         p->se.nr_migrations             = 0;
1609         p->se.vruntime                  = 0;
1610         INIT_LIST_HEAD(&p->se.group_node);
1611
1612 /*
1613  * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
1614  * removed when useful for applications beyond shares distribution (e.g.
1615  * load-balance).
1616  */
1617 #if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
1618         p->se.avg.runnable_avg_period = 0;
1619         p->se.avg.runnable_avg_sum = 0;
1620 #ifdef CONFIG_SCHED_HMP
1621         /* keep LOAD_AVG_MAX in sync with fair.c if load avg series is changed */
1622 #define LOAD_AVG_MAX 47742
1623         if (p->mm) {
1624                 p->se.avg.hmp_last_up_migration = 0;
1625                 p->se.avg.hmp_last_down_migration = 0;
1626                 p->se.avg.load_avg_ratio = 1023;
1627                 p->se.avg.load_avg_contrib =
1628                                 (1023 * scale_load_down(p->se.load.weight));
1629                 p->se.avg.runnable_avg_period = LOAD_AVG_MAX;
1630                 p->se.avg.runnable_avg_sum = LOAD_AVG_MAX;
1631                 p->se.avg.usage_avg_sum = LOAD_AVG_MAX;
1632         }
1633 #endif
1634 #endif
1635 #ifdef CONFIG_SCHEDSTATS
1636         memset(&p->se.statistics, 0, sizeof(p->se.statistics));
1637 #endif
1638
1639         INIT_LIST_HEAD(&p->rt.run_list);
1640
1641 #ifdef CONFIG_PREEMPT_NOTIFIERS
1642         INIT_HLIST_HEAD(&p->preempt_notifiers);
1643 #endif
1644
1645 #ifdef CONFIG_NUMA_BALANCING
1646         if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
1647                 p->mm->numa_next_scan = jiffies;
1648                 p->mm->numa_next_reset = jiffies;
1649                 p->mm->numa_scan_seq = 0;
1650         }
1651
1652         p->node_stamp = 0ULL;
1653         p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
1654         p->numa_migrate_seq = p->mm ? p->mm->numa_scan_seq - 1 : 0;
1655         p->numa_scan_period = sysctl_numa_balancing_scan_delay;
1656         p->numa_work.next = &p->numa_work;
1657 #endif /* CONFIG_NUMA_BALANCING */
1658 }
1659
1660 #ifdef CONFIG_NUMA_BALANCING
1661 #ifdef CONFIG_SCHED_DEBUG
1662 void set_numabalancing_state(bool enabled)
1663 {
1664         if (enabled)
1665                 sched_feat_set("NUMA");
1666         else
1667                 sched_feat_set("NO_NUMA");
1668 }
1669 #else
1670 __read_mostly bool numabalancing_enabled;
1671
1672 void set_numabalancing_state(bool enabled)
1673 {
1674         numabalancing_enabled = enabled;
1675 }
1676 #endif /* CONFIG_SCHED_DEBUG */
1677 #endif /* CONFIG_NUMA_BALANCING */
1678
1679 /*
1680  * fork()/clone()-time setup:
1681  */
1682 void sched_fork(struct task_struct *p)
1683 {
1684         unsigned long flags;
1685         int cpu = get_cpu();
1686
1687         __sched_fork(p);
1688         /*
1689          * We mark the process as running here. This guarantees that
1690          * nobody will actually run it, and a signal or other external
1691          * event cannot wake it up and insert it on the runqueue either.
1692          */
1693         p->state = TASK_RUNNING;
1694
1695         /*
1696          * Make sure we do not leak PI boosting priority to the child.
1697          */
1698         p->prio = current->normal_prio;
1699
1700         /*
1701          * Revert to default priority/policy on fork if requested.
1702          */
1703         if (unlikely(p->sched_reset_on_fork)) {
1704                 if (task_has_rt_policy(p)) {
1705                         p->policy = SCHED_NORMAL;
1706                         p->static_prio = NICE_TO_PRIO(0);
1707                         p->rt_priority = 0;
1708                 } else if (PRIO_TO_NICE(p->static_prio) < 0)
1709                         p->static_prio = NICE_TO_PRIO(0);
1710
1711                 p->prio = p->normal_prio = __normal_prio(p);
1712                 set_load_weight(p);
1713
1714                 /*
1715                  * We don't need the reset flag anymore after the fork. It has
1716                  * fulfilled its duty:
1717                  */
1718                 p->sched_reset_on_fork = 0;
1719         }
1720
1721         if (!rt_prio(p->prio))
1722                 p->sched_class = &fair_sched_class;
1723
1724         if (p->sched_class->task_fork)
1725                 p->sched_class->task_fork(p);
1726
1727         /*
1728          * The child is not yet in the pid-hash so no cgroup attach races,
1729          * and the cgroup is pinned to this child due to cgroup_fork()
1730          * is ran before sched_fork().
1731          *
1732          * Silence PROVE_RCU.
1733          */
1734         raw_spin_lock_irqsave(&p->pi_lock, flags);
1735         set_task_cpu(p, cpu);
1736         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1737
1738 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1739         if (likely(sched_info_on()))
1740                 memset(&p->sched_info, 0, sizeof(p->sched_info));
1741 #endif
1742 #if defined(CONFIG_SMP)
1743         p->on_cpu = 0;
1744 #endif
1745 #ifdef CONFIG_PREEMPT_COUNT
1746         /* Want to start with kernel preemption disabled. */
1747         task_thread_info(p)->preempt_count = 1;
1748 #endif
1749 #ifdef CONFIG_SMP
1750         plist_node_init(&p->pushable_tasks, MAX_PRIO);
1751 #endif
1752
1753         put_cpu();
1754 }
1755
1756 /*
1757  * wake_up_new_task - wake up a newly created task for the first time.
1758  *
1759  * This function will do some initial scheduler statistics housekeeping
1760  * that must be done for every newly created context, then puts the task
1761  * on the runqueue and wakes it.
1762  */
1763 void wake_up_new_task(struct task_struct *p)
1764 {
1765         unsigned long flags;
1766         struct rq *rq;
1767
1768         raw_spin_lock_irqsave(&p->pi_lock, flags);
1769 #ifdef CONFIG_SMP
1770         /*
1771          * Fork balancing, do it here and not earlier because:
1772          *  - cpus_allowed can change in the fork path
1773          *  - any previously selected cpu might disappear through hotplug
1774          */
1775         set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
1776 #endif
1777
1778         rq = __task_rq_lock(p);
1779         activate_task(rq, p, 0);
1780         p->on_rq = 1;
1781         trace_sched_wakeup_new(p, true);
1782         check_preempt_curr(rq, p, WF_FORK);
1783 #ifdef CONFIG_SMP
1784         if (p->sched_class->task_woken)
1785                 p->sched_class->task_woken(rq, p);
1786 #endif
1787         task_rq_unlock(rq, p, &flags);
1788 }
1789
1790 #ifdef CONFIG_PREEMPT_NOTIFIERS
1791
1792 /**
1793  * preempt_notifier_register - tell me when current is being preempted & rescheduled
1794  * @notifier: notifier struct to register
1795  */
1796 void preempt_notifier_register(struct preempt_notifier *notifier)
1797 {
1798         hlist_add_head(&notifier->link, &current->preempt_notifiers);
1799 }
1800 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1801
1802 /**
1803  * preempt_notifier_unregister - no longer interested in preemption notifications
1804  * @notifier: notifier struct to unregister
1805  *
1806  * This is safe to call from within a preemption notifier.
1807  */
1808 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1809 {
1810         hlist_del(&notifier->link);
1811 }
1812 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1813
1814 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1815 {
1816         struct preempt_notifier *notifier;
1817
1818         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
1819                 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1820 }
1821
1822 static void
1823 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1824                                  struct task_struct *next)
1825 {
1826         struct preempt_notifier *notifier;
1827
1828         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
1829                 notifier->ops->sched_out(notifier, next);
1830 }
1831
1832 #else /* !CONFIG_PREEMPT_NOTIFIERS */
1833
1834 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1835 {
1836 }
1837
1838 static void
1839 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1840                                  struct task_struct *next)
1841 {
1842 }
1843
1844 #endif /* CONFIG_PREEMPT_NOTIFIERS */
1845
1846 /**
1847  * prepare_task_switch - prepare to switch tasks
1848  * @rq: the runqueue preparing to switch
1849  * @prev: the current task that is being switched out
1850  * @next: the task we are going to switch to.
1851  *
1852  * This is called with the rq lock held and interrupts off. It must
1853  * be paired with a subsequent finish_task_switch after the context
1854  * switch.
1855  *
1856  * prepare_task_switch sets up locking and calls architecture specific
1857  * hooks.
1858  */
1859 static inline void
1860 prepare_task_switch(struct rq *rq, struct task_struct *prev,
1861                     struct task_struct *next)
1862 {
1863         trace_sched_switch(prev, next);
1864         sched_info_switch(prev, next);
1865         perf_event_task_sched_out(prev, next);
1866         fire_sched_out_preempt_notifiers(prev, next);
1867         prepare_lock_switch(rq, next);
1868         prepare_arch_switch(next);
1869 }
1870
1871 /**
1872  * finish_task_switch - clean up after a task-switch
1873  * @rq: runqueue associated with task-switch
1874  * @prev: the thread we just switched away from.
1875  *
1876  * finish_task_switch must be called after the context switch, paired
1877  * with a prepare_task_switch call before the context switch.
1878  * finish_task_switch will reconcile locking set up by prepare_task_switch,
1879  * and do any other architecture-specific cleanup actions.
1880  *
1881  * Note that we may have delayed dropping an mm in context_switch(). If
1882  * so, we finish that here outside of the runqueue lock. (Doing it
1883  * with the lock held can cause deadlocks; see schedule() for
1884  * details.)
1885  */
1886 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1887         __releases(rq->lock)
1888 {
1889         struct mm_struct *mm = rq->prev_mm;
1890         long prev_state;
1891
1892         rq->prev_mm = NULL;
1893
1894         /*
1895          * A task struct has one reference for the use as "current".
1896          * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1897          * schedule one last time. The schedule call will never return, and
1898          * the scheduled task must drop that reference.
1899          * The test for TASK_DEAD must occur while the runqueue locks are
1900          * still held, otherwise prev could be scheduled on another cpu, die
1901          * there before we look at prev->state, and then the reference would
1902          * be dropped twice.
1903          *              Manfred Spraul <manfred@colorfullife.com>
1904          */
1905         prev_state = prev->state;
1906         vtime_task_switch(prev);
1907         finish_arch_switch(prev);
1908         perf_event_task_sched_in(prev, current);
1909         finish_lock_switch(rq, prev);
1910         finish_arch_post_lock_switch();
1911
1912         fire_sched_in_preempt_notifiers(current);
1913         if (mm)
1914                 mmdrop(mm);
1915         if (unlikely(prev_state == TASK_DEAD)) {
1916                 /*
1917                  * Remove function-return probe instances associated with this
1918                  * task and put them back on the free list.
1919                  */
1920                 kprobe_flush_task(prev);
1921                 put_task_struct(prev);
1922         }
1923
1924         tick_nohz_task_switch(current);
1925 }
1926
1927 #ifdef CONFIG_SMP
1928
1929 /* assumes rq->lock is held */
1930 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
1931 {
1932         if (prev->sched_class->pre_schedule)
1933                 prev->sched_class->pre_schedule(rq, prev);
1934 }
1935
1936 /* rq->lock is NOT held, but preemption is disabled */
1937 static inline void post_schedule(struct rq *rq)
1938 {
1939         if (rq->post_schedule) {
1940                 unsigned long flags;
1941
1942                 raw_spin_lock_irqsave(&rq->lock, flags);
1943                 if (rq->curr->sched_class->post_schedule)
1944                         rq->curr->sched_class->post_schedule(rq);
1945                 raw_spin_unlock_irqrestore(&rq->lock, flags);
1946
1947                 rq->post_schedule = 0;
1948         }
1949 }
1950
1951 #else
1952
1953 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
1954 {
1955 }
1956
1957 static inline void post_schedule(struct rq *rq)
1958 {
1959 }
1960
1961 #endif
1962
1963 /**
1964  * schedule_tail - first thing a freshly forked thread must call.
1965  * @prev: the thread we just switched away from.
1966  */
1967 asmlinkage void schedule_tail(struct task_struct *prev)
1968         __releases(rq->lock)
1969 {
1970         struct rq *rq = this_rq();
1971
1972         finish_task_switch(rq, prev);
1973
1974         /*
1975          * FIXME: do we need to worry about rq being invalidated by the
1976          * task_switch?
1977          */
1978         post_schedule(rq);
1979
1980 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1981         /* In this case, finish_task_switch does not reenable preemption */
1982         preempt_enable();
1983 #endif
1984         if (current->set_child_tid)
1985                 put_user(task_pid_vnr(current), current->set_child_tid);
1986 }
1987
1988 /*
1989  * context_switch - switch to the new MM and the new
1990  * thread's register state.
1991  */
1992 static inline void
1993 context_switch(struct rq *rq, struct task_struct *prev,
1994                struct task_struct *next)
1995 {
1996         struct mm_struct *mm, *oldmm;
1997
1998         prepare_task_switch(rq, prev, next);
1999
2000         mm = next->mm;
2001         oldmm = prev->active_mm;
2002         /*
2003          * For paravirt, this is coupled with an exit in switch_to to
2004          * combine the page table reload and the switch backend into
2005          * one hypercall.
2006          */
2007         arch_start_context_switch(prev);
2008
2009         if (!mm) {
2010                 next->active_mm = oldmm;
2011                 atomic_inc(&oldmm->mm_count);
2012                 enter_lazy_tlb(oldmm, next);
2013         } else
2014                 switch_mm(oldmm, mm, next);
2015
2016         if (!prev->mm) {
2017                 prev->active_mm = NULL;
2018                 rq->prev_mm = oldmm;
2019         }
2020         /*
2021          * Since the runqueue lock will be released by the next
2022          * task (which is an invalid locking op but in the case
2023          * of the scheduler it's an obvious special-case), so we
2024          * do an early lockdep release here:
2025          */
2026 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2027         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2028 #endif
2029
2030         context_tracking_task_switch(prev, next);
2031         /* Here we just switch the register state and the stack. */
2032         switch_to(prev, next, prev);
2033
2034         barrier();
2035         /*
2036          * this_rq must be evaluated again because prev may have moved
2037          * CPUs since it called schedule(), thus the 'rq' on its stack
2038          * frame will be invalid.
2039          */
2040         finish_task_switch(this_rq(), prev);
2041 }
2042
2043 /*
2044  * nr_running and nr_context_switches:
2045  *
2046  * externally visible scheduler statistics: current number of runnable
2047  * threads, total number of context switches performed since bootup.
2048  */
2049 unsigned long nr_running(void)
2050 {
2051         unsigned long i, sum = 0;
2052
2053         for_each_online_cpu(i)
2054                 sum += cpu_rq(i)->nr_running;
2055
2056         return sum;
2057 }
2058
2059 unsigned long long nr_context_switches(void)
2060 {
2061         int i;
2062         unsigned long long sum = 0;
2063
2064         for_each_possible_cpu(i)
2065                 sum += cpu_rq(i)->nr_switches;
2066
2067         return sum;
2068 }
2069
2070 unsigned long nr_iowait(void)
2071 {
2072         unsigned long i, sum = 0;
2073
2074         for_each_possible_cpu(i)
2075                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2076
2077         return sum;
2078 }
2079
2080 unsigned long nr_iowait_cpu(int cpu)
2081 {
2082         struct rq *this = cpu_rq(cpu);
2083         return atomic_read(&this->nr_iowait);
2084 }
2085
2086 unsigned long this_cpu_load(void)
2087 {
2088         struct rq *this = this_rq();
2089         return this->cpu_load[0];
2090 }
2091
2092
2093 /*
2094  * Global load-average calculations
2095  *
2096  * We take a distributed and async approach to calculating the global load-avg
2097  * in order to minimize overhead.
2098  *
2099  * The global load average is an exponentially decaying average of nr_running +
2100  * nr_uninterruptible.
2101  *
2102  * Once every LOAD_FREQ:
2103  *
2104  *   nr_active = 0;
2105  *   for_each_possible_cpu(cpu)
2106  *      nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
2107  *
2108  *   avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
2109  *
2110  * Due to a number of reasons the above turns in the mess below:
2111  *
2112  *  - for_each_possible_cpu() is prohibitively expensive on machines with
2113  *    serious number of cpus, therefore we need to take a distributed approach
2114  *    to calculating nr_active.
2115  *
2116  *        \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
2117  *                      = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
2118  *
2119  *    So assuming nr_active := 0 when we start out -- true per definition, we
2120  *    can simply take per-cpu deltas and fold those into a global accumulate
2121  *    to obtain the same result. See calc_load_fold_active().
2122  *
2123  *    Furthermore, in order to avoid synchronizing all per-cpu delta folding
2124  *    across the machine, we assume 10 ticks is sufficient time for every
2125  *    cpu to have completed this task.
2126  *
2127  *    This places an upper-bound on the IRQ-off latency of the machine. Then
2128  *    again, being late doesn't loose the delta, just wrecks the sample.
2129  *
2130  *  - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
2131  *    this would add another cross-cpu cacheline miss and atomic operation
2132  *    to the wakeup path. Instead we increment on whatever cpu the task ran
2133  *    when it went into uninterruptible state and decrement on whatever cpu
2134  *    did the wakeup. This means that only the sum of nr_uninterruptible over
2135  *    all cpus yields the correct result.
2136  *
2137  *  This covers the NO_HZ=n code, for extra head-aches, see the comment below.
2138  */
2139
2140 /* Variables and functions for calc_load */
2141 static atomic_long_t calc_load_tasks;
2142 static unsigned long calc_load_update;
2143 unsigned long avenrun[3];
2144 EXPORT_SYMBOL(avenrun); /* should be removed */
2145
2146 /**
2147  * get_avenrun - get the load average array
2148  * @loads:      pointer to dest load array
2149  * @offset:     offset to add
2150  * @shift:      shift count to shift the result left
2151  *
2152  * These values are estimates at best, so no need for locking.
2153  */
2154 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
2155 {
2156         loads[0] = (avenrun[0] + offset) << shift;
2157         loads[1] = (avenrun[1] + offset) << shift;
2158         loads[2] = (avenrun[2] + offset) << shift;
2159 }
2160
2161 static long calc_load_fold_active(struct rq *this_rq)
2162 {
2163         long nr_active, delta = 0;
2164
2165         nr_active = this_rq->nr_running;
2166         nr_active += (long) this_rq->nr_uninterruptible;
2167
2168         if (nr_active != this_rq->calc_load_active) {
2169                 delta = nr_active - this_rq->calc_load_active;
2170                 this_rq->calc_load_active = nr_active;
2171         }
2172
2173         return delta;
2174 }
2175
2176 /*
2177  * a1 = a0 * e + a * (1 - e)
2178  */
2179 static unsigned long
2180 calc_load(unsigned long load, unsigned long exp, unsigned long active)
2181 {
2182         load *= exp;
2183         load += active * (FIXED_1 - exp);
2184         load += 1UL << (FSHIFT - 1);
2185         return load >> FSHIFT;
2186 }
2187
2188 #ifdef CONFIG_NO_HZ_COMMON
2189 /*
2190  * Handle NO_HZ for the global load-average.
2191  *
2192  * Since the above described distributed algorithm to compute the global
2193  * load-average relies on per-cpu sampling from the tick, it is affected by
2194  * NO_HZ.
2195  *
2196  * The basic idea is to fold the nr_active delta into a global idle-delta upon
2197  * entering NO_HZ state such that we can include this as an 'extra' cpu delta
2198  * when we read the global state.
2199  *
2200  * Obviously reality has to ruin such a delightfully simple scheme:
2201  *
2202  *  - When we go NO_HZ idle during the window, we can negate our sample
2203  *    contribution, causing under-accounting.
2204  *
2205  *    We avoid this by keeping two idle-delta counters and flipping them
2206  *    when the window starts, thus separating old and new NO_HZ load.
2207  *
2208  *    The only trick is the slight shift in index flip for read vs write.
2209  *
2210  *        0s            5s            10s           15s
2211  *          +10           +10           +10           +10
2212  *        |-|-----------|-|-----------|-|-----------|-|
2213  *    r:0 0 1           1 0           0 1           1 0
2214  *    w:0 1 1           0 0           1 1           0 0
2215  *
2216  *    This ensures we'll fold the old idle contribution in this window while
2217  *    accumlating the new one.
2218  *
2219  *  - When we wake up from NO_HZ idle during the window, we push up our
2220  *    contribution, since we effectively move our sample point to a known
2221  *    busy state.
2222  *
2223  *    This is solved by pushing the window forward, and thus skipping the
2224  *    sample, for this cpu (effectively using the idle-delta for this cpu which
2225  *    was in effect at the time the window opened). This also solves the issue
2226  *    of having to deal with a cpu having been in NOHZ idle for multiple
2227  *    LOAD_FREQ intervals.
2228  *
2229  * When making the ILB scale, we should try to pull this in as well.
2230  */
2231 static atomic_long_t calc_load_idle[2];
2232 static int calc_load_idx;
2233
2234 static inline int calc_load_write_idx(void)
2235 {
2236         int idx = calc_load_idx;
2237
2238         /*
2239          * See calc_global_nohz(), if we observe the new index, we also
2240          * need to observe the new update time.
2241          */
2242         smp_rmb();
2243
2244         /*
2245          * If the folding window started, make sure we start writing in the
2246          * next idle-delta.
2247          */
2248         if (!time_before(jiffies, calc_load_update))
2249                 idx++;
2250
2251         return idx & 1;
2252 }
2253
2254 static inline int calc_load_read_idx(void)
2255 {
2256         return calc_load_idx & 1;
2257 }
2258
2259 void calc_load_enter_idle(void)
2260 {
2261         struct rq *this_rq = this_rq();
2262         long delta;
2263
2264         /*
2265          * We're going into NOHZ mode, if there's any pending delta, fold it
2266          * into the pending idle delta.
2267          */
2268         delta = calc_load_fold_active(this_rq);
2269         if (delta) {
2270                 int idx = calc_load_write_idx();
2271                 atomic_long_add(delta, &calc_load_idle[idx]);
2272         }
2273 }
2274
2275 void calc_load_exit_idle(void)
2276 {
2277         struct rq *this_rq = this_rq();
2278
2279         /*
2280          * If we're still before the sample window, we're done.
2281          */
2282         if (time_before(jiffies, this_rq->calc_load_update))
2283                 return;
2284
2285         /*
2286          * We woke inside or after the sample window, this means we're already
2287          * accounted through the nohz accounting, so skip the entire deal and
2288          * sync up for the next window.
2289          */
2290         this_rq->calc_load_update = calc_load_update;
2291         if (time_before(jiffies, this_rq->calc_load_update + 10))
2292                 this_rq->calc_load_update += LOAD_FREQ;
2293 }
2294
2295 static long calc_load_fold_idle(void)
2296 {
2297         int idx = calc_load_read_idx();
2298         long delta = 0;
2299
2300         if (atomic_long_read(&calc_load_idle[idx]))
2301                 delta = atomic_long_xchg(&calc_load_idle[idx], 0);
2302
2303         return delta;
2304 }
2305
2306 /**
2307  * fixed_power_int - compute: x^n, in O(log n) time
2308  *
2309  * @x:         base of the power
2310  * @frac_bits: fractional bits of @x
2311  * @n:         power to raise @x to.
2312  *
2313  * By exploiting the relation between the definition of the natural power
2314  * function: x^n := x*x*...*x (x multiplied by itself for n times), and
2315  * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
2316  * (where: n_i \elem {0, 1}, the binary vector representing n),
2317  * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
2318  * of course trivially computable in O(log_2 n), the length of our binary
2319  * vector.
2320  */
2321 static unsigned long
2322 fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
2323 {
2324         unsigned long result = 1UL << frac_bits;
2325
2326         if (n) for (;;) {
2327                 if (n & 1) {
2328                         result *= x;
2329                         result += 1UL << (frac_bits - 1);
2330                         result >>= frac_bits;
2331                 }
2332                 n >>= 1;
2333                 if (!n)
2334                         break;
2335                 x *= x;
2336                 x += 1UL << (frac_bits - 1);
2337                 x >>= frac_bits;
2338         }
2339
2340         return result;
2341 }
2342
2343 /*
2344  * a1 = a0 * e + a * (1 - e)
2345  *
2346  * a2 = a1 * e + a * (1 - e)
2347  *    = (a0 * e + a * (1 - e)) * e + a * (1 - e)
2348  *    = a0 * e^2 + a * (1 - e) * (1 + e)
2349  *
2350  * a3 = a2 * e + a * (1 - e)
2351  *    = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
2352  *    = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
2353  *
2354  *  ...
2355  *
2356  * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
2357  *    = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
2358  *    = a0 * e^n + a * (1 - e^n)
2359  *
2360  * [1] application of the geometric series:
2361  *
2362  *              n         1 - x^(n+1)
2363  *     S_n := \Sum x^i = -------------
2364  *             i=0          1 - x
2365  */
2366 static unsigned long
2367 calc_load_n(unsigned long load, unsigned long exp,
2368             unsigned long active, unsigned int n)
2369 {
2370
2371         return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
2372 }
2373
2374 /*
2375  * NO_HZ can leave us missing all per-cpu ticks calling
2376  * calc_load_account_active(), but since an idle CPU folds its delta into
2377  * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
2378  * in the pending idle delta if our idle period crossed a load cycle boundary.
2379  *
2380  * Once we've updated the global active value, we need to apply the exponential
2381  * weights adjusted to the number of cycles missed.
2382  */
2383 static void calc_global_nohz(void)
2384 {
2385         long delta, active, n;
2386
2387         if (!time_before(jiffies, calc_load_update + 10)) {
2388                 /*
2389                  * Catch-up, fold however many we are behind still
2390                  */
2391                 delta = jiffies - calc_load_update - 10;
2392                 n = 1 + (delta / LOAD_FREQ);
2393
2394                 active = atomic_long_read(&calc_load_tasks);
2395                 active = active > 0 ? active * FIXED_1 : 0;
2396
2397                 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
2398                 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
2399                 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
2400
2401                 calc_load_update += n * LOAD_FREQ;
2402         }
2403
2404         /*
2405          * Flip the idle index...
2406          *
2407          * Make sure we first write the new time then flip the index, so that
2408          * calc_load_write_idx() will see the new time when it reads the new
2409          * index, this avoids a double flip messing things up.
2410          */
2411         smp_wmb();
2412         calc_load_idx++;
2413 }
2414 #else /* !CONFIG_NO_HZ_COMMON */
2415
2416 static inline long calc_load_fold_idle(void) { return 0; }
2417 static inline void calc_global_nohz(void) { }
2418
2419 #endif /* CONFIG_NO_HZ_COMMON */
2420
2421 /*
2422  * calc_load - update the avenrun load estimates 10 ticks after the
2423  * CPUs have updated calc_load_tasks.
2424  */
2425 void calc_global_load(unsigned long ticks)
2426 {
2427         long active, delta;
2428
2429         if (time_before(jiffies, calc_load_update + 10))
2430                 return;
2431
2432         /*
2433          * Fold the 'old' idle-delta to include all NO_HZ cpus.
2434          */
2435         delta = calc_load_fold_idle();
2436         if (delta)
2437                 atomic_long_add(delta, &calc_load_tasks);
2438
2439         active = atomic_long_read(&calc_load_tasks);
2440         active = active > 0 ? active * FIXED_1 : 0;
2441
2442         avenrun[0] = calc_load(avenrun[0], EXP_1, active);
2443         avenrun[1] = calc_load(avenrun[1], EXP_5, active);
2444         avenrun[2] = calc_load(avenrun[2], EXP_15, active);
2445
2446         calc_load_update += LOAD_FREQ;
2447
2448         /*
2449          * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk.
2450          */
2451         calc_global_nohz();
2452 }
2453
2454 /*
2455  * Called from update_cpu_load() to periodically update this CPU's
2456  * active count.
2457  */
2458 static void calc_load_account_active(struct rq *this_rq)
2459 {
2460         long delta;
2461
2462         if (time_before(jiffies, this_rq->calc_load_update))
2463                 return;
2464
2465         delta  = calc_load_fold_active(this_rq);
2466         if (delta)
2467                 atomic_long_add(delta, &calc_load_tasks);
2468
2469         this_rq->calc_load_update += LOAD_FREQ;
2470 }
2471
2472 /*
2473  * End of global load-average stuff
2474  */
2475
2476 /*
2477  * The exact cpuload at various idx values, calculated at every tick would be
2478  * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
2479  *
2480  * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
2481  * on nth tick when cpu may be busy, then we have:
2482  * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2483  * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
2484  *
2485  * decay_load_missed() below does efficient calculation of
2486  * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2487  * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
2488  *
2489  * The calculation is approximated on a 128 point scale.
2490  * degrade_zero_ticks is the number of ticks after which load at any
2491  * particular idx is approximated to be zero.
2492  * degrade_factor is a precomputed table, a row for each load idx.
2493  * Each column corresponds to degradation factor for a power of two ticks,
2494  * based on 128 point scale.
2495  * Example:
2496  * row 2, col 3 (=12) says that the degradation at load idx 2 after
2497  * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
2498  *
2499  * With this power of 2 load factors, we can degrade the load n times
2500  * by looking at 1 bits in n and doing as many mult/shift instead of
2501  * n mult/shifts needed by the exact degradation.
2502  */
2503 #define DEGRADE_SHIFT           7
2504 static const unsigned char
2505                 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
2506 static const unsigned char
2507                 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
2508                                         {0, 0, 0, 0, 0, 0, 0, 0},
2509                                         {64, 32, 8, 0, 0, 0, 0, 0},
2510                                         {96, 72, 40, 12, 1, 0, 0},
2511                                         {112, 98, 75, 43, 15, 1, 0},
2512                                         {120, 112, 98, 76, 45, 16, 2} };
2513
2514 /*
2515  * Update cpu_load for any missed ticks, due to tickless idle. The backlog
2516  * would be when CPU is idle and so we just decay the old load without
2517  * adding any new load.
2518  */
2519 static unsigned long
2520 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
2521 {
2522         int j = 0;
2523
2524         if (!missed_updates)
2525                 return load;
2526
2527         if (missed_updates >= degrade_zero_ticks[idx])
2528                 return 0;
2529
2530         if (idx == 1)
2531                 return load >> missed_updates;
2532
2533         while (missed_updates) {
2534                 if (missed_updates % 2)
2535                         load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
2536
2537                 missed_updates >>= 1;
2538                 j++;
2539         }
2540         return load;
2541 }
2542
2543 /*
2544  * Update rq->cpu_load[] statistics. This function is usually called every
2545  * scheduler tick (TICK_NSEC). With tickless idle this will not be called
2546  * every tick. We fix it up based on jiffies.
2547  */
2548 static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
2549                               unsigned long pending_updates)
2550 {
2551         int i, scale;
2552
2553         this_rq->nr_load_updates++;
2554
2555         /* Update our load: */
2556         this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
2557         for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2558                 unsigned long old_load, new_load;
2559
2560                 /* scale is effectively 1 << i now, and >> i divides by scale */
2561
2562                 old_load = this_rq->cpu_load[i];
2563                 old_load = decay_load_missed(old_load, pending_updates - 1, i);
2564                 new_load = this_load;
2565                 /*
2566                  * Round up the averaging division if load is increasing. This
2567                  * prevents us from getting stuck on 9 if the load is 10, for
2568                  * example.
2569                  */
2570                 if (new_load > old_load)
2571                         new_load += scale - 1;
2572
2573                 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
2574         }
2575
2576         sched_avg_update(this_rq);
2577 }
2578
2579 #ifdef CONFIG_NO_HZ_COMMON
2580 /*
2581  * There is no sane way to deal with nohz on smp when using jiffies because the
2582  * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
2583  * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
2584  *
2585  * Therefore we cannot use the delta approach from the regular tick since that
2586  * would seriously skew the load calculation. However we'll make do for those
2587  * updates happening while idle (nohz_idle_balance) or coming out of idle
2588  * (tick_nohz_idle_exit).
2589  *
2590  * This means we might still be one tick off for nohz periods.
2591  */
2592
2593 /*
2594  * Called from nohz_idle_balance() to update the load ratings before doing the
2595  * idle balance.
2596  */
2597 void update_idle_cpu_load(struct rq *this_rq)
2598 {
2599         unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2600         unsigned long load = this_rq->load.weight;
2601         unsigned long pending_updates;
2602
2603         /*
2604          * bail if there's load or we're actually up-to-date.
2605          */
2606         if (load || curr_jiffies == this_rq->last_load_update_tick)
2607                 return;
2608
2609         pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2610         this_rq->last_load_update_tick = curr_jiffies;
2611
2612         __update_cpu_load(this_rq, load, pending_updates);
2613 }
2614
2615 /*
2616  * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
2617  */
2618 void update_cpu_load_nohz(void)
2619 {
2620         struct rq *this_rq = this_rq();
2621         unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2622         unsigned long pending_updates;
2623
2624         if (curr_jiffies == this_rq->last_load_update_tick)
2625                 return;
2626
2627         raw_spin_lock(&this_rq->lock);
2628         pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2629         if (pending_updates) {
2630                 this_rq->last_load_update_tick = curr_jiffies;
2631                 /*
2632                  * We were idle, this means load 0, the current load might be
2633                  * !0 due to remote wakeups and the sort.
2634                  */
2635                 __update_cpu_load(this_rq, 0, pending_updates);
2636         }
2637         raw_spin_unlock(&this_rq->lock);
2638 }
2639 #endif /* CONFIG_NO_HZ_COMMON */
2640
2641 /*
2642  * Called from scheduler_tick()
2643  */
2644 static void update_cpu_load_active(struct rq *this_rq)
2645 {
2646         /*
2647          * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
2648          */
2649         this_rq->last_load_update_tick = jiffies;
2650         __update_cpu_load(this_rq, this_rq->load.weight, 1);
2651
2652         calc_load_account_active(this_rq);
2653 }
2654
2655 #ifdef CONFIG_SMP
2656
2657 /*
2658  * sched_exec - execve() is a valuable balancing opportunity, because at
2659  * this point the task has the smallest effective memory and cache footprint.
2660  */
2661 void sched_exec(void)
2662 {
2663         struct task_struct *p = current;
2664         unsigned long flags;
2665         int dest_cpu;
2666
2667         raw_spin_lock_irqsave(&p->pi_lock, flags);
2668         dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
2669         if (dest_cpu == smp_processor_id())
2670                 goto unlock;
2671
2672         if (likely(cpu_active(dest_cpu))) {
2673                 struct migration_arg arg = { p, dest_cpu };
2674
2675                 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2676                 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2677                 return;
2678         }
2679 unlock:
2680         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2681 }
2682
2683 #endif
2684
2685 DEFINE_PER_CPU(struct kernel_stat, kstat);
2686 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2687
2688 EXPORT_PER_CPU_SYMBOL(kstat);
2689 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2690
2691 /*
2692  * Return any ns on the sched_clock that have not yet been accounted in
2693  * @p in case that task is currently running.
2694  *
2695  * Called with task_rq_lock() held on @rq.
2696  */
2697 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
2698 {
2699         u64 ns = 0;
2700
2701         if (task_current(rq, p)) {
2702                 update_rq_clock(rq);
2703                 ns = rq->clock_task - p->se.exec_start;
2704                 if ((s64)ns < 0)
2705                         ns = 0;
2706         }
2707
2708         return ns;
2709 }
2710
2711 unsigned long long task_delta_exec(struct task_struct *p)
2712 {
2713         unsigned long flags;
2714         struct rq *rq;
2715         u64 ns = 0;
2716
2717         rq = task_rq_lock(p, &flags);
2718         ns = do_task_delta_exec(p, rq);
2719         task_rq_unlock(rq, p, &flags);
2720
2721         return ns;
2722 }
2723
2724 /*
2725  * Return accounted runtime for the task.
2726  * In case the task is currently running, return the runtime plus current's
2727  * pending runtime that have not been accounted yet.
2728  */
2729 unsigned long long task_sched_runtime(struct task_struct *p)
2730 {
2731         unsigned long flags;
2732         struct rq *rq;
2733         u64 ns = 0;
2734
2735         rq = task_rq_lock(p, &flags);
2736         ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
2737         task_rq_unlock(rq, p, &flags);
2738
2739         return ns;
2740 }
2741
2742 /*
2743  * This function gets called by the timer code, with HZ frequency.
2744  * We call it with interrupts disabled.
2745  */
2746 void scheduler_tick(void)
2747 {
2748         int cpu = smp_processor_id();
2749         struct rq *rq = cpu_rq(cpu);
2750         struct task_struct *curr = rq->curr;
2751
2752         sched_clock_tick();
2753
2754         raw_spin_lock(&rq->lock);
2755         update_rq_clock(rq);
2756         update_cpu_load_active(rq);
2757         curr->sched_class->task_tick(rq, curr, 0);
2758         raw_spin_unlock(&rq->lock);
2759
2760         perf_event_task_tick();
2761
2762 #ifdef CONFIG_SMP
2763         rq->idle_balance = idle_cpu(cpu);
2764         trigger_load_balance(rq, cpu);
2765 #endif
2766         rq_last_tick_reset(rq);
2767 }
2768
2769 #ifdef CONFIG_NO_HZ_FULL
2770 /**
2771  * scheduler_tick_max_deferment
2772  *
2773  * Keep at least one tick per second when a single
2774  * active task is running because the scheduler doesn't
2775  * yet completely support full dynticks environment.
2776  *
2777  * This makes sure that uptime, CFS vruntime, load
2778  * balancing, etc... continue to move forward, even
2779  * with a very low granularity.
2780  */
2781 u64 scheduler_tick_max_deferment(void)
2782 {
2783         struct rq *rq = this_rq();
2784         unsigned long next, now = ACCESS_ONCE(jiffies);
2785
2786         next = rq->last_sched_tick + HZ;
2787
2788         if (time_before_eq(next, now))
2789                 return 0;
2790
2791         return jiffies_to_usecs(next - now) * NSEC_PER_USEC;
2792 }
2793 #endif
2794
2795 notrace unsigned long get_parent_ip(unsigned long addr)
2796 {
2797         if (in_lock_functions(addr)) {
2798                 addr = CALLER_ADDR2;
2799                 if (in_lock_functions(addr))
2800                         addr = CALLER_ADDR3;
2801         }
2802         return addr;
2803 }
2804
2805 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
2806                                 defined(CONFIG_PREEMPT_TRACER))
2807
2808 void __kprobes add_preempt_count(int val)
2809 {
2810 #ifdef CONFIG_DEBUG_PREEMPT
2811         /*
2812          * Underflow?
2813          */
2814         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
2815                 return;
2816 #endif
2817         preempt_count() += val;
2818 #ifdef CONFIG_DEBUG_PREEMPT
2819         /*
2820          * Spinlock count overflowing soon?
2821          */
2822         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
2823                                 PREEMPT_MASK - 10);
2824 #endif
2825         if (preempt_count() == val)
2826                 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
2827 }
2828 EXPORT_SYMBOL(add_preempt_count);
2829
2830 void __kprobes sub_preempt_count(int val)
2831 {
2832 #ifdef CONFIG_DEBUG_PREEMPT
2833         /*
2834          * Underflow?
2835          */
2836         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
2837                 return;
2838         /*
2839          * Is the spinlock portion underflowing?
2840          */
2841         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
2842                         !(preempt_count() & PREEMPT_MASK)))
2843                 return;
2844 #endif
2845
2846         if (preempt_count() == val)
2847                 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
2848         preempt_count() -= val;
2849 }
2850 EXPORT_SYMBOL(sub_preempt_count);
2851
2852 #endif
2853
2854 /*
2855  * Print scheduling while atomic bug:
2856  */
2857 static noinline void __schedule_bug(struct task_struct *prev)
2858 {
2859         if (oops_in_progress)
2860                 return;
2861
2862         printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
2863                 prev->comm, prev->pid, preempt_count());
2864
2865         debug_show_held_locks(prev);
2866         print_modules();
2867         if (irqs_disabled())
2868                 print_irqtrace_events(prev);
2869         dump_stack();
2870         add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
2871 }
2872
2873 /*
2874  * Various schedule()-time debugging checks and statistics:
2875  */
2876 static inline void schedule_debug(struct task_struct *prev)
2877 {
2878         /*
2879          * Test if we are atomic. Since do_exit() needs to call into
2880          * schedule() atomically, we ignore that path for now.
2881          * Otherwise, whine if we are scheduling when we should not be.
2882          */
2883         if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
2884                 __schedule_bug(prev);
2885         rcu_sleep_check();
2886
2887         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2888
2889         schedstat_inc(this_rq(), sched_count);
2890 }
2891
2892 static void put_prev_task(struct rq *rq, struct task_struct *prev)
2893 {
2894         if (prev->on_rq || rq->skip_clock_update < 0)
2895                 update_rq_clock(rq);
2896         prev->sched_class->put_prev_task(rq, prev);
2897 }
2898
2899 /*
2900  * Pick up the highest-prio task:
2901  */
2902 static inline struct task_struct *
2903 pick_next_task(struct rq *rq)
2904 {
2905         const struct sched_class *class;
2906         struct task_struct *p;
2907
2908         /*
2909          * Optimization: we know that if all tasks are in
2910          * the fair class we can call that function directly:
2911          */
2912         if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
2913                 p = fair_sched_class.pick_next_task(rq);
2914                 if (likely(p))
2915                         return p;
2916         }
2917
2918         for_each_class(class) {
2919                 p = class->pick_next_task(rq);
2920                 if (p)
2921                         return p;
2922         }
2923
2924         BUG(); /* the idle class will always have a runnable task */
2925 }
2926
2927 /*
2928  * __schedule() is the main scheduler function.
2929  *
2930  * The main means of driving the scheduler and thus entering this function are:
2931  *
2932  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
2933  *
2934  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
2935  *      paths. For example, see arch/x86/entry_64.S.
2936  *
2937  *      To drive preemption between tasks, the scheduler sets the flag in timer
2938  *      interrupt handler scheduler_tick().
2939  *
2940  *   3. Wakeups don't really cause entry into schedule(). They add a
2941  *      task to the run-queue and that's it.
2942  *
2943  *      Now, if the new task added to the run-queue preempts the current
2944  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
2945  *      called on the nearest possible occasion:
2946  *
2947  *       - If the kernel is preemptible (CONFIG_PREEMPT=y):
2948  *
2949  *         - in syscall or exception context, at the next outmost
2950  *           preempt_enable(). (this might be as soon as the wake_up()'s
2951  *           spin_unlock()!)
2952  *
2953  *         - in IRQ context, return from interrupt-handler to
2954  *           preemptible context
2955  *
2956  *       - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
2957  *         then at the next:
2958  *
2959  *          - cond_resched() call
2960  *          - explicit schedule() call
2961  *          - return from syscall or exception to user-space
2962  *          - return from interrupt-handler to user-space
2963  */
2964 static void __sched __schedule(void)
2965 {
2966         struct task_struct *prev, *next;
2967         unsigned long *switch_count;
2968         struct rq *rq;
2969         int cpu;
2970
2971 need_resched:
2972         preempt_disable();
2973         cpu = smp_processor_id();
2974         rq = cpu_rq(cpu);
2975         rcu_note_context_switch(cpu);
2976         prev = rq->curr;
2977
2978         schedule_debug(prev);
2979
2980         if (sched_feat(HRTICK))
2981                 hrtick_clear(rq);
2982
2983         raw_spin_lock_irq(&rq->lock);
2984
2985         switch_count = &prev->nivcsw;
2986         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2987                 if (unlikely(signal_pending_state(prev->state, prev))) {
2988                         prev->state = TASK_RUNNING;
2989                 } else {
2990                         deactivate_task(rq, prev, DEQUEUE_SLEEP);
2991                         prev->on_rq = 0;
2992
2993                         /*
2994                          * If a worker went to sleep, notify and ask workqueue
2995                          * whether it wants to wake up a task to maintain
2996                          * concurrency.
2997                          */
2998                         if (prev->flags & PF_WQ_WORKER) {
2999                                 struct task_struct *to_wakeup;
3000
3001                                 to_wakeup = wq_worker_sleeping(prev, cpu);
3002                                 if (to_wakeup)
3003                                         try_to_wake_up_local(to_wakeup);
3004                         }
3005                 }
3006                 switch_count = &prev->nvcsw;
3007         }
3008
3009         pre_schedule(rq, prev);
3010
3011         if (unlikely(!rq->nr_running))
3012                 idle_balance(cpu, rq);
3013
3014         put_prev_task(rq, prev);
3015         next = pick_next_task(rq);
3016         clear_tsk_need_resched(prev);
3017         rq->skip_clock_update = 0;
3018
3019         if (likely(prev != next)) {
3020                 rq->nr_switches++;
3021                 rq->curr = next;
3022                 ++*switch_count;
3023
3024                 context_switch(rq, prev, next); /* unlocks the rq */
3025                 /*
3026                  * The context switch have flipped the stack from under us
3027                  * and restored the local variables which were saved when
3028                  * this task called schedule() in the past. prev == current
3029                  * is still correct, but it can be moved to another cpu/rq.
3030                  */
3031                 cpu = smp_processor_id();
3032                 rq = cpu_rq(cpu);
3033         } else
3034                 raw_spin_unlock_irq(&rq->lock);
3035
3036         post_schedule(rq);
3037
3038         sched_preempt_enable_no_resched();
3039         if (need_resched())
3040                 goto need_resched;
3041 }
3042
3043 static inline void sched_submit_work(struct task_struct *tsk)
3044 {
3045         if (!tsk->state || tsk_is_pi_blocked(tsk))
3046                 return;
3047         /*
3048          * If we are going to sleep and we have plugged IO queued,
3049          * make sure to submit it to avoid deadlocks.
3050          */
3051         if (blk_needs_flush_plug(tsk))
3052                 blk_schedule_flush_plug(tsk);
3053 }
3054
3055 asmlinkage void __sched schedule(void)
3056 {
3057         struct task_struct *tsk = current;
3058
3059         sched_submit_work(tsk);
3060         __schedule();
3061 }
3062 EXPORT_SYMBOL(schedule);
3063
3064 #ifdef CONFIG_CONTEXT_TRACKING
3065 asmlinkage void __sched schedule_user(void)
3066 {
3067         /*
3068          * If we come here after a random call to set_need_resched(),
3069          * or we have been woken up remotely but the IPI has not yet arrived,
3070          * we haven't yet exited the RCU idle mode. Do it here manually until
3071          * we find a better solution.
3072          */
3073         user_exit();
3074         schedule();
3075         user_enter();
3076 }
3077 #endif
3078
3079 /**
3080  * schedule_preempt_disabled - called with preemption disabled
3081  *
3082  * Returns with preemption disabled. Note: preempt_count must be 1
3083  */
3084 void __sched schedule_preempt_disabled(void)
3085 {
3086         sched_preempt_enable_no_resched();
3087         schedule();
3088         preempt_disable();
3089 }
3090
3091 #ifdef CONFIG_PREEMPT
3092 /*
3093  * this is the entry point to schedule() from in-kernel preemption
3094  * off of preempt_enable. Kernel preemptions off return from interrupt
3095  * occur there and call schedule directly.
3096  */
3097 asmlinkage void __sched notrace preempt_schedule(void)
3098 {
3099         struct thread_info *ti = current_thread_info();
3100
3101         /*
3102          * If there is a non-zero preempt_count or interrupts are disabled,
3103          * we do not want to preempt the current task. Just return..
3104          */
3105         if (likely(ti->preempt_count || irqs_disabled()))
3106                 return;
3107
3108         do {
3109                 add_preempt_count_notrace(PREEMPT_ACTIVE);
3110                 __schedule();
3111                 sub_preempt_count_notrace(PREEMPT_ACTIVE);
3112
3113                 /*
3114                  * Check again in case we missed a preemption opportunity
3115                  * between schedule and now.
3116                  */
3117                 barrier();
3118         } while (need_resched());
3119 }
3120 EXPORT_SYMBOL(preempt_schedule);
3121
3122 /*
3123  * this is the entry point to schedule() from kernel preemption
3124  * off of irq context.
3125  * Note, that this is called and return with irqs disabled. This will
3126  * protect us against recursive calling from irq.
3127  */
3128 asmlinkage void __sched preempt_schedule_irq(void)
3129 {
3130         struct thread_info *ti = current_thread_info();
3131         enum ctx_state prev_state;
3132
3133         /* Catch callers which need to be fixed */
3134         BUG_ON(ti->preempt_count || !irqs_disabled());
3135
3136         prev_state = exception_enter();
3137
3138         do {
3139                 add_preempt_count(PREEMPT_ACTIVE);
3140                 local_irq_enable();
3141                 __schedule();
3142                 local_irq_disable();
3143                 sub_preempt_count(PREEMPT_ACTIVE);
3144
3145                 /*
3146                  * Check again in case we missed a preemption opportunity
3147                  * between schedule and now.
3148                  */
3149                 barrier();
3150         } while (need_resched());
3151
3152         exception_exit(prev_state);
3153 }
3154
3155 #endif /* CONFIG_PREEMPT */
3156
3157 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3158                           void *key)
3159 {
3160         return try_to_wake_up(curr->private, mode, wake_flags);
3161 }
3162 EXPORT_SYMBOL(default_wake_function);
3163
3164 /*
3165  * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3166  * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3167  * number) then we wake all the non-exclusive tasks and one exclusive task.
3168  *
3169  * There are circumstances in which we can try to wake a task which has already
3170  * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3171  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3172  */
3173 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3174                         int nr_exclusive, int wake_flags, void *key)
3175 {
3176         wait_queue_t *curr, *next;
3177
3178         list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3179                 unsigned flags = curr->flags;
3180
3181                 if (curr->func(curr, mode, wake_flags, key) &&
3182                                 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3183                         break;
3184         }
3185 }
3186
3187 /**
3188  * __wake_up - wake up threads blocked on a waitqueue.
3189  * @q: the waitqueue
3190  * @mode: which threads
3191  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3192  * @key: is directly passed to the wakeup function
3193  *
3194  * It may be assumed that this function implies a write memory barrier before
3195  * changing the task state if and only if any tasks are woken up.
3196  */
3197 void __wake_up(wait_queue_head_t *q, unsigned int mode,
3198                         int nr_exclusive, void *key)
3199 {
3200         unsigned long flags;
3201
3202         spin_lock_irqsave(&q->lock, flags);
3203         __wake_up_common(q, mode, nr_exclusive, 0, key);
3204         spin_unlock_irqrestore(&q->lock, flags);
3205 }
3206 EXPORT_SYMBOL(__wake_up);
3207
3208 /*
3209  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3210  */
3211 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr)
3212 {
3213         __wake_up_common(q, mode, nr, 0, NULL);
3214 }
3215 EXPORT_SYMBOL_GPL(__wake_up_locked);
3216
3217 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
3218 {
3219         __wake_up_common(q, mode, 1, 0, key);
3220 }
3221 EXPORT_SYMBOL_GPL(__wake_up_locked_key);
3222
3223 /**
3224  * __wake_up_sync_key - wake up threads blocked on a waitqueue.
3225  * @q: the waitqueue
3226  * @mode: which threads
3227  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3228  * @key: opaque value to be passed to wakeup targets
3229  *
3230  * The sync wakeup differs that the waker knows that it will schedule
3231  * away soon, so while the target thread will be woken up, it will not
3232  * be migrated to another CPU - ie. the two threads are 'synchronized'
3233  * with each other. This can prevent needless bouncing between CPUs.
3234  *
3235  * On UP it can prevent extra preemption.
3236  *
3237  * It may be assumed that this function implies a write memory barrier before
3238  * changing the task state if and only if any tasks are woken up.
3239  */
3240 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
3241                         int nr_exclusive, void *key)
3242 {
3243         unsigned long flags;
3244         int wake_flags = WF_SYNC;
3245
3246         if (unlikely(!q))
3247                 return;
3248
3249         if (unlikely(!nr_exclusive))
3250                 wake_flags = 0;
3251
3252         spin_lock_irqsave(&q->lock, flags);
3253         __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
3254         spin_unlock_irqrestore(&q->lock, flags);
3255 }
3256 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
3257
3258 /*
3259  * __wake_up_sync - see __wake_up_sync_key()
3260  */
3261 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3262 {
3263         __wake_up_sync_key(q, mode, nr_exclusive, NULL);
3264 }
3265 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
3266
3267 /**
3268  * complete: - signals a single thread waiting on this completion
3269  * @x:  holds the state of this particular completion
3270  *
3271  * This will wake up a single thread waiting on this completion. Threads will be
3272  * awakened in the same order in which they were queued.
3273  *
3274  * See also complete_all(), wait_for_completion() and related routines.
3275  *
3276  * It may be assumed that this function implies a write memory barrier before
3277  * changing the task state if and only if any tasks are woken up.
3278  */
3279 void complete(struct completion *x)
3280 {
3281         unsigned long flags;
3282
3283         spin_lock_irqsave(&x->wait.lock, flags);
3284         x->done++;
3285         __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
3286         spin_unlock_irqrestore(&x->wait.lock, flags);
3287 }
3288 EXPORT_SYMBOL(complete);
3289
3290 /**
3291  * complete_all: - signals all threads waiting on this completion
3292  * @x:  holds the state of this particular completion
3293  *
3294  * This will wake up all threads waiting on this particular completion event.
3295  *
3296  * It may be assumed that this function implies a write memory barrier before
3297  * changing the task state if and only if any tasks are woken up.
3298  */
3299 void complete_all(struct completion *x)
3300 {
3301         unsigned long flags;
3302
3303         spin_lock_irqsave(&x->wait.lock, flags);
3304         x->done += UINT_MAX/2;
3305         __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
3306         spin_unlock_irqrestore(&x->wait.lock, flags);
3307 }
3308 EXPORT_SYMBOL(complete_all);
3309
3310 static inline long __sched
3311 do_wait_for_common(struct completion *x,
3312                    long (*action)(long), long timeout, int state)
3313 {
3314         if (!x->done) {
3315                 DECLARE_WAITQUEUE(wait, current);
3316
3317                 __add_wait_queue_tail_exclusive(&x->wait, &wait);
3318                 do {
3319                         if (signal_pending_state(state, current)) {
3320                                 timeout = -ERESTARTSYS;
3321                                 break;
3322                         }
3323                         __set_current_state(state);
3324                         spin_unlock_irq(&x->wait.lock);
3325                         timeout = action(timeout);
3326                         spin_lock_irq(&x->wait.lock);
3327                 } while (!x->done && timeout);
3328                 __remove_wait_queue(&x->wait, &wait);
3329                 if (!x->done)
3330                         return timeout;
3331         }
3332         x->done--;
3333         return timeout ?: 1;
3334 }
3335
3336 static inline long __sched
3337 __wait_for_common(struct completion *x,
3338                   long (*action)(long), long timeout, int state)
3339 {
3340         might_sleep();
3341
3342         spin_lock_irq(&x->wait.lock);
3343         timeout = do_wait_for_common(x, action, timeout, state);
3344         spin_unlock_irq(&x->wait.lock);
3345         return timeout;
3346 }
3347
3348 static long __sched
3349 wait_for_common(struct completion *x, long timeout, int state)
3350 {
3351         return __wait_for_common(x, schedule_timeout, timeout, state);
3352 }
3353
3354 static long __sched
3355 wait_for_common_io(struct completion *x, long timeout, int state)
3356 {
3357         return __wait_for_common(x, io_schedule_timeout, timeout, state);
3358 }
3359
3360 /**
3361  * wait_for_completion: - waits for completion of a task
3362  * @x:  holds the state of this particular completion
3363  *
3364  * This waits to be signaled for completion of a specific task. It is NOT
3365  * interruptible and there is no timeout.
3366  *
3367  * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
3368  * and interrupt capability. Also see complete().
3369  */
3370 void __sched wait_for_completion(struct completion *x)
3371 {
3372         wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3373 }
3374 EXPORT_SYMBOL(wait_for_completion);
3375
3376 /**
3377  * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
3378  * @x:  holds the state of this particular completion
3379  * @timeout:  timeout value in jiffies
3380  *
3381  * This waits for either a completion of a specific task to be signaled or for a
3382  * specified timeout to expire. The timeout is in jiffies. It is not
3383  * interruptible.
3384  *
3385  * The return value is 0 if timed out, and positive (at least 1, or number of
3386  * jiffies left till timeout) if completed.
3387  */
3388 unsigned long __sched
3389 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3390 {
3391         return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
3392 }
3393 EXPORT_SYMBOL(wait_for_completion_timeout);
3394
3395 /**
3396  * wait_for_completion_io: - waits for completion of a task
3397  * @x:  holds the state of this particular completion
3398  *
3399  * This waits to be signaled for completion of a specific task. It is NOT
3400  * interruptible and there is no timeout. The caller is accounted as waiting
3401  * for IO.
3402  */
3403 void __sched wait_for_completion_io(struct completion *x)
3404 {
3405         wait_for_common_io(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3406 }
3407 EXPORT_SYMBOL(wait_for_completion_io);
3408
3409 /**
3410  * wait_for_completion_io_timeout: - waits for completion of a task (w/timeout)
3411  * @x:  holds the state of this particular completion
3412  * @timeout:  timeout value in jiffies
3413  *
3414  * This waits for either a completion of a specific task to be signaled or for a
3415  * specified timeout to expire. The timeout is in jiffies. It is not
3416  * interruptible. The caller is accounted as waiting for IO.
3417  *
3418  * The return value is 0 if timed out, and positive (at least 1, or number of
3419  * jiffies left till timeout) if completed.
3420  */
3421 unsigned long __sched
3422 wait_for_completion_io_timeout(struct completion *x, unsigned long timeout)
3423 {
3424         return wait_for_common_io(x, timeout, TASK_UNINTERRUPTIBLE);
3425 }
3426 EXPORT_SYMBOL(wait_for_completion_io_timeout);
3427
3428 /**
3429  * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
3430  * @x:  holds the state of this particular completion
3431  *
3432  * This waits for completion of a specific task to be signaled. It is
3433  * interruptible.
3434  *
3435  * The return value is -ERESTARTSYS if interrupted, 0 if completed.
3436  */
3437 int __sched wait_for_completion_interruptible(struct completion *x)
3438 {
3439         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3440         if (t == -ERESTARTSYS)
3441                 return t;
3442         return 0;
3443 }
3444 EXPORT_SYMBOL(wait_for_completion_interruptible);
3445
3446 /**
3447  * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
3448  * @x:  holds the state of this particular completion
3449  * @timeout:  timeout value in jiffies
3450  *
3451  * This waits for either a completion of a specific task to be signaled or for a
3452  * specified timeout to expire. It is interruptible. The timeout is in jiffies.
3453  *
3454  * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3455  * positive (at least 1, or number of jiffies left till timeout) if completed.
3456  */
3457 long __sched
3458 wait_for_completion_interruptible_timeout(struct completion *x,
3459                                           unsigned long timeout)
3460 {
3461         return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
3462 }
3463 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3464
3465 /**
3466  * wait_for_completion_killable: - waits for completion of a task (killable)
3467  * @x:  holds the state of this particular completion
3468  *
3469  * This waits to be signaled for completion of a specific task. It can be
3470  * interrupted by a kill signal.
3471  *
3472  * The return value is -ERESTARTSYS if interrupted, 0 if completed.
3473  */
3474 int __sched wait_for_completion_killable(struct completion *x)
3475 {
3476         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
3477         if (t == -ERESTARTSYS)
3478                 return t;
3479         return 0;
3480 }
3481 EXPORT_SYMBOL(wait_for_completion_killable);
3482
3483 /**
3484  * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
3485  * @x:  holds the state of this particular completion
3486  * @timeout:  timeout value in jiffies
3487  *
3488  * This waits for either a completion of a specific task to be
3489  * signaled or for a specified timeout to expire. It can be
3490  * interrupted by a kill signal. The timeout is in jiffies.
3491  *
3492  * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3493  * positive (at least 1, or number of jiffies left till timeout) if completed.
3494  */
3495 long __sched
3496 wait_for_completion_killable_timeout(struct completion *x,
3497                                      unsigned long timeout)
3498 {
3499         return wait_for_common(x, timeout, TASK_KILLABLE);
3500 }
3501 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
3502
3503 /**
3504  *      try_wait_for_completion - try to decrement a completion without blocking
3505  *      @x:     completion structure
3506  *
3507  *      Returns: 0 if a decrement cannot be done without blocking
3508  *               1 if a decrement succeeded.
3509  *
3510  *      If a completion is being used as a counting completion,
3511  *      attempt to decrement the counter without blocking. This
3512  *      enables us to avoid waiting if the resource the completion
3513  *      is protecting is not available.
3514  */
3515 bool try_wait_for_completion(struct completion *x)
3516 {
3517         unsigned long flags;
3518         int ret = 1;
3519
3520         spin_lock_irqsave(&x->wait.lock, flags);
3521         if (!x->done)
3522                 ret = 0;
3523         else
3524                 x->done--;
3525         spin_unlock_irqrestore(&x->wait.lock, flags);
3526         return ret;
3527 }
3528 EXPORT_SYMBOL(try_wait_for_completion);
3529
3530 /**
3531  *      completion_done - Test to see if a completion has any waiters
3532  *      @x:     completion structure
3533  *
3534  *      Returns: 0 if there are waiters (wait_for_completion() in progress)
3535  *               1 if there are no waiters.
3536  *
3537  */
3538 bool completion_done(struct completion *x)
3539 {
3540         unsigned long flags;
3541         int ret = 1;
3542
3543         spin_lock_irqsave(&x->wait.lock, flags);
3544         if (!x->done)
3545                 ret = 0;
3546         spin_unlock_irqrestore(&x->wait.lock, flags);
3547         return ret;
3548 }
3549 EXPORT_SYMBOL(completion_done);
3550
3551 static long __sched
3552 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
3553 {
3554         unsigned long flags;
3555         wait_queue_t wait;
3556
3557         init_waitqueue_entry(&wait, current);
3558
3559         __set_current_state(state);
3560
3561         spin_lock_irqsave(&q->lock, flags);
3562         __add_wait_queue(q, &wait);
3563         spin_unlock(&q->lock);
3564         timeout = schedule_timeout(timeout);
3565         spin_lock_irq(&q->lock);
3566         __remove_wait_queue(q, &wait);
3567         spin_unlock_irqrestore(&q->lock, flags);
3568
3569         return timeout;
3570 }
3571
3572 void __sched interruptible_sleep_on(wait_queue_head_t *q)
3573 {
3574         sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3575 }
3576 EXPORT_SYMBOL(interruptible_sleep_on);
3577
3578 long __sched
3579 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3580 {
3581         return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
3582 }
3583 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3584
3585 void __sched sleep_on(wait_queue_head_t *q)
3586 {
3587         sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3588 }
3589 EXPORT_SYMBOL(sleep_on);
3590
3591 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3592 {
3593         return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
3594 }
3595 EXPORT_SYMBOL(sleep_on_timeout);
3596
3597 #ifdef CONFIG_RT_MUTEXES
3598
3599 /*
3600  * rt_mutex_setprio - set the current priority of a task
3601  * @p: task
3602  * @prio: prio value (kernel-internal form)
3603  *
3604  * This function changes the 'effective' priority of a task. It does
3605  * not touch ->normal_prio like __setscheduler().
3606  *
3607  * Used by the rt_mutex code to implement priority inheritance logic.
3608  */
3609 void rt_mutex_setprio(struct task_struct *p, int prio)
3610 {
3611         int oldprio, on_rq, running;
3612         struct rq *rq;
3613         const struct sched_class *prev_class;
3614
3615         BUG_ON(prio < 0 || prio > MAX_PRIO);
3616
3617         rq = __task_rq_lock(p);
3618
3619         /*
3620          * Idle task boosting is a nono in general. There is one
3621          * exception, when PREEMPT_RT and NOHZ is active:
3622          *
3623          * The idle task calls get_next_timer_interrupt() and holds
3624          * the timer wheel base->lock on the CPU and another CPU wants
3625          * to access the timer (probably to cancel it). We can safely
3626          * ignore the boosting request, as the idle CPU runs this code
3627          * with interrupts disabled and will complete the lock
3628          * protected section without being interrupted. So there is no
3629          * real need to boost.
3630          */
3631         if (unlikely(p == rq->idle)) {
3632                 WARN_ON(p != rq->curr);
3633                 WARN_ON(p->pi_blocked_on);
3634                 goto out_unlock;
3635         }
3636
3637         trace_sched_pi_setprio(p, prio);
3638         oldprio = p->prio;
3639         prev_class = p->sched_class;
3640         on_rq = p->on_rq;
3641         running = task_current(rq, p);
3642         if (on_rq)
3643                 dequeue_task(rq, p, 0);
3644         if (running)
3645                 p->sched_class->put_prev_task(rq, p);
3646
3647         if (rt_prio(prio))
3648                 p->sched_class = &rt_sched_class;
3649         else
3650                 p->sched_class = &fair_sched_class;
3651
3652         p->prio = prio;
3653
3654         if (running)
3655                 p->sched_class->set_curr_task(rq);
3656         if (on_rq)
3657                 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
3658
3659         check_class_changed(rq, p, prev_class, oldprio);
3660 out_unlock:
3661         __task_rq_unlock(rq);
3662 }
3663 #endif
3664 void set_user_nice(struct task_struct *p, long nice)
3665 {
3666         int old_prio, delta, on_rq;
3667         unsigned long flags;
3668         struct rq *rq;
3669
3670         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3671                 return;
3672         /*
3673          * We have to be careful, if called from sys_setpriority(),
3674          * the task might be in the middle of scheduling on another CPU.
3675          */
3676         rq = task_rq_lock(p, &flags);
3677         /*
3678          * The RT priorities are set via sched_setscheduler(), but we still
3679          * allow the 'normal' nice value to be set - but as expected
3680          * it wont have any effect on scheduling until the task is
3681          * SCHED_FIFO/SCHED_RR:
3682          */
3683         if (task_has_rt_policy(p)) {
3684                 p->static_prio = NICE_TO_PRIO(nice);
3685                 goto out_unlock;
3686         }
3687         on_rq = p->on_rq;
3688         if (on_rq)
3689                 dequeue_task(rq, p, 0);
3690
3691         p->static_prio = NICE_TO_PRIO(nice);
3692         set_load_weight(p);
3693         old_prio = p->prio;
3694         p->prio = effective_prio(p);
3695         delta = p->prio - old_prio;
3696
3697         if (on_rq) {
3698                 enqueue_task(rq, p, 0);
3699                 /*
3700                  * If the task increased its priority or is running and
3701                  * lowered its priority, then reschedule its CPU:
3702                  */
3703                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3704                         resched_task(rq->curr);
3705         }
3706 out_unlock:
3707         task_rq_unlock(rq, p, &flags);
3708 }
3709 EXPORT_SYMBOL(set_user_nice);
3710
3711 /*
3712  * can_nice - check if a task can reduce its nice value
3713  * @p: task
3714  * @nice: nice value
3715  */
3716 int can_nice(const struct task_struct *p, const int nice)
3717 {
3718         /* convert nice value [19,-20] to rlimit style value [1,40] */
3719         int nice_rlim = 20 - nice;
3720
3721         return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3722                 capable(CAP_SYS_NICE));
3723 }
3724
3725 #ifdef __ARCH_WANT_SYS_NICE
3726
3727 /*
3728  * sys_nice - change the priority of the current process.
3729  * @increment: priority increment
3730  *
3731  * sys_setpriority is a more generic, but much slower function that
3732  * does similar things.
3733  */
3734 SYSCALL_DEFINE1(nice, int, increment)
3735 {
3736         long nice, retval;
3737
3738         /*
3739          * Setpriority might change our priority at the same moment.
3740          * We don't have to worry. Conceptually one call occurs first
3741          * and we have a single winner.
3742          */
3743         if (increment < -40)
3744                 increment = -40;
3745         if (increment > 40)
3746                 increment = 40;
3747
3748         nice = TASK_NICE(current) + increment;
3749         if (nice < -20)
3750                 nice = -20;
3751         if (nice > 19)
3752                 nice = 19;
3753
3754         if (increment < 0 && !can_nice(current, nice))
3755                 return -EPERM;
3756
3757         retval = security_task_setnice(current, nice);
3758         if (retval)
3759                 return retval;
3760
3761         set_user_nice(current, nice);
3762         return 0;
3763 }
3764
3765 #endif
3766
3767 /**
3768  * task_prio - return the priority value of a given task.
3769  * @p: the task in question.
3770  *
3771  * This is the priority value as seen by users in /proc.
3772  * RT tasks are offset by -200. Normal tasks are centered
3773  * around 0, value goes from -16 to +15.
3774  */
3775 int task_prio(const struct task_struct *p)
3776 {
3777         return p->prio - MAX_RT_PRIO;
3778 }
3779
3780 /**
3781  * task_nice - return the nice value of a given task.
3782  * @p: the task in question.
3783  */
3784 int task_nice(const struct task_struct *p)
3785 {
3786         return TASK_NICE(p);
3787 }
3788 EXPORT_SYMBOL(task_nice);
3789
3790 /**
3791  * idle_cpu - is a given cpu idle currently?
3792  * @cpu: the processor in question.
3793  */
3794 int idle_cpu(int cpu)
3795 {
3796         struct rq *rq = cpu_rq(cpu);
3797
3798         if (rq->curr != rq->idle)
3799                 return 0;
3800
3801         if (rq->nr_running)
3802                 return 0;
3803
3804 #ifdef CONFIG_SMP
3805         if (!llist_empty(&rq->wake_list))
3806                 return 0;
3807 #endif
3808
3809         return 1;
3810 }
3811
3812 /**
3813  * idle_task - return the idle task for a given cpu.
3814  * @cpu: the processor in question.
3815  */
3816 struct task_struct *idle_task(int cpu)
3817 {
3818         return cpu_rq(cpu)->idle;
3819 }
3820
3821 /**
3822  * find_process_by_pid - find a process with a matching PID value.
3823  * @pid: the pid in question.
3824  */
3825 static struct task_struct *find_process_by_pid(pid_t pid)
3826 {
3827         return pid ? find_task_by_vpid(pid) : current;
3828 }
3829
3830 extern struct cpumask hmp_slow_cpu_mask;
3831
3832 /* Actually do priority change: must hold rq lock. */
3833 static void
3834 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
3835 {
3836         p->policy = policy;
3837         p->rt_priority = prio;
3838         p->normal_prio = normal_prio(p);
3839         /* we are holding p->pi_lock already */
3840         p->prio = rt_mutex_getprio(p);
3841         if (rt_prio(p->prio)) {
3842                 p->sched_class = &rt_sched_class;
3843 #ifdef CONFIG_SCHED_HMP
3844                 if (!cpumask_empty(&hmp_slow_cpu_mask))
3845                         if (cpumask_equal(&p->cpus_allowed, cpu_all_mask))
3846                                 do_set_cpus_allowed(p, &hmp_slow_cpu_mask);
3847 #endif
3848         }
3849         else
3850                 p->sched_class = &fair_sched_class;
3851         set_load_weight(p);
3852 }
3853
3854 /*
3855  * check the target process has a UID that matches the current process's
3856  */
3857 static bool check_same_owner(struct task_struct *p)
3858 {
3859         const struct cred *cred = current_cred(), *pcred;
3860         bool match;
3861
3862         rcu_read_lock();
3863         pcred = __task_cred(p);
3864         match = (uid_eq(cred->euid, pcred->euid) ||
3865                  uid_eq(cred->euid, pcred->uid));
3866         rcu_read_unlock();
3867         return match;
3868 }
3869
3870 static int __sched_setscheduler(struct task_struct *p, int policy,
3871                                 const struct sched_param *param, bool user)
3872 {
3873         int retval, oldprio, oldpolicy = -1, on_rq, running;
3874         unsigned long flags;
3875         const struct sched_class *prev_class;
3876         struct rq *rq;
3877         int reset_on_fork;
3878
3879         /* may grab non-irq protected spin_locks */
3880         BUG_ON(in_interrupt());
3881 recheck:
3882         /* double check policy once rq lock held */
3883         if (policy < 0) {
3884                 reset_on_fork = p->sched_reset_on_fork;
3885                 policy = oldpolicy = p->policy;
3886         } else {
3887                 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
3888                 policy &= ~SCHED_RESET_ON_FORK;
3889
3890                 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3891                                 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
3892                                 policy != SCHED_IDLE)
3893                         return -EINVAL;
3894         }
3895
3896         /*
3897          * Valid priorities for SCHED_FIFO and SCHED_RR are
3898          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3899          * SCHED_BATCH and SCHED_IDLE is 0.
3900          */
3901         if (param->sched_priority < 0 ||
3902             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3903             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3904                 return -EINVAL;
3905         if (rt_policy(policy) != (param->sched_priority != 0))
3906                 return -EINVAL;
3907
3908         /*
3909          * Allow unprivileged RT tasks to decrease priority:
3910          */
3911         if (user && !capable(CAP_SYS_NICE)) {
3912                 if (rt_policy(policy)) {
3913                         unsigned long rlim_rtprio =
3914                                         task_rlimit(p, RLIMIT_RTPRIO);
3915
3916                         /* can't set/change the rt policy */
3917                         if (policy != p->policy && !rlim_rtprio)
3918                                 return -EPERM;
3919
3920                         /* can't increase priority */
3921                         if (param->sched_priority > p->rt_priority &&
3922                             param->sched_priority > rlim_rtprio)
3923                                 return -EPERM;
3924                 }
3925
3926                 /*
3927                  * Treat SCHED_IDLE as nice 20. Only allow a switch to
3928                  * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
3929                  */
3930                 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
3931                         if (!can_nice(p, TASK_NICE(p)))
3932                                 return -EPERM;
3933                 }
3934
3935                 /* can't change other user's priorities */
3936                 if (!check_same_owner(p))
3937                         return -EPERM;
3938
3939                 /* Normal users shall not reset the sched_reset_on_fork flag */
3940                 if (p->sched_reset_on_fork && !reset_on_fork)
3941                         return -EPERM;
3942         }
3943
3944         if (user) {
3945                 retval = security_task_setscheduler(p);
3946                 if (retval)
3947                         return retval;
3948         }
3949
3950         /*
3951          * make sure no PI-waiters arrive (or leave) while we are
3952          * changing the priority of the task:
3953          *
3954          * To be able to change p->policy safely, the appropriate
3955          * runqueue lock must be held.
3956          */
3957         rq = task_rq_lock(p, &flags);
3958
3959         /*
3960          * Changing the policy of the stop threads its a very bad idea
3961          */
3962         if (p == rq->stop) {
3963                 task_rq_unlock(rq, p, &flags);
3964                 return -EINVAL;
3965         }
3966
3967         /*
3968          * If not changing anything there's no need to proceed further:
3969          */
3970         if (unlikely(policy == p->policy && (!rt_policy(policy) ||
3971                         param->sched_priority == p->rt_priority))) {
3972                 task_rq_unlock(rq, p, &flags);
3973                 return 0;
3974         }
3975
3976 #ifdef CONFIG_RT_GROUP_SCHED
3977         if (user) {
3978                 /*
3979                  * Do not allow realtime tasks into groups that have no runtime
3980                  * assigned.
3981                  */
3982                 if (rt_bandwidth_enabled() && rt_policy(policy) &&
3983                                 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
3984                                 !task_group_is_autogroup(task_group(p))) {
3985                         task_rq_unlock(rq, p, &flags);
3986                         return -EPERM;
3987                 }
3988         }
3989 #endif
3990
3991         /* recheck policy now with rq lock held */
3992         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3993                 policy = oldpolicy = -1;
3994                 task_rq_unlock(rq, p, &flags);
3995                 goto recheck;
3996         }
3997         on_rq = p->on_rq;
3998         running = task_current(rq, p);
3999         if (on_rq)
4000                 dequeue_task(rq, p, 0);
4001         if (running)
4002                 p->sched_class->put_prev_task(rq, p);
4003
4004         p->sched_reset_on_fork = reset_on_fork;
4005
4006         oldprio = p->prio;
4007         prev_class = p->sched_class;
4008         __setscheduler(rq, p, policy, param->sched_priority);
4009
4010         if (running)
4011                 p->sched_class->set_curr_task(rq);
4012         if (on_rq)
4013                 enqueue_task(rq, p, 0);
4014
4015         check_class_changed(rq, p, prev_class, oldprio);
4016         task_rq_unlock(rq, p, &flags);
4017
4018         rt_mutex_adjust_pi(p);
4019
4020         return 0;
4021 }
4022
4023 /**
4024  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4025  * @p: the task in question.
4026  * @policy: new policy.
4027  * @param: structure containing the new RT priority.
4028  *
4029  * NOTE that the task may be already dead.
4030  */
4031 int sched_setscheduler(struct task_struct *p, int policy,
4032                        const struct sched_param *param)
4033 {
4034         return __sched_setscheduler(p, policy, param, true);
4035 }
4036 EXPORT_SYMBOL_GPL(sched_setscheduler);
4037
4038 /**
4039  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4040  * @p: the task in question.
4041  * @policy: new policy.
4042  * @param: structure containing the new RT priority.
4043  *
4044  * Just like sched_setscheduler, only don't bother checking if the
4045  * current context has permission.  For example, this is needed in
4046  * stop_machine(): we create temporary high priority worker threads,
4047  * but our caller might not have that capability.
4048  */
4049 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4050                                const struct sched_param *param)
4051 {
4052         return __sched_setscheduler(p, policy, param, false);
4053 }
4054
4055 static int
4056 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4057 {
4058         struct sched_param lparam;
4059         struct task_struct *p;
4060         int retval;
4061
4062         if (!param || pid < 0)
4063                 return -EINVAL;
4064         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4065                 return -EFAULT;
4066
4067         rcu_read_lock();
4068         retval = -ESRCH;
4069         p = find_process_by_pid(pid);
4070         if (p != NULL)
4071                 retval = sched_setscheduler(p, policy, &lparam);
4072         rcu_read_unlock();
4073
4074         return retval;
4075 }
4076
4077 /**
4078  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4079  * @pid: the pid in question.
4080  * @policy: new policy.
4081  * @param: structure containing the new RT priority.
4082  */
4083 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4084                 struct sched_param __user *, param)
4085 {
4086         /* negative values for policy are not valid */
4087         if (policy < 0)
4088                 return -EINVAL;
4089
4090         return do_sched_setscheduler(pid, policy, param);
4091 }
4092
4093 /**
4094  * sys_sched_setparam - set/change the RT priority of a thread
4095  * @pid: the pid in question.
4096  * @param: structure containing the new RT priority.
4097  */
4098 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4099 {
4100         return do_sched_setscheduler(pid, -1, param);
4101 }
4102
4103 /**
4104  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4105  * @pid: the pid in question.
4106  */
4107 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4108 {
4109         struct task_struct *p;
4110         int retval;
4111
4112         if (pid < 0)
4113                 return -EINVAL;
4114
4115         retval = -ESRCH;
4116         rcu_read_lock();
4117         p = find_process_by_pid(pid);
4118         if (p) {
4119                 retval = security_task_getscheduler(p);
4120                 if (!retval)
4121                         retval = p->policy
4122                                 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4123         }
4124         rcu_read_unlock();
4125         return retval;
4126 }
4127
4128 /**
4129  * sys_sched_getparam - get the RT priority of a thread
4130  * @pid: the pid in question.
4131  * @param: structure containing the RT priority.
4132  */
4133 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4134 {
4135         struct sched_param lp;
4136         struct task_struct *p;
4137         int retval;
4138
4139         if (!param || pid < 0)
4140                 return -EINVAL;
4141
4142         rcu_read_lock();
4143         p = find_process_by_pid(pid);
4144         retval = -ESRCH;
4145         if (!p)
4146                 goto out_unlock;
4147
4148         retval = security_task_getscheduler(p);
4149         if (retval)
4150                 goto out_unlock;
4151
4152         lp.sched_priority = p->rt_priority;
4153         rcu_read_unlock();
4154
4155         /*
4156          * This one might sleep, we cannot do it with a spinlock held ...
4157          */
4158         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4159
4160         return retval;
4161
4162 out_unlock:
4163         rcu_read_unlock();
4164         return retval;
4165 }
4166
4167 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4168 {
4169         cpumask_var_t cpus_allowed, new_mask;
4170         struct task_struct *p;
4171         int retval;
4172
4173         get_online_cpus();
4174         rcu_read_lock();
4175
4176         p = find_process_by_pid(pid);
4177         if (!p) {
4178                 rcu_read_unlock();
4179                 put_online_cpus();
4180                 return -ESRCH;
4181         }
4182
4183         /* Prevent p going away */
4184         get_task_struct(p);
4185         rcu_read_unlock();
4186
4187         if (p->flags & PF_NO_SETAFFINITY) {
4188                 retval = -EINVAL;
4189                 goto out_put_task;
4190         }
4191         if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4192                 retval = -ENOMEM;
4193                 goto out_put_task;
4194         }
4195         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4196                 retval = -ENOMEM;
4197                 goto out_free_cpus_allowed;
4198         }
4199         retval = -EPERM;
4200         if (!check_same_owner(p)) {
4201                 rcu_read_lock();
4202                 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4203                         rcu_read_unlock();
4204                         goto out_unlock;
4205                 }
4206                 rcu_read_unlock();
4207         }
4208
4209         retval = security_task_setscheduler(p);
4210         if (retval)
4211                 goto out_unlock;
4212
4213         cpuset_cpus_allowed(p, cpus_allowed);
4214         cpumask_and(new_mask, in_mask, cpus_allowed);
4215 again:
4216         retval = set_cpus_allowed_ptr(p, new_mask);
4217
4218         if (!retval) {
4219                 cpuset_cpus_allowed(p, cpus_allowed);
4220                 if (!cpumask_subset(new_mask, cpus_allowed)) {
4221                         /*
4222                          * We must have raced with a concurrent cpuset
4223                          * update. Just reset the cpus_allowed to the
4224                          * cpuset's cpus_allowed
4225                          */
4226                         cpumask_copy(new_mask, cpus_allowed);
4227                         goto again;
4228                 }
4229         }
4230 out_unlock:
4231         free_cpumask_var(new_mask);
4232 out_free_cpus_allowed:
4233         free_cpumask_var(cpus_allowed);
4234 out_put_task:
4235         put_task_struct(p);
4236         put_online_cpus();
4237         return retval;
4238 }
4239
4240 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4241                              struct cpumask *new_mask)
4242 {
4243         if (len < cpumask_size())
4244                 cpumask_clear(new_mask);
4245         else if (len > cpumask_size())
4246                 len = cpumask_size();
4247
4248         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4249 }
4250
4251 /**
4252  * sys_sched_setaffinity - set the cpu affinity of a process
4253  * @pid: pid of the process
4254  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4255  * @user_mask_ptr: user-space pointer to the new cpu mask
4256  */
4257 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4258                 unsigned long __user *, user_mask_ptr)
4259 {
4260         cpumask_var_t new_mask;
4261         int retval;
4262
4263         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4264                 return -ENOMEM;
4265
4266         retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4267         if (retval == 0)
4268                 retval = sched_setaffinity(pid, new_mask);
4269         free_cpumask_var(new_mask);
4270         return retval;
4271 }
4272
4273 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4274 {
4275         struct task_struct *p;
4276         unsigned long flags;
4277         int retval;
4278
4279         get_online_cpus();
4280         rcu_read_lock();
4281
4282         retval = -ESRCH;
4283         p = find_process_by_pid(pid);
4284         if (!p)
4285                 goto out_unlock;
4286
4287         retval = security_task_getscheduler(p);
4288         if (retval)
4289                 goto out_unlock;
4290
4291         raw_spin_lock_irqsave(&p->pi_lock, flags);
4292         cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4293         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4294
4295 out_unlock:
4296         rcu_read_unlock();
4297         put_online_cpus();
4298
4299         return retval;
4300 }
4301
4302 /**
4303  * sys_sched_getaffinity - get the cpu affinity of a process
4304  * @pid: pid of the process
4305  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4306  * @user_mask_ptr: user-space pointer to hold the current cpu mask
4307  */
4308 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4309                 unsigned long __user *, user_mask_ptr)
4310 {
4311         int ret;
4312         cpumask_var_t mask;
4313
4314         if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4315                 return -EINVAL;
4316         if (len & (sizeof(unsigned long)-1))
4317                 return -EINVAL;
4318
4319         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4320                 return -ENOMEM;
4321
4322         ret = sched_getaffinity(pid, mask);
4323         if (ret == 0) {
4324                 size_t retlen = min_t(size_t, len, cpumask_size());
4325
4326                 if (copy_to_user(user_mask_ptr, mask, retlen))
4327                         ret = -EFAULT;
4328                 else
4329                         ret = retlen;
4330         }
4331         free_cpumask_var(mask);
4332
4333         return ret;
4334 }
4335
4336 /**
4337  * sys_sched_yield - yield the current processor to other threads.
4338  *
4339  * This function yields the current CPU to other tasks. If there are no
4340  * other threads running on this CPU then this function will return.
4341  */
4342 SYSCALL_DEFINE0(sched_yield)
4343 {
4344         struct rq *rq = this_rq_lock();
4345
4346         schedstat_inc(rq, yld_count);
4347         current->sched_class->yield_task(rq);
4348
4349         /*
4350          * Since we are going to call schedule() anyway, there's
4351          * no need to preempt or enable interrupts:
4352          */
4353         __release(rq->lock);
4354         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4355         do_raw_spin_unlock(&rq->lock);
4356         sched_preempt_enable_no_resched();
4357
4358         schedule();
4359
4360         return 0;
4361 }
4362
4363 static inline int should_resched(void)
4364 {
4365         return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
4366 }
4367
4368 static void __cond_resched(void)
4369 {
4370         add_preempt_count(PREEMPT_ACTIVE);
4371         __schedule();
4372         sub_preempt_count(PREEMPT_ACTIVE);
4373 }
4374
4375 int __sched _cond_resched(void)
4376 {
4377         if (should_resched()) {
4378                 __cond_resched();
4379                 return 1;
4380         }
4381         return 0;
4382 }
4383 EXPORT_SYMBOL(_cond_resched);
4384
4385 /*
4386  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4387  * call schedule, and on return reacquire the lock.
4388  *
4389  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4390  * operations here to prevent schedule() from being called twice (once via
4391  * spin_unlock(), once by hand).
4392  */
4393 int __cond_resched_lock(spinlock_t *lock)
4394 {
4395         int resched = should_resched();
4396         int ret = 0;
4397
4398         lockdep_assert_held(lock);
4399
4400         if (spin_needbreak(lock) || resched) {
4401                 spin_unlock(lock);
4402                 if (resched)
4403                         __cond_resched();
4404                 else
4405                         cpu_relax();
4406                 ret = 1;
4407                 spin_lock(lock);
4408         }
4409         return ret;
4410 }
4411 EXPORT_SYMBOL(__cond_resched_lock);
4412
4413 int __sched __cond_resched_softirq(void)
4414 {
4415         BUG_ON(!in_softirq());
4416
4417         if (should_resched()) {
4418                 local_bh_enable();
4419                 __cond_resched();
4420                 local_bh_disable();
4421                 return 1;
4422         }
4423         return 0;
4424 }
4425 EXPORT_SYMBOL(__cond_resched_softirq);
4426
4427 /**
4428  * yield - yield the current processor to other threads.
4429  *
4430  * Do not ever use this function, there's a 99% chance you're doing it wrong.
4431  *
4432  * The scheduler is at all times free to pick the calling task as the most
4433  * eligible task to run, if removing the yield() call from your code breaks
4434  * it, its already broken.
4435  *
4436  * Typical broken usage is:
4437  *
4438  * while (!event)
4439  *      yield();
4440  *
4441  * where one assumes that yield() will let 'the other' process run that will
4442  * make event true. If the current task is a SCHED_FIFO task that will never
4443  * happen. Never use yield() as a progress guarantee!!
4444  *
4445  * If you want to use yield() to wait for something, use wait_event().
4446  * If you want to use yield() to be 'nice' for others, use cond_resched().
4447  * If you still want to use yield(), do not!
4448  */
4449 void __sched yield(void)
4450 {
4451         set_current_state(TASK_RUNNING);
4452         sys_sched_yield();
4453 }
4454 EXPORT_SYMBOL(yield);
4455
4456 /**
4457  * yield_to - yield the current processor to another thread in
4458  * your thread group, or accelerate that thread toward the
4459  * processor it's on.
4460  * @p: target task
4461  * @preempt: whether task preemption is allowed or not
4462  *
4463  * It's the caller's job to ensure that the target task struct
4464  * can't go away on us before we can do any checks.
4465  *
4466  * Returns:
4467  *      true (>0) if we indeed boosted the target task.
4468  *      false (0) if we failed to boost the target.
4469  *      -ESRCH if there's no task to yield to.
4470  */
4471 bool __sched yield_to(struct task_struct *p, bool preempt)
4472 {
4473         struct task_struct *curr = current;
4474         struct rq *rq, *p_rq;
4475         unsigned long flags;
4476         int yielded = 0;
4477
4478         local_irq_save(flags);
4479         rq = this_rq();
4480
4481 again:
4482         p_rq = task_rq(p);
4483         /*
4484          * If we're the only runnable task on the rq and target rq also
4485          * has only one task, there's absolutely no point in yielding.
4486          */
4487         if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4488                 yielded = -ESRCH;
4489                 goto out_irq;
4490         }
4491
4492         double_rq_lock(rq, p_rq);
4493         while (task_rq(p) != p_rq) {
4494                 double_rq_unlock(rq, p_rq);
4495                 goto again;
4496         }
4497
4498         if (!curr->sched_class->yield_to_task)
4499                 goto out_unlock;
4500
4501         if (curr->sched_class != p->sched_class)
4502                 goto out_unlock;
4503
4504         if (task_running(p_rq, p) || p->state)
4505                 goto out_unlock;
4506
4507         yielded = curr->sched_class->yield_to_task(rq, p, preempt);
4508         if (yielded) {
4509                 schedstat_inc(rq, yld_count);
4510                 /*
4511                  * Make p's CPU reschedule; pick_next_entity takes care of
4512                  * fairness.
4513                  */
4514                 if (preempt && rq != p_rq)
4515                         resched_task(p_rq->curr);
4516         }
4517
4518 out_unlock:
4519         double_rq_unlock(rq, p_rq);
4520 out_irq:
4521         local_irq_restore(flags);
4522
4523         if (yielded > 0)
4524                 schedule();
4525
4526         return yielded;
4527 }
4528 EXPORT_SYMBOL_GPL(yield_to);
4529
4530 /*
4531  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4532  * that process accounting knows that this is a task in IO wait state.
4533  */
4534 void __sched io_schedule(void)
4535 {
4536         struct rq *rq = raw_rq();
4537
4538         delayacct_blkio_start();
4539         atomic_inc(&rq->nr_iowait);
4540         blk_flush_plug(current);
4541         current->in_iowait = 1;
4542         schedule();
4543         current->in_iowait = 0;
4544         atomic_dec(&rq->nr_iowait);
4545         delayacct_blkio_end();
4546 }
4547 EXPORT_SYMBOL(io_schedule);
4548
4549 long __sched io_schedule_timeout(long timeout)
4550 {
4551         struct rq *rq = raw_rq();
4552         long ret;
4553
4554         delayacct_blkio_start();
4555         atomic_inc(&rq->nr_iowait);
4556         blk_flush_plug(current);
4557         current->in_iowait = 1;
4558         ret = schedule_timeout(timeout);
4559         current->in_iowait = 0;
4560         atomic_dec(&rq->nr_iowait);
4561         delayacct_blkio_end();
4562         return ret;
4563 }
4564
4565 /**
4566  * sys_sched_get_priority_max - return maximum RT priority.
4567  * @policy: scheduling class.
4568  *
4569  * this syscall returns the maximum rt_priority that can be used
4570  * by a given scheduling class.
4571  */
4572 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
4573 {
4574         int ret = -EINVAL;
4575
4576         switch (policy) {
4577         case SCHED_FIFO:
4578         case SCHED_RR:
4579                 ret = MAX_USER_RT_PRIO-1;
4580                 break;
4581         case SCHED_NORMAL:
4582         case SCHED_BATCH:
4583         case SCHED_IDLE:
4584                 ret = 0;
4585                 break;
4586         }
4587         return ret;
4588 }
4589
4590 /**
4591  * sys_sched_get_priority_min - return minimum RT priority.
4592  * @policy: scheduling class.
4593  *
4594  * this syscall returns the minimum rt_priority that can be used
4595  * by a given scheduling class.
4596  */
4597 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
4598 {
4599         int ret = -EINVAL;
4600
4601         switch (policy) {
4602         case SCHED_FIFO:
4603         case SCHED_RR:
4604                 ret = 1;
4605                 break;
4606         case SCHED_NORMAL:
4607         case SCHED_BATCH:
4608         case SCHED_IDLE:
4609                 ret = 0;
4610         }
4611         return ret;
4612 }
4613
4614 /**
4615  * sys_sched_rr_get_interval - return the default timeslice of a process.
4616  * @pid: pid of the process.
4617  * @interval: userspace pointer to the timeslice value.
4618  *
4619  * this syscall writes the default timeslice value of a given process
4620  * into the user-space timespec buffer. A value of '0' means infinity.
4621  */
4622 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
4623                 struct timespec __user *, interval)
4624 {
4625         struct task_struct *p;
4626         unsigned int time_slice;
4627         unsigned long flags;
4628         struct rq *rq;
4629         int retval;
4630         struct timespec t;
4631
4632         if (pid < 0)
4633                 return -EINVAL;
4634
4635         retval = -ESRCH;
4636         rcu_read_lock();
4637         p = find_process_by_pid(pid);
4638         if (!p)
4639                 goto out_unlock;
4640
4641         retval = security_task_getscheduler(p);
4642         if (retval)
4643                 goto out_unlock;
4644
4645         rq = task_rq_lock(p, &flags);
4646         time_slice = p->sched_class->get_rr_interval(rq, p);
4647         task_rq_unlock(rq, p, &flags);
4648
4649         rcu_read_unlock();
4650         jiffies_to_timespec(time_slice, &t);
4651         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4652         return retval;
4653
4654 out_unlock:
4655         rcu_read_unlock();
4656         return retval;
4657 }
4658
4659 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
4660
4661 void sched_show_task(struct task_struct *p)
4662 {
4663         unsigned long free = 0;
4664         int ppid;
4665         unsigned state;
4666
4667         state = p->state ? __ffs(p->state) + 1 : 0;
4668         printk(KERN_INFO "%-15.15s %c", p->comm,
4669                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4670 #if BITS_PER_LONG == 32
4671         if (state == TASK_RUNNING)
4672                 printk(KERN_CONT " running  ");
4673         else
4674                 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
4675 #else
4676         if (state == TASK_RUNNING)
4677                 printk(KERN_CONT "  running task    ");
4678         else
4679                 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
4680 #endif
4681 #ifdef CONFIG_DEBUG_STACK_USAGE
4682         free = stack_not_used(p);
4683 #endif
4684         rcu_read_lock();
4685         ppid = task_pid_nr(rcu_dereference(p->real_parent));
4686         rcu_read_unlock();
4687         printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4688                 task_pid_nr(p), ppid,
4689                 (unsigned long)task_thread_info(p)->flags);
4690
4691         print_worker_info(KERN_INFO, p);
4692         show_stack(p, NULL);
4693 }
4694
4695 void show_state_filter(unsigned long state_filter)
4696 {
4697         struct task_struct *g, *p;
4698
4699 #if BITS_PER_LONG == 32
4700         printk(KERN_INFO
4701                 "  task                PC stack   pid father\n");
4702 #else
4703         printk(KERN_INFO
4704                 "  task                        PC stack   pid father\n");
4705 #endif
4706         rcu_read_lock();
4707         do_each_thread(g, p) {
4708                 /*
4709                  * reset the NMI-timeout, listing all files on a slow
4710                  * console might take a lot of time:
4711                  */
4712                 touch_nmi_watchdog();
4713                 if (!state_filter || (p->state & state_filter))
4714                         sched_show_task(p);
4715         } while_each_thread(g, p);
4716
4717         touch_all_softlockup_watchdogs();
4718
4719 #ifdef CONFIG_SCHED_DEBUG
4720         sysrq_sched_debug_show();
4721 #endif
4722         rcu_read_unlock();
4723         /*
4724          * Only show locks if all tasks are dumped:
4725          */
4726         if (!state_filter)
4727                 debug_show_all_locks();
4728 }
4729
4730 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4731 {
4732         idle->sched_class = &idle_sched_class;
4733 }
4734
4735 /**
4736  * init_idle - set up an idle thread for a given CPU
4737  * @idle: task in question
4738  * @cpu: cpu the idle task belongs to
4739  *
4740  * NOTE: this function does not set the idle thread's NEED_RESCHED
4741  * flag, to make booting more robust.
4742  */
4743 void __cpuinit init_idle(struct task_struct *idle, int cpu)
4744 {
4745         struct rq *rq = cpu_rq(cpu);
4746         unsigned long flags;
4747
4748         raw_spin_lock_irqsave(&rq->lock, flags);
4749
4750         __sched_fork(idle);
4751         idle->state = TASK_RUNNING;
4752         idle->se.exec_start = sched_clock();
4753
4754         do_set_cpus_allowed(idle, cpumask_of(cpu));
4755         /*
4756          * We're having a chicken and egg problem, even though we are
4757          * holding rq->lock, the cpu isn't yet set to this cpu so the
4758          * lockdep check in task_group() will fail.
4759          *
4760          * Similar case to sched_fork(). / Alternatively we could
4761          * use task_rq_lock() here and obtain the other rq->lock.
4762          *
4763          * Silence PROVE_RCU
4764          */
4765         rcu_read_lock();
4766         __set_task_cpu(idle, cpu);
4767         rcu_read_unlock();
4768
4769         rq->curr = rq->idle = idle;
4770 #if defined(CONFIG_SMP)
4771         idle->on_cpu = 1;
4772 #endif
4773         raw_spin_unlock_irqrestore(&rq->lock, flags);
4774
4775         /* Set the preempt count _outside_ the spinlocks! */
4776         task_thread_info(idle)->preempt_count = 0;
4777
4778         /*
4779          * The idle tasks have their own, simple scheduling class:
4780          */
4781         idle->sched_class = &idle_sched_class;
4782         ftrace_graph_init_idle_task(idle, cpu);
4783         vtime_init_idle(idle, cpu);
4784 #if defined(CONFIG_SMP)
4785         sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
4786 #endif
4787 }
4788
4789 #ifdef CONFIG_SMP
4790 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
4791 {
4792         if (p->sched_class && p->sched_class->set_cpus_allowed)
4793                 p->sched_class->set_cpus_allowed(p, new_mask);
4794
4795         cpumask_copy(&p->cpus_allowed, new_mask);
4796         p->nr_cpus_allowed = cpumask_weight(new_mask);
4797 }
4798
4799 /*
4800  * This is how migration works:
4801  *
4802  * 1) we invoke migration_cpu_stop() on the target CPU using
4803  *    stop_one_cpu().
4804  * 2) stopper starts to run (implicitly forcing the migrated thread
4805  *    off the CPU)
4806  * 3) it checks whether the migrated task is still in the wrong runqueue.
4807  * 4) if it's in the wrong runqueue then the migration thread removes
4808  *    it and puts it into the right queue.
4809  * 5) stopper completes and stop_one_cpu() returns and the migration
4810  *    is done.
4811  */
4812
4813 /*
4814  * Change a given task's CPU affinity. Migrate the thread to a
4815  * proper CPU and schedule it away if the CPU it's executing on
4816  * is removed from the allowed bitmask.
4817  *
4818  * NOTE: the caller must have a valid reference to the task, the
4819  * task must not exit() & deallocate itself prematurely. The
4820  * call is not atomic; no spinlocks may be held.
4821  */
4822 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
4823 {
4824         unsigned long flags;
4825         struct rq *rq;
4826         unsigned int dest_cpu;
4827         int ret = 0;
4828
4829         rq = task_rq_lock(p, &flags);
4830
4831         if (cpumask_equal(&p->cpus_allowed, new_mask))
4832                 goto out;
4833
4834         if (!cpumask_intersects(new_mask, cpu_active_mask)) {
4835                 ret = -EINVAL;
4836                 goto out;
4837         }
4838
4839         do_set_cpus_allowed(p, new_mask);
4840
4841         /* Can the task run on the task's current CPU? If so, we're done */
4842         if (cpumask_test_cpu(task_cpu(p), new_mask))
4843                 goto out;
4844
4845         dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
4846         if (p->on_rq) {
4847                 struct migration_arg arg = { p, dest_cpu };
4848                 /* Need help from migration thread: drop lock and wait. */
4849                 task_rq_unlock(rq, p, &flags);
4850                 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
4851                 tlb_migrate_finish(p->mm);
4852                 return 0;
4853         }
4854 out:
4855         task_rq_unlock(rq, p, &flags);
4856
4857         return ret;
4858 }
4859 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
4860
4861 /*
4862  * Move (not current) task off this cpu, onto dest cpu. We're doing
4863  * this because either it can't run here any more (set_cpus_allowed()
4864  * away from this CPU, or CPU going down), or because we're
4865  * attempting to rebalance this task on exec (sched_exec).
4866  *
4867  * So we race with normal scheduler movements, but that's OK, as long
4868  * as the task is no longer on this CPU.
4869  *
4870  * Returns non-zero if task was successfully migrated.
4871  */
4872 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4873 {
4874         struct rq *rq_dest, *rq_src;
4875         int ret = 0;
4876
4877         if (unlikely(!cpu_active(dest_cpu)))
4878                 return ret;
4879
4880         rq_src = cpu_rq(src_cpu);
4881         rq_dest = cpu_rq(dest_cpu);
4882
4883         raw_spin_lock(&p->pi_lock);
4884         double_rq_lock(rq_src, rq_dest);
4885         /* Already moved. */
4886         if (task_cpu(p) != src_cpu)
4887                 goto done;
4888         /* Affinity changed (again). */
4889         if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
4890                 goto fail;
4891
4892         /*
4893          * If we're not on a rq, the next wake-up will ensure we're
4894          * placed properly.
4895          */
4896         if (p->on_rq) {
4897                 dequeue_task(rq_src, p, 0);
4898                 set_task_cpu(p, dest_cpu);
4899                 enqueue_task(rq_dest, p, 0);
4900                 check_preempt_curr(rq_dest, p, 0);
4901         }
4902 done:
4903         ret = 1;
4904 fail:
4905         double_rq_unlock(rq_src, rq_dest);
4906         raw_spin_unlock(&p->pi_lock);
4907         return ret;
4908 }
4909
4910 /*
4911  * migration_cpu_stop - this will be executed by a highprio stopper thread
4912  * and performs thread migration by bumping thread off CPU then
4913  * 'pushing' onto another runqueue.
4914  */
4915 static int migration_cpu_stop(void *data)
4916 {
4917         struct migration_arg *arg = data;
4918
4919         /*
4920          * The original target cpu might have gone down and we might
4921          * be on another cpu but it doesn't matter.
4922          */
4923         local_irq_disable();
4924         __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
4925         local_irq_enable();
4926         return 0;
4927 }
4928
4929 #ifdef CONFIG_HOTPLUG_CPU
4930
4931 /*
4932  * Ensures that the idle task is using init_mm right before its cpu goes
4933  * offline.
4934  */
4935 void idle_task_exit(void)
4936 {
4937         struct mm_struct *mm = current->active_mm;
4938
4939         BUG_ON(cpu_online(smp_processor_id()));
4940
4941         if (mm != &init_mm)
4942                 switch_mm(mm, &init_mm, current);
4943         mmdrop(mm);
4944 }
4945
4946 /*
4947  * Since this CPU is going 'away' for a while, fold any nr_active delta
4948  * we might have. Assumes we're called after migrate_tasks() so that the
4949  * nr_active count is stable.
4950  *
4951  * Also see the comment "Global load-average calculations".
4952  */
4953 static void calc_load_migrate(struct rq *rq)
4954 {
4955         long delta = calc_load_fold_active(rq);
4956         if (delta)
4957                 atomic_long_add(delta, &calc_load_tasks);
4958 }
4959
4960 /*
4961  * Migrate all tasks from the rq, sleeping tasks will be migrated by
4962  * try_to_wake_up()->select_task_rq().
4963  *
4964  * Called with rq->lock held even though we'er in stop_machine() and
4965  * there's no concurrency possible, we hold the required locks anyway
4966  * because of lock validation efforts.
4967  */
4968 static void migrate_tasks(unsigned int dead_cpu)
4969 {
4970         struct rq *rq = cpu_rq(dead_cpu);
4971         struct task_struct *next, *stop = rq->stop;
4972         int dest_cpu;
4973
4974         /*
4975          * Fudge the rq selection such that the below task selection loop
4976          * doesn't get stuck on the currently eligible stop task.
4977          *
4978          * We're currently inside stop_machine() and the rq is either stuck
4979          * in the stop_machine_cpu_stop() loop, or we're executing this code,
4980          * either way we should never end up calling schedule() until we're
4981          * done here.
4982          */
4983         rq->stop = NULL;
4984
4985         for ( ; ; ) {
4986                 /*
4987                  * There's this thread running, bail when that's the only
4988                  * remaining thread.
4989                  */
4990                 if (rq->nr_running == 1)
4991                         break;
4992
4993                 next = pick_next_task(rq);
4994                 BUG_ON(!next);
4995                 next->sched_class->put_prev_task(rq, next);
4996
4997                 /* Find suitable destination for @next, with force if needed. */
4998                 dest_cpu = select_fallback_rq(dead_cpu, next);
4999                 raw_spin_unlock(&rq->lock);
5000
5001                 __migrate_task(next, dead_cpu, dest_cpu);
5002
5003                 raw_spin_lock(&rq->lock);
5004         }
5005
5006         rq->stop = stop;
5007 }
5008
5009 #endif /* CONFIG_HOTPLUG_CPU */
5010
5011 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5012
5013 static struct ctl_table sd_ctl_dir[] = {
5014         {
5015                 .procname       = "sched_domain",
5016                 .mode           = 0555,
5017         },
5018         {}
5019 };
5020
5021 static struct ctl_table sd_ctl_root[] = {
5022         {
5023                 .procname       = "kernel",
5024                 .mode           = 0555,
5025                 .child          = sd_ctl_dir,
5026         },
5027         {}
5028 };
5029
5030 static struct ctl_table *sd_alloc_ctl_entry(int n)
5031 {
5032         struct ctl_table *entry =
5033                 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5034
5035         return entry;
5036 }
5037
5038 static void sd_free_ctl_entry(struct ctl_table **tablep)
5039 {
5040         struct ctl_table *entry;
5041
5042         /*
5043          * In the intermediate directories, both the child directory and
5044          * procname are dynamically allocated and could fail but the mode
5045          * will always be set. In the lowest directory the names are
5046          * static strings and all have proc handlers.
5047          */
5048         for (entry = *tablep; entry->mode; entry++) {
5049                 if (entry->child)
5050                         sd_free_ctl_entry(&entry->child);
5051                 if (entry->proc_handler == NULL)
5052                         kfree(entry->procname);
5053         }
5054
5055         kfree(*tablep);
5056         *tablep = NULL;
5057 }
5058
5059 static int min_load_idx = 0;
5060 static int max_load_idx = CPU_LOAD_IDX_MAX-1;
5061
5062 static void
5063 set_table_entry(struct ctl_table *entry,
5064                 const char *procname, void *data, int maxlen,
5065                 umode_t mode, proc_handler *proc_handler,
5066                 bool load_idx)
5067 {
5068         entry->procname = procname;
5069         entry->data = data;
5070         entry->maxlen = maxlen;
5071         entry->mode = mode;
5072         entry->proc_handler = proc_handler;
5073
5074         if (load_idx) {
5075                 entry->extra1 = &min_load_idx;
5076                 entry->extra2 = &max_load_idx;
5077         }
5078 }
5079
5080 static struct ctl_table *
5081 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5082 {
5083         struct ctl_table *table = sd_alloc_ctl_entry(13);
5084
5085         if (table == NULL)
5086                 return NULL;
5087
5088         set_table_entry(&table[0], "min_interval", &sd->min_interval,
5089                 sizeof(long), 0644, proc_doulongvec_minmax, false);
5090         set_table_entry(&table[1], "max_interval", &sd->max_interval,
5091                 sizeof(long), 0644, proc_doulongvec_minmax, false);
5092         set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5093                 sizeof(int), 0644, proc_dointvec_minmax, true);
5094         set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5095                 sizeof(int), 0644, proc_dointvec_minmax, true);
5096         set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5097                 sizeof(int), 0644, proc_dointvec_minmax, true);
5098         set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5099                 sizeof(int), 0644, proc_dointvec_minmax, true);
5100         set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5101                 sizeof(int), 0644, proc_dointvec_minmax, true);
5102         set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5103                 sizeof(int), 0644, proc_dointvec_minmax, false);
5104         set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5105                 sizeof(int), 0644, proc_dointvec_minmax, false);
5106         set_table_entry(&table[9], "cache_nice_tries",
5107                 &sd->cache_nice_tries,
5108                 sizeof(int), 0644, proc_dointvec_minmax, false);
5109         set_table_entry(&table[10], "flags", &sd->flags,
5110                 sizeof(int), 0644, proc_dointvec_minmax, false);
5111         set_table_entry(&table[11], "name", sd->name,
5112                 CORENAME_MAX_SIZE, 0444, proc_dostring, false);
5113         /* &table[12] is terminator */
5114
5115         return table;
5116 }
5117
5118 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5119 {
5120         struct ctl_table *entry, *table;
5121         struct sched_domain *sd;
5122         int domain_num = 0, i;
5123         char buf[32];
5124
5125         for_each_domain(cpu, sd)
5126                 domain_num++;
5127         entry = table = sd_alloc_ctl_entry(domain_num + 1);
5128         if (table == NULL)
5129                 return NULL;
5130
5131         i = 0;
5132         for_each_domain(cpu, sd) {
5133                 snprintf(buf, 32, "domain%d", i);
5134                 entry->procname = kstrdup(buf, GFP_KERNEL);
5135                 entry->mode = 0555;
5136                 entry->child = sd_alloc_ctl_domain_table(sd);
5137                 entry++;
5138                 i++;
5139         }
5140         return table;
5141 }
5142
5143 static struct ctl_table_header *sd_sysctl_header;
5144 static void register_sched_domain_sysctl(void)
5145 {
5146         int i, cpu_num = num_possible_cpus();
5147         struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5148         char buf[32];
5149
5150         WARN_ON(sd_ctl_dir[0].child);
5151         sd_ctl_dir[0].child = entry;
5152
5153         if (entry == NULL)
5154                 return;
5155
5156         for_each_possible_cpu(i) {
5157                 snprintf(buf, 32, "cpu%d", i);
5158                 entry->procname = kstrdup(buf, GFP_KERNEL);
5159                 entry->mode = 0555;
5160                 entry->child = sd_alloc_ctl_cpu_table(i);
5161                 entry++;
5162         }
5163
5164         WARN_ON(sd_sysctl_header);
5165         sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5166 }
5167
5168 /* may be called multiple times per register */
5169 static void unregister_sched_domain_sysctl(void)
5170 {
5171         if (sd_sysctl_header)
5172                 unregister_sysctl_table(sd_sysctl_header);
5173         sd_sysctl_header = NULL;
5174         if (sd_ctl_dir[0].child)
5175                 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5176 }
5177 #else
5178 static void register_sched_domain_sysctl(void)
5179 {
5180 }
5181 static void unregister_sched_domain_sysctl(void)
5182 {
5183 }
5184 #endif
5185
5186 static void set_rq_online(struct rq *rq)
5187 {
5188         if (!rq->online) {
5189                 const struct sched_class *class;
5190
5191                 cpumask_set_cpu(rq->cpu, rq->rd->online);
5192                 rq->online = 1;
5193
5194                 for_each_class(class) {
5195                         if (class->rq_online)
5196                                 class->rq_online(rq);
5197                 }
5198         }
5199 }
5200
5201 static void set_rq_offline(struct rq *rq)
5202 {
5203         if (rq->online) {
5204                 const struct sched_class *class;
5205
5206                 for_each_class(class) {
5207                         if (class->rq_offline)
5208                                 class->rq_offline(rq);
5209                 }
5210
5211                 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5212                 rq->online = 0;
5213         }
5214 }
5215
5216 /*
5217  * migration_call - callback that gets triggered when a CPU is added.
5218  * Here we can start up the necessary migration thread for the new CPU.
5219  */
5220 static int __cpuinit
5221 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5222 {
5223         int cpu = (long)hcpu;
5224         unsigned long flags;
5225         struct rq *rq = cpu_rq(cpu);
5226
5227         switch (action & ~CPU_TASKS_FROZEN) {
5228
5229         case CPU_UP_PREPARE:
5230                 rq->calc_load_update = calc_load_update;
5231                 break;
5232
5233         case CPU_ONLINE:
5234                 /* Update our root-domain */
5235                 raw_spin_lock_irqsave(&rq->lock, flags);
5236                 if (rq->rd) {
5237                         BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5238
5239                         set_rq_online(rq);
5240                 }
5241                 raw_spin_unlock_irqrestore(&rq->lock, flags);
5242                 break;
5243
5244 #ifdef CONFIG_HOTPLUG_CPU
5245         case CPU_DYING:
5246                 sched_ttwu_pending();
5247                 /* Update our root-domain */
5248                 raw_spin_lock_irqsave(&rq->lock, flags);
5249                 if (rq->rd) {
5250                         BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5251                         set_rq_offline(rq);
5252                 }
5253                 migrate_tasks(cpu);
5254                 BUG_ON(rq->nr_running != 1); /* the migration thread */
5255                 raw_spin_unlock_irqrestore(&rq->lock, flags);
5256                 break;
5257
5258         case CPU_DEAD:
5259                 calc_load_migrate(rq);
5260                 break;
5261 #endif
5262         }
5263
5264         update_max_interval();
5265
5266         return NOTIFY_OK;
5267 }
5268
5269 /*
5270  * Register at high priority so that task migration (migrate_all_tasks)
5271  * happens before everything else.  This has to be lower priority than
5272  * the notifier in the perf_event subsystem, though.
5273  */
5274 static struct notifier_block __cpuinitdata migration_notifier = {
5275         .notifier_call = migration_call,
5276         .priority = CPU_PRI_MIGRATION,
5277 };
5278
5279 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5280                                       unsigned long action, void *hcpu)
5281 {
5282         switch (action & ~CPU_TASKS_FROZEN) {
5283         case CPU_STARTING:
5284         case CPU_DOWN_FAILED:
5285                 set_cpu_active((long)hcpu, true);
5286                 return NOTIFY_OK;
5287         default:
5288                 return NOTIFY_DONE;
5289         }
5290 }
5291
5292 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5293                                         unsigned long action, void *hcpu)
5294 {
5295         switch (action & ~CPU_TASKS_FROZEN) {
5296         case CPU_DOWN_PREPARE:
5297                 set_cpu_active((long)hcpu, false);
5298                 return NOTIFY_OK;
5299         default:
5300                 return NOTIFY_DONE;
5301         }
5302 }
5303
5304 static int __init migration_init(void)
5305 {
5306         void *cpu = (void *)(long)smp_processor_id();
5307         int err;
5308
5309         /* Initialize migration for the boot CPU */
5310         err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5311         BUG_ON(err == NOTIFY_BAD);
5312         migration_call(&migration_notifier, CPU_ONLINE, cpu);
5313         register_cpu_notifier(&migration_notifier);
5314
5315         /* Register cpu active notifiers */
5316         cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5317         cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5318
5319         return 0;
5320 }
5321 early_initcall(migration_init);
5322 #endif
5323
5324 #ifdef CONFIG_SMP
5325
5326 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5327
5328 #ifdef CONFIG_SCHED_DEBUG
5329
5330 static __read_mostly int sched_debug_enabled;
5331
5332 static int __init sched_debug_setup(char *str)
5333 {
5334         sched_debug_enabled = 1;
5335
5336         return 0;
5337 }
5338 early_param("sched_debug", sched_debug_setup);
5339
5340 static inline bool sched_debug(void)
5341 {
5342         return sched_debug_enabled;
5343 }
5344
5345 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5346                                   struct cpumask *groupmask)
5347 {
5348         struct sched_group *group = sd->groups;
5349         char str[256];
5350
5351         cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
5352         cpumask_clear(groupmask);
5353
5354         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5355
5356         if (!(sd->flags & SD_LOAD_BALANCE)) {
5357                 printk("does not load-balance\n");
5358                 if (sd->parent)
5359                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5360                                         " has parent");
5361                 return -1;
5362         }
5363
5364         printk(KERN_CONT "span %s level %s\n", str, sd->name);
5365
5366         if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5367                 printk(KERN_ERR "ERROR: domain->span does not contain "
5368                                 "CPU%d\n", cpu);
5369         }
5370         if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5371                 printk(KERN_ERR "ERROR: domain->groups does not contain"
5372                                 " CPU%d\n", cpu);
5373         }
5374
5375         printk(KERN_DEBUG "%*s groups:", level + 1, "");
5376         do {
5377                 if (!group) {
5378                         printk("\n");
5379                         printk(KERN_ERR "ERROR: group is NULL\n");
5380                         break;
5381                 }
5382
5383                 /*
5384                  * Even though we initialize ->power to something semi-sane,
5385                  * we leave power_orig unset. This allows us to detect if
5386                  * domain iteration is still funny without causing /0 traps.
5387                  */
5388                 if (!group->sgp->power_orig) {
5389                         printk(KERN_CONT "\n");
5390                         printk(KERN_ERR "ERROR: domain->cpu_power not "
5391                                         "set\n");
5392                         break;
5393                 }
5394
5395                 if (!cpumask_weight(sched_group_cpus(group))) {
5396                         printk(KERN_CONT "\n");
5397                         printk(KERN_ERR "ERROR: empty group\n");
5398                         break;
5399                 }
5400
5401                 if (!(sd->flags & SD_OVERLAP) &&
5402                     cpumask_intersects(groupmask, sched_group_cpus(group))) {
5403                         printk(KERN_CONT "\n");
5404                         printk(KERN_ERR "ERROR: repeated CPUs\n");
5405                         break;
5406                 }
5407
5408                 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5409
5410                 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
5411
5412                 printk(KERN_CONT " %s", str);
5413                 if (group->sgp->power != SCHED_POWER_SCALE) {
5414                         printk(KERN_CONT " (cpu_power = %d)",
5415                                 group->sgp->power);
5416                 }
5417
5418                 group = group->next;
5419         } while (group != sd->groups);
5420         printk(KERN_CONT "\n");
5421
5422         if (!cpumask_equal(sched_domain_span(sd), groupmask))
5423                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5424
5425         if (sd->parent &&
5426             !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5427                 printk(KERN_ERR "ERROR: parent span is not a superset "
5428                         "of domain->span\n");
5429         return 0;
5430 }
5431
5432 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5433 {
5434         int level = 0;
5435
5436         if (!sched_debug_enabled)
5437                 return;
5438
5439         if (!sd) {
5440                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5441                 return;
5442         }
5443
5444         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5445
5446         for (;;) {
5447                 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5448                         break;
5449                 level++;
5450                 sd = sd->parent;
5451                 if (!sd)
5452                         break;
5453         }
5454 }
5455 #else /* !CONFIG_SCHED_DEBUG */
5456 # define sched_domain_debug(sd, cpu) do { } while (0)
5457 static inline bool sched_debug(void)
5458 {
5459         return false;
5460 }
5461 #endif /* CONFIG_SCHED_DEBUG */
5462
5463 static int sd_degenerate(struct sched_domain *sd)
5464 {
5465         if (cpumask_weight(sched_domain_span(sd)) == 1)
5466                 return 1;
5467
5468         /* Following flags need at least 2 groups */
5469         if (sd->flags & (SD_LOAD_BALANCE |
5470                          SD_BALANCE_NEWIDLE |
5471                          SD_BALANCE_FORK |
5472                          SD_BALANCE_EXEC |
5473                          SD_SHARE_CPUPOWER |
5474                          SD_SHARE_PKG_RESOURCES)) {
5475                 if (sd->groups != sd->groups->next)
5476                         return 0;
5477         }
5478
5479         /* Following flags don't use groups */
5480         if (sd->flags & (SD_WAKE_AFFINE))
5481                 return 0;
5482
5483         return 1;
5484 }
5485
5486 static int
5487 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5488 {
5489         unsigned long cflags = sd->flags, pflags = parent->flags;
5490
5491         if (sd_degenerate(parent))
5492                 return 1;
5493
5494         if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5495                 return 0;
5496
5497         /* Flags needing groups don't count if only 1 group in parent */
5498         if (parent->groups == parent->groups->next) {
5499                 pflags &= ~(SD_LOAD_BALANCE |
5500                                 SD_BALANCE_NEWIDLE |
5501                                 SD_BALANCE_FORK |
5502                                 SD_BALANCE_EXEC |
5503                                 SD_SHARE_CPUPOWER |
5504                                 SD_SHARE_PKG_RESOURCES);
5505                 if (nr_node_ids == 1)
5506                         pflags &= ~SD_SERIALIZE;
5507         }
5508         if (~cflags & pflags)
5509                 return 0;
5510
5511         return 1;
5512 }
5513
5514 static void free_rootdomain(struct rcu_head *rcu)
5515 {
5516         struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5517
5518         cpupri_cleanup(&rd->cpupri);
5519         free_cpumask_var(rd->rto_mask);
5520         free_cpumask_var(rd->online);
5521         free_cpumask_var(rd->span);
5522         kfree(rd);
5523 }
5524
5525 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5526 {
5527         struct root_domain *old_rd = NULL;
5528         unsigned long flags;
5529
5530         raw_spin_lock_irqsave(&rq->lock, flags);
5531
5532         if (rq->rd) {
5533                 old_rd = rq->rd;
5534
5535                 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5536                         set_rq_offline(rq);
5537
5538                 cpumask_clear_cpu(rq->cpu, old_rd->span);
5539
5540                 /*
5541                  * If we dont want to free the old_rt yet then
5542                  * set old_rd to NULL to skip the freeing later
5543                  * in this function:
5544                  */
5545                 if (!atomic_dec_and_test(&old_rd->refcount))
5546                         old_rd = NULL;
5547         }
5548
5549         atomic_inc(&rd->refcount);
5550         rq->rd = rd;
5551
5552         cpumask_set_cpu(rq->cpu, rd->span);
5553         if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5554                 set_rq_online(rq);
5555
5556         raw_spin_unlock_irqrestore(&rq->lock, flags);
5557
5558         if (old_rd)
5559                 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5560 }
5561
5562 static int init_rootdomain(struct root_domain *rd)
5563 {
5564         memset(rd, 0, sizeof(*rd));
5565
5566         if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
5567                 goto out;
5568         if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
5569                 goto free_span;
5570         if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5571                 goto free_online;
5572
5573         if (cpupri_init(&rd->cpupri) != 0)
5574                 goto free_rto_mask;
5575         return 0;
5576
5577 free_rto_mask:
5578         free_cpumask_var(rd->rto_mask);
5579 free_online:
5580         free_cpumask_var(rd->online);
5581 free_span:
5582         free_cpumask_var(rd->span);
5583 out:
5584         return -ENOMEM;
5585 }
5586
5587 /*
5588  * By default the system creates a single root-domain with all cpus as
5589  * members (mimicking the global state we have today).
5590  */
5591 struct root_domain def_root_domain;
5592
5593 static void init_defrootdomain(void)
5594 {
5595         init_rootdomain(&def_root_domain);
5596
5597         atomic_set(&def_root_domain.refcount, 1);
5598 }
5599
5600 static struct root_domain *alloc_rootdomain(void)
5601 {
5602         struct root_domain *rd;
5603
5604         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5605         if (!rd)
5606                 return NULL;
5607
5608         if (init_rootdomain(rd) != 0) {
5609                 kfree(rd);
5610                 return NULL;
5611         }
5612
5613         return rd;
5614 }
5615
5616 static void free_sched_groups(struct sched_group *sg, int free_sgp)
5617 {
5618         struct sched_group *tmp, *first;
5619
5620         if (!sg)
5621                 return;
5622
5623         first = sg;
5624         do {
5625                 tmp = sg->next;
5626
5627                 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
5628                         kfree(sg->sgp);
5629
5630                 kfree(sg);
5631                 sg = tmp;
5632         } while (sg != first);
5633 }
5634
5635 static void free_sched_domain(struct rcu_head *rcu)
5636 {
5637         struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5638
5639         /*
5640          * If its an overlapping domain it has private groups, iterate and
5641          * nuke them all.
5642          */
5643         if (sd->flags & SD_OVERLAP) {
5644                 free_sched_groups(sd->groups, 1);
5645         } else if (atomic_dec_and_test(&sd->groups->ref)) {
5646                 kfree(sd->groups->sgp);
5647                 kfree(sd->groups);
5648         }
5649         kfree(sd);
5650 }
5651
5652 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5653 {
5654         call_rcu(&sd->rcu, free_sched_domain);
5655 }
5656
5657 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5658 {
5659         for (; sd; sd = sd->parent)
5660                 destroy_sched_domain(sd, cpu);
5661 }
5662
5663 /*
5664  * Keep a special pointer to the highest sched_domain that has
5665  * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5666  * allows us to avoid some pointer chasing select_idle_sibling().
5667  *
5668  * Also keep a unique ID per domain (we use the first cpu number in
5669  * the cpumask of the domain), this allows us to quickly tell if
5670  * two cpus are in the same cache domain, see cpus_share_cache().
5671  */
5672 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5673 DEFINE_PER_CPU(int, sd_llc_id);
5674
5675 static void update_top_cache_domain(int cpu)
5676 {
5677         struct sched_domain *sd;
5678         int id = cpu;
5679
5680         sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
5681         if (sd)
5682                 id = cpumask_first(sched_domain_span(sd));
5683
5684         rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5685         per_cpu(sd_llc_id, cpu) = id;
5686 }
5687
5688 /*
5689  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5690  * hold the hotplug lock.
5691  */
5692 static void
5693 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5694 {
5695         struct rq *rq = cpu_rq(cpu);
5696         struct sched_domain *tmp;
5697
5698         /* Remove the sched domains which do not contribute to scheduling. */
5699         for (tmp = sd; tmp; ) {
5700                 struct sched_domain *parent = tmp->parent;
5701                 if (!parent)
5702                         break;
5703
5704                 if (sd_parent_degenerate(tmp, parent)) {
5705                         tmp->parent = parent->parent;
5706                         if (parent->parent)
5707                                 parent->parent->child = tmp;
5708                         destroy_sched_domain(parent, cpu);
5709                 } else
5710                         tmp = tmp->parent;
5711         }
5712
5713         if (sd && sd_degenerate(sd)) {
5714                 tmp = sd;
5715                 sd = sd->parent;
5716                 destroy_sched_domain(tmp, cpu);
5717                 if (sd)
5718                         sd->child = NULL;
5719         }
5720
5721         sched_domain_debug(sd, cpu);
5722
5723         rq_attach_root(rq, rd);
5724         tmp = rq->sd;
5725         rcu_assign_pointer(rq->sd, sd);
5726         destroy_sched_domains(tmp, cpu);
5727
5728         update_top_cache_domain(cpu);
5729 }
5730
5731 /* cpus with isolated domains */
5732 static cpumask_var_t cpu_isolated_map;
5733
5734 /* Setup the mask of cpus configured for isolated domains */
5735 static int __init isolated_cpu_setup(char *str)
5736 {
5737         alloc_bootmem_cpumask_var(&cpu_isolated_map);
5738         cpulist_parse(str, cpu_isolated_map);
5739         return 1;
5740 }
5741
5742 __setup("isolcpus=", isolated_cpu_setup);
5743
5744 static const struct cpumask *cpu_cpu_mask(int cpu)
5745 {
5746         return cpumask_of_node(cpu_to_node(cpu));
5747 }
5748
5749 struct sd_data {
5750         struct sched_domain **__percpu sd;
5751         struct sched_group **__percpu sg;
5752         struct sched_group_power **__percpu sgp;
5753 };
5754
5755 struct s_data {
5756         struct sched_domain ** __percpu sd;
5757         struct root_domain      *rd;
5758 };
5759
5760 enum s_alloc {
5761         sa_rootdomain,
5762         sa_sd,
5763         sa_sd_storage,
5764         sa_none,
5765 };
5766
5767 struct sched_domain_topology_level;
5768
5769 typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
5770 typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
5771
5772 #define SDTL_OVERLAP    0x01
5773
5774 struct sched_domain_topology_level {
5775         sched_domain_init_f init;
5776         sched_domain_mask_f mask;
5777         int                 flags;
5778         int                 numa_level;
5779         struct sd_data      data;
5780 };
5781
5782 /*
5783  * Build an iteration mask that can exclude certain CPUs from the upwards
5784  * domain traversal.
5785  *
5786  * Asymmetric node setups can result in situations where the domain tree is of
5787  * unequal depth, make sure to skip domains that already cover the entire
5788  * range.
5789  *
5790  * In that case build_sched_domains() will have terminated the iteration early
5791  * and our sibling sd spans will be empty. Domains should always include the
5792  * cpu they're built on, so check that.
5793  *
5794  */
5795 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5796 {
5797         const struct cpumask *span = sched_domain_span(sd);
5798         struct sd_data *sdd = sd->private;
5799         struct sched_domain *sibling;
5800         int i;
5801
5802         for_each_cpu(i, span) {
5803                 sibling = *per_cpu_ptr(sdd->sd, i);
5804                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5805                         continue;
5806
5807                 cpumask_set_cpu(i, sched_group_mask(sg));
5808         }
5809 }
5810
5811 /*
5812  * Return the canonical balance cpu for this group, this is the first cpu
5813  * of this group that's also in the iteration mask.
5814  */
5815 int group_balance_cpu(struct sched_group *sg)
5816 {
5817         return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
5818 }
5819
5820 static int
5821 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
5822 {
5823         struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
5824         const struct cpumask *span = sched_domain_span(sd);
5825         struct cpumask *covered = sched_domains_tmpmask;
5826         struct sd_data *sdd = sd->private;
5827         struct sched_domain *child;
5828         int i;
5829
5830         cpumask_clear(covered);
5831
5832         for_each_cpu(i, span) {
5833                 struct cpumask *sg_span;
5834
5835                 if (cpumask_test_cpu(i, covered))
5836                         continue;
5837
5838                 child = *per_cpu_ptr(sdd->sd, i);
5839
5840                 /* See the comment near build_group_mask(). */
5841                 if (!cpumask_test_cpu(i, sched_domain_span(child)))
5842                         continue;
5843
5844                 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
5845                                 GFP_KERNEL, cpu_to_node(cpu));
5846
5847                 if (!sg)
5848                         goto fail;
5849
5850                 sg_span = sched_group_cpus(sg);
5851                 if (child->child) {
5852                         child = child->child;
5853                         cpumask_copy(sg_span, sched_domain_span(child));
5854                 } else
5855                         cpumask_set_cpu(i, sg_span);
5856
5857                 cpumask_or(covered, covered, sg_span);
5858
5859                 sg->sgp = *per_cpu_ptr(sdd->sgp, i);
5860                 if (atomic_inc_return(&sg->sgp->ref) == 1)
5861                         build_group_mask(sd, sg);
5862
5863                 /*
5864                  * Initialize sgp->power such that even if we mess up the
5865                  * domains and no possible iteration will get us here, we won't
5866                  * die on a /0 trap.
5867                  */
5868                 sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span);
5869
5870                 /*
5871                  * Make sure the first group of this domain contains the
5872                  * canonical balance cpu. Otherwise the sched_domain iteration
5873                  * breaks. See update_sg_lb_stats().
5874                  */
5875                 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
5876                     group_balance_cpu(sg) == cpu)
5877                         groups = sg;
5878
5879                 if (!first)
5880                         first = sg;
5881                 if (last)
5882                         last->next = sg;
5883                 last = sg;
5884                 last->next = first;
5885         }
5886         sd->groups = groups;
5887
5888         return 0;
5889
5890 fail:
5891         free_sched_groups(first, 0);
5892
5893         return -ENOMEM;
5894 }
5895
5896 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
5897 {
5898         struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
5899         struct sched_domain *child = sd->child;
5900
5901         if (child)
5902                 cpu = cpumask_first(sched_domain_span(child));
5903
5904         if (sg) {
5905                 *sg = *per_cpu_ptr(sdd->sg, cpu);
5906                 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
5907                 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
5908         }
5909
5910         return cpu;
5911 }
5912
5913 /*
5914  * build_sched_groups will build a circular linked list of the groups
5915  * covered by the given span, and will set each group's ->cpumask correctly,
5916  * and ->cpu_power to 0.
5917  *
5918  * Assumes the sched_domain tree is fully constructed
5919  */
5920 static int
5921 build_sched_groups(struct sched_domain *sd, int cpu)
5922 {
5923         struct sched_group *first = NULL, *last = NULL;
5924         struct sd_data *sdd = sd->private;
5925         const struct cpumask *span = sched_domain_span(sd);
5926         struct cpumask *covered;
5927         int i;
5928
5929         get_group(cpu, sdd, &sd->groups);
5930         atomic_inc(&sd->groups->ref);
5931
5932         if (cpu != cpumask_first(sched_domain_span(sd)))
5933                 return 0;
5934
5935         lockdep_assert_held(&sched_domains_mutex);
5936         covered = sched_domains_tmpmask;
5937
5938         cpumask_clear(covered);
5939
5940         for_each_cpu(i, span) {
5941                 struct sched_group *sg;
5942                 int group = get_group(i, sdd, &sg);
5943                 int j;
5944
5945                 if (cpumask_test_cpu(i, covered))
5946                         continue;
5947
5948                 cpumask_clear(sched_group_cpus(sg));
5949                 sg->sgp->power = 0;
5950                 cpumask_setall(sched_group_mask(sg));
5951
5952                 for_each_cpu(j, span) {
5953                         if (get_group(j, sdd, NULL) != group)
5954                                 continue;
5955
5956                         cpumask_set_cpu(j, covered);
5957                         cpumask_set_cpu(j, sched_group_cpus(sg));
5958                 }
5959
5960                 if (!first)
5961                         first = sg;
5962                 if (last)
5963                         last->next = sg;
5964                 last = sg;
5965         }
5966         last->next = first;
5967
5968         return 0;
5969 }
5970
5971 /*
5972  * Initialize sched groups cpu_power.
5973  *
5974  * cpu_power indicates the capacity of sched group, which is used while
5975  * distributing the load between different sched groups in a sched domain.
5976  * Typically cpu_power for all the groups in a sched domain will be same unless
5977  * there are asymmetries in the topology. If there are asymmetries, group
5978  * having more cpu_power will pickup more load compared to the group having
5979  * less cpu_power.
5980  */
5981 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5982 {
5983         struct sched_group *sg = sd->groups;
5984
5985         WARN_ON(!sd || !sg);
5986
5987         do {
5988                 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
5989                 sg = sg->next;
5990         } while (sg != sd->groups);
5991
5992         if (cpu != group_balance_cpu(sg))
5993                 return;
5994
5995         update_group_power(sd, cpu);
5996         atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
5997 }
5998
5999 int __weak arch_sd_sibling_asym_packing(void)
6000 {
6001        return 0*SD_ASYM_PACKING;
6002 }
6003
6004 /*
6005  * Initializers for schedule domains
6006  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6007  */
6008
6009 #ifdef CONFIG_SCHED_DEBUG
6010 # define SD_INIT_NAME(sd, type)         sd->name = #type
6011 #else
6012 # define SD_INIT_NAME(sd, type)         do { } while (0)
6013 #endif
6014
6015 #define SD_INIT_FUNC(type)                                              \
6016 static noinline struct sched_domain *                                   \
6017 sd_init_##type(struct sched_domain_topology_level *tl, int cpu)         \
6018 {                                                                       \
6019         struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);       \
6020         *sd = SD_##type##_INIT;                                         \
6021         SD_INIT_NAME(sd, type);                                         \
6022         sd->private = &tl->data;                                        \
6023         return sd;                                                      \
6024 }
6025
6026 SD_INIT_FUNC(CPU)
6027 #ifdef CONFIG_SCHED_SMT
6028  SD_INIT_FUNC(SIBLING)
6029 #endif
6030 #ifdef CONFIG_SCHED_MC
6031  SD_INIT_FUNC(MC)
6032 #endif
6033 #ifdef CONFIG_SCHED_BOOK
6034  SD_INIT_FUNC(BOOK)
6035 #endif
6036
6037 static int default_relax_domain_level = -1;
6038 int sched_domain_level_max;
6039
6040 static int __init setup_relax_domain_level(char *str)
6041 {
6042         if (kstrtoint(str, 0, &default_relax_domain_level))
6043                 pr_warn("Unable to set relax_domain_level\n");
6044
6045         return 1;
6046 }
6047 __setup("relax_domain_level=", setup_relax_domain_level);
6048
6049 static void set_domain_attribute(struct sched_domain *sd,
6050                                  struct sched_domain_attr *attr)
6051 {
6052         int request;
6053
6054         if (!attr || attr->relax_domain_level < 0) {
6055                 if (default_relax_domain_level < 0)
6056                         return;
6057                 else
6058                         request = default_relax_domain_level;
6059         } else
6060                 request = attr->relax_domain_level;
6061         if (request < sd->level) {
6062                 /* turn off idle balance on this domain */
6063                 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6064         } else {
6065                 /* turn on idle balance on this domain */
6066                 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6067         }
6068 }
6069
6070 static void __sdt_free(const struct cpumask *cpu_map);
6071 static int __sdt_alloc(const struct cpumask *cpu_map);
6072
6073 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6074                                  const struct cpumask *cpu_map)
6075 {
6076         switch (what) {
6077         case sa_rootdomain:
6078                 if (!atomic_read(&d->rd->refcount))
6079                         free_rootdomain(&d->rd->rcu); /* fall through */
6080         case sa_sd:
6081                 free_percpu(d->sd); /* fall through */
6082         case sa_sd_storage:
6083                 __sdt_free(cpu_map); /* fall through */
6084         case sa_none:
6085                 break;
6086         }
6087 }
6088
6089 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6090                                                    const struct cpumask *cpu_map)
6091 {
6092         memset(d, 0, sizeof(*d));
6093
6094         if (__sdt_alloc(cpu_map))
6095                 return sa_sd_storage;
6096         d->sd = alloc_percpu(struct sched_domain *);
6097         if (!d->sd)
6098                 return sa_sd_storage;
6099         d->rd = alloc_rootdomain();
6100         if (!d->rd)
6101                 return sa_sd;
6102         return sa_rootdomain;
6103 }
6104
6105 /*
6106  * NULL the sd_data elements we've used to build the sched_domain and
6107  * sched_group structure so that the subsequent __free_domain_allocs()
6108  * will not free the data we're using.
6109  */
6110 static void claim_allocations(int cpu, struct sched_domain *sd)
6111 {
6112         struct sd_data *sdd = sd->private;
6113
6114         WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6115         *per_cpu_ptr(sdd->sd, cpu) = NULL;
6116
6117         if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6118                 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6119
6120         if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
6121                 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
6122 }
6123
6124 #ifdef CONFIG_SCHED_SMT
6125 static const struct cpumask *cpu_smt_mask(int cpu)
6126 {
6127         return topology_thread_cpumask(cpu);
6128 }
6129 #endif
6130
6131 /*
6132  * Topology list, bottom-up.
6133  */
6134 static struct sched_domain_topology_level default_topology[] = {
6135 #ifdef CONFIG_SCHED_SMT
6136         { sd_init_SIBLING, cpu_smt_mask, },
6137 #endif
6138 #ifdef CONFIG_SCHED_MC
6139         { sd_init_MC, cpu_coregroup_mask, },
6140 #endif
6141 #ifdef CONFIG_SCHED_BOOK
6142         { sd_init_BOOK, cpu_book_mask, },
6143 #endif
6144         { sd_init_CPU, cpu_cpu_mask, },
6145         { NULL, },
6146 };
6147
6148 static struct sched_domain_topology_level *sched_domain_topology = default_topology;
6149
6150 #ifdef CONFIG_NUMA
6151
6152 static int sched_domains_numa_levels;
6153 static int *sched_domains_numa_distance;
6154 static struct cpumask ***sched_domains_numa_masks;
6155 static int sched_domains_curr_level;
6156
6157 static inline int sd_local_flags(int level)
6158 {
6159         if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE)
6160                 return 0;
6161
6162         return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE;
6163 }
6164
6165 static struct sched_domain *
6166 sd_numa_init(struct sched_domain_topology_level *tl, int cpu)
6167 {
6168         struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6169         int level = tl->numa_level;
6170         int sd_weight = cpumask_weight(
6171                         sched_domains_numa_masks[level][cpu_to_node(cpu)]);
6172
6173         *sd = (struct sched_domain){
6174                 .min_interval           = sd_weight,
6175                 .max_interval           = 2*sd_weight,
6176                 .busy_factor            = 32,
6177                 .imbalance_pct          = 125,
6178                 .cache_nice_tries       = 2,
6179                 .busy_idx               = 3,
6180                 .idle_idx               = 2,
6181                 .newidle_idx            = 0,
6182                 .wake_idx               = 0,
6183                 .forkexec_idx           = 0,
6184
6185                 .flags                  = 1*SD_LOAD_BALANCE
6186                                         | 1*SD_BALANCE_NEWIDLE
6187                                         | 0*SD_BALANCE_EXEC
6188                                         | 0*SD_BALANCE_FORK
6189                                         | 0*SD_BALANCE_WAKE
6190                                         | 0*SD_WAKE_AFFINE
6191                                         | 0*SD_SHARE_CPUPOWER
6192                                         | 0*SD_SHARE_PKG_RESOURCES
6193                                         | 1*SD_SERIALIZE
6194                                         | 0*SD_PREFER_SIBLING
6195                                         | sd_local_flags(level)
6196                                         ,
6197                 .last_balance           = jiffies,
6198                 .balance_interval       = sd_weight,
6199         };
6200         SD_INIT_NAME(sd, NUMA);
6201         sd->private = &tl->data;
6202
6203         /*
6204          * Ugly hack to pass state to sd_numa_mask()...
6205          */
6206         sched_domains_curr_level = tl->numa_level;
6207
6208         return sd;
6209 }
6210
6211 static const struct cpumask *sd_numa_mask(int cpu)
6212 {
6213         return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6214 }
6215
6216 static void sched_numa_warn(const char *str)
6217 {
6218         static int done = false;
6219         int i,j;
6220
6221         if (done)
6222                 return;
6223
6224         done = true;
6225
6226         printk(KERN_WARNING "ERROR: %s\n\n", str);
6227
6228         for (i = 0; i < nr_node_ids; i++) {
6229                 printk(KERN_WARNING "  ");
6230                 for (j = 0; j < nr_node_ids; j++)
6231                         printk(KERN_CONT "%02d ", node_distance(i,j));
6232                 printk(KERN_CONT "\n");
6233         }
6234         printk(KERN_WARNING "\n");
6235 }
6236
6237 static bool find_numa_distance(int distance)
6238 {
6239         int i;
6240
6241         if (distance == node_distance(0, 0))
6242                 return true;
6243
6244         for (i = 0; i < sched_domains_numa_levels; i++) {
6245                 if (sched_domains_numa_distance[i] == distance)
6246                         return true;
6247         }
6248
6249         return false;
6250 }
6251
6252 static void sched_init_numa(void)
6253 {
6254         int next_distance, curr_distance = node_distance(0, 0);
6255         struct sched_domain_topology_level *tl;
6256         int level = 0;
6257         int i, j, k;
6258
6259         sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6260         if (!sched_domains_numa_distance)
6261                 return;
6262
6263         /*
6264          * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6265          * unique distances in the node_distance() table.
6266          *
6267          * Assumes node_distance(0,j) includes all distances in
6268          * node_distance(i,j) in order to avoid cubic time.
6269          */
6270         next_distance = curr_distance;
6271         for (i = 0; i < nr_node_ids; i++) {
6272                 for (j = 0; j < nr_node_ids; j++) {
6273                         for (k = 0; k < nr_node_ids; k++) {
6274                                 int distance = node_distance(i, k);
6275
6276                                 if (distance > curr_distance &&
6277                                     (distance < next_distance ||
6278                                      next_distance == curr_distance))
6279                                         next_distance = distance;
6280
6281                                 /*
6282                                  * While not a strong assumption it would be nice to know
6283                                  * about cases where if node A is connected to B, B is not
6284                                  * equally connected to A.
6285                                  */
6286                                 if (sched_debug() && node_distance(k, i) != distance)
6287                                         sched_numa_warn("Node-distance not symmetric");
6288
6289                                 if (sched_debug() && i && !find_numa_distance(distance))
6290                                         sched_numa_warn("Node-0 not representative");
6291                         }
6292                         if (next_distance != curr_distance) {
6293                                 sched_domains_numa_distance[level++] = next_distance;
6294                                 sched_domains_numa_levels = level;
6295                                 curr_distance = next_distance;
6296                         } else break;
6297                 }
6298
6299                 /*
6300                  * In case of sched_debug() we verify the above assumption.
6301                  */
6302                 if (!sched_debug())
6303                         break;
6304         }
6305         /*
6306          * 'level' contains the number of unique distances, excluding the
6307          * identity distance node_distance(i,i).
6308          *
6309          * The sched_domains_numa_distance[] array includes the actual distance
6310          * numbers.
6311          */
6312
6313         /*
6314          * Here, we should temporarily reset sched_domains_numa_levels to 0.
6315          * If it fails to allocate memory for array sched_domains_numa_masks[][],
6316          * the array will contain less then 'level' members. This could be
6317          * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6318          * in other functions.
6319          *
6320          * We reset it to 'level' at the end of this function.
6321          */
6322         sched_domains_numa_levels = 0;
6323
6324         sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6325         if (!sched_domains_numa_masks)
6326                 return;
6327
6328         /*
6329          * Now for each level, construct a mask per node which contains all
6330          * cpus of nodes that are that many hops away from us.
6331          */
6332         for (i = 0; i < level; i++) {
6333                 sched_domains_numa_masks[i] =
6334                         kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6335                 if (!sched_domains_numa_masks[i])
6336                         return;
6337
6338                 for (j = 0; j < nr_node_ids; j++) {
6339                         struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6340                         if (!mask)
6341                                 return;
6342
6343                         sched_domains_numa_masks[i][j] = mask;
6344
6345                         for (k = 0; k < nr_node_ids; k++) {
6346                                 if (node_distance(j, k) > sched_domains_numa_distance[i])
6347                                         continue;
6348
6349                                 cpumask_or(mask, mask, cpumask_of_node(k));
6350                         }
6351                 }
6352         }
6353
6354         tl = kzalloc((ARRAY_SIZE(default_topology) + level) *
6355                         sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6356         if (!tl)
6357                 return;
6358
6359         /*
6360          * Copy the default topology bits..
6361          */
6362         for (i = 0; default_topology[i].init; i++)
6363                 tl[i] = default_topology[i];
6364
6365         /*
6366          * .. and append 'j' levels of NUMA goodness.
6367          */
6368         for (j = 0; j < level; i++, j++) {
6369                 tl[i] = (struct sched_domain_topology_level){
6370                         .init = sd_numa_init,
6371                         .mask = sd_numa_mask,
6372                         .flags = SDTL_OVERLAP,
6373                         .numa_level = j,
6374                 };
6375         }
6376
6377         sched_domain_topology = tl;
6378
6379         sched_domains_numa_levels = level;
6380 }
6381
6382 static void sched_domains_numa_masks_set(int cpu)
6383 {
6384         int i, j;
6385         int node = cpu_to_node(cpu);
6386
6387         for (i = 0; i < sched_domains_numa_levels; i++) {
6388                 for (j = 0; j < nr_node_ids; j++) {
6389                         if (node_distance(j, node) <= sched_domains_numa_distance[i])
6390                                 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6391                 }
6392         }
6393 }
6394
6395 static void sched_domains_numa_masks_clear(int cpu)
6396 {
6397         int i, j;
6398         for (i = 0; i < sched_domains_numa_levels; i++) {
6399                 for (j = 0; j < nr_node_ids; j++)
6400                         cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6401         }
6402 }
6403
6404 /*
6405  * Update sched_domains_numa_masks[level][node] array when new cpus
6406  * are onlined.
6407  */
6408 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6409                                            unsigned long action,
6410                                            void *hcpu)
6411 {
6412         int cpu = (long)hcpu;
6413
6414         switch (action & ~CPU_TASKS_FROZEN) {
6415         case CPU_ONLINE:
6416                 sched_domains_numa_masks_set(cpu);
6417                 break;
6418
6419         case CPU_DEAD:
6420                 sched_domains_numa_masks_clear(cpu);
6421                 break;
6422
6423         default:
6424                 return NOTIFY_DONE;
6425         }
6426
6427         return NOTIFY_OK;
6428 }
6429 #else
6430 static inline void sched_init_numa(void)
6431 {
6432 }
6433
6434 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6435                                            unsigned long action,
6436                                            void *hcpu)
6437 {
6438         return 0;
6439 }
6440 #endif /* CONFIG_NUMA */
6441
6442 static int __sdt_alloc(const struct cpumask *cpu_map)
6443 {
6444         struct sched_domain_topology_level *tl;
6445         int j;
6446
6447         for (tl = sched_domain_topology; tl->init; tl++) {
6448                 struct sd_data *sdd = &tl->data;
6449
6450                 sdd->sd = alloc_percpu(struct sched_domain *);
6451                 if (!sdd->sd)
6452                         return -ENOMEM;
6453
6454                 sdd->sg = alloc_percpu(struct sched_group *);
6455                 if (!sdd->sg)
6456                         return -ENOMEM;
6457
6458                 sdd->sgp = alloc_percpu(struct sched_group_power *);
6459                 if (!sdd->sgp)
6460                         return -ENOMEM;
6461
6462                 for_each_cpu(j, cpu_map) {
6463                         struct sched_domain *sd;
6464                         struct sched_group *sg;
6465                         struct sched_group_power *sgp;
6466
6467                         sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6468                                         GFP_KERNEL, cpu_to_node(j));
6469                         if (!sd)
6470                                 return -ENOMEM;
6471
6472                         *per_cpu_ptr(sdd->sd, j) = sd;
6473
6474                         sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6475                                         GFP_KERNEL, cpu_to_node(j));
6476                         if (!sg)
6477                                 return -ENOMEM;
6478
6479                         sg->next = sg;
6480
6481                         *per_cpu_ptr(sdd->sg, j) = sg;
6482
6483                         sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(),
6484                                         GFP_KERNEL, cpu_to_node(j));
6485                         if (!sgp)
6486                                 return -ENOMEM;
6487
6488                         *per_cpu_ptr(sdd->sgp, j) = sgp;
6489                 }
6490         }
6491
6492         return 0;
6493 }
6494
6495 static void __sdt_free(const struct cpumask *cpu_map)
6496 {
6497         struct sched_domain_topology_level *tl;
6498         int j;
6499
6500         for (tl = sched_domain_topology; tl->init; tl++) {
6501                 struct sd_data *sdd = &tl->data;
6502
6503                 for_each_cpu(j, cpu_map) {
6504                         struct sched_domain *sd;
6505
6506                         if (sdd->sd) {
6507                                 sd = *per_cpu_ptr(sdd->sd, j);
6508                                 if (sd && (sd->flags & SD_OVERLAP))
6509                                         free_sched_groups(sd->groups, 0);
6510                                 kfree(*per_cpu_ptr(sdd->sd, j));
6511                         }
6512
6513                         if (sdd->sg)
6514                                 kfree(*per_cpu_ptr(sdd->sg, j));
6515                         if (sdd->sgp)
6516                                 kfree(*per_cpu_ptr(sdd->sgp, j));
6517                 }
6518                 free_percpu(sdd->sd);
6519                 sdd->sd = NULL;
6520                 free_percpu(sdd->sg);
6521                 sdd->sg = NULL;
6522                 free_percpu(sdd->sgp);
6523                 sdd->sgp = NULL;
6524         }
6525 }
6526
6527 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6528                 struct s_data *d, const struct cpumask *cpu_map,
6529                 struct sched_domain_attr *attr, struct sched_domain *child,
6530                 int cpu)
6531 {
6532         struct sched_domain *sd = tl->init(tl, cpu);
6533         if (!sd)
6534                 return child;
6535
6536         cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6537         if (child) {
6538                 sd->level = child->level + 1;
6539                 sched_domain_level_max = max(sched_domain_level_max, sd->level);
6540                 child->parent = sd;
6541         }
6542         sd->child = child;
6543         set_domain_attribute(sd, attr);
6544
6545         return sd;
6546 }
6547
6548 /*
6549  * Build sched domains for a given set of cpus and attach the sched domains
6550  * to the individual cpus
6551  */
6552 static int build_sched_domains(const struct cpumask *cpu_map,
6553                                struct sched_domain_attr *attr)
6554 {
6555         enum s_alloc alloc_state = sa_none;
6556         struct sched_domain *sd;
6557         struct s_data d;
6558         int i, ret = -ENOMEM;
6559
6560         alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6561         if (alloc_state != sa_rootdomain)
6562                 goto error;
6563
6564         /* Set up domains for cpus specified by the cpu_map. */
6565         for_each_cpu(i, cpu_map) {
6566                 struct sched_domain_topology_level *tl;
6567
6568                 sd = NULL;
6569                 for (tl = sched_domain_topology; tl->init; tl++) {
6570                         sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
6571                         if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6572                                 sd->flags |= SD_OVERLAP;
6573                         if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6574                                 break;
6575                 }
6576
6577                 while (sd->child)
6578                         sd = sd->child;
6579
6580                 *per_cpu_ptr(d.sd, i) = sd;
6581         }
6582
6583         /* Build the groups for the domains */
6584         for_each_cpu(i, cpu_map) {
6585                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6586                         sd->span_weight = cpumask_weight(sched_domain_span(sd));
6587                         if (sd->flags & SD_OVERLAP) {
6588                                 if (build_overlap_sched_groups(sd, i))
6589                                         goto error;
6590                         } else {
6591                                 if (build_sched_groups(sd, i))
6592                                         goto error;
6593                         }
6594                 }
6595         }
6596
6597         /* Calculate CPU power for physical packages and nodes */
6598         for (i = nr_cpumask_bits-1; i >= 0; i--) {
6599                 if (!cpumask_test_cpu(i, cpu_map))
6600                         continue;
6601
6602                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6603                         claim_allocations(i, sd);
6604                         init_sched_groups_power(i, sd);
6605                 }
6606         }
6607
6608         /* Attach the domains */
6609         rcu_read_lock();
6610         for_each_cpu(i, cpu_map) {
6611                 sd = *per_cpu_ptr(d.sd, i);
6612                 cpu_attach_domain(sd, d.rd, i);
6613         }
6614         rcu_read_unlock();
6615
6616         ret = 0;
6617 error:
6618         __free_domain_allocs(&d, alloc_state, cpu_map);
6619         return ret;
6620 }
6621
6622 static cpumask_var_t *doms_cur; /* current sched domains */
6623 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
6624 static struct sched_domain_attr *dattr_cur;
6625                                 /* attribues of custom domains in 'doms_cur' */
6626
6627 /*
6628  * Special case: If a kmalloc of a doms_cur partition (array of
6629  * cpumask) fails, then fallback to a single sched domain,
6630  * as determined by the single cpumask fallback_doms.
6631  */
6632 static cpumask_var_t fallback_doms;
6633
6634 /*
6635  * arch_update_cpu_topology lets virtualized architectures update the
6636  * cpu core maps. It is supposed to return 1 if the topology changed
6637  * or 0 if it stayed the same.
6638  */
6639 int __attribute__((weak)) arch_update_cpu_topology(void)
6640 {
6641         return 0;
6642 }
6643
6644 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6645 {
6646         int i;
6647         cpumask_var_t *doms;
6648
6649         doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6650         if (!doms)
6651                 return NULL;
6652         for (i = 0; i < ndoms; i++) {
6653                 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6654                         free_sched_domains(doms, i);
6655                         return NULL;
6656                 }
6657         }
6658         return doms;
6659 }
6660
6661 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6662 {
6663         unsigned int i;
6664         for (i = 0; i < ndoms; i++)
6665                 free_cpumask_var(doms[i]);
6666         kfree(doms);
6667 }
6668
6669 /*
6670  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6671  * For now this just excludes isolated cpus, but could be used to
6672  * exclude other special cases in the future.
6673  */
6674 static int init_sched_domains(const struct cpumask *cpu_map)
6675 {
6676         int err;
6677
6678         arch_update_cpu_topology();
6679         ndoms_cur = 1;
6680         doms_cur = alloc_sched_domains(ndoms_cur);
6681         if (!doms_cur)
6682                 doms_cur = &fallback_doms;
6683         cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
6684         err = build_sched_domains(doms_cur[0], NULL);
6685         register_sched_domain_sysctl();
6686
6687         return err;
6688 }
6689
6690 /*
6691  * Detach sched domains from a group of cpus specified in cpu_map
6692  * These cpus will now be attached to the NULL domain
6693  */
6694 static void detach_destroy_domains(const struct cpumask *cpu_map)
6695 {
6696         int i;
6697
6698         rcu_read_lock();
6699         for_each_cpu(i, cpu_map)
6700                 cpu_attach_domain(NULL, &def_root_domain, i);
6701         rcu_read_unlock();
6702 }
6703
6704 /* handle null as "default" */
6705 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6706                         struct sched_domain_attr *new, int idx_new)
6707 {
6708         struct sched_domain_attr tmp;
6709
6710         /* fast path */
6711         if (!new && !cur)
6712                 return 1;
6713
6714         tmp = SD_ATTR_INIT;
6715         return !memcmp(cur ? (cur + idx_cur) : &tmp,
6716                         new ? (new + idx_new) : &tmp,
6717                         sizeof(struct sched_domain_attr));
6718 }
6719
6720 /*
6721  * Partition sched domains as specified by the 'ndoms_new'
6722  * cpumasks in the array doms_new[] of cpumasks. This compares
6723  * doms_new[] to the current sched domain partitioning, doms_cur[].
6724  * It destroys each deleted domain and builds each new domain.
6725  *
6726  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
6727  * The masks don't intersect (don't overlap.) We should setup one
6728  * sched domain for each mask. CPUs not in any of the cpumasks will
6729  * not be load balanced. If the same cpumask appears both in the
6730  * current 'doms_cur' domains and in the new 'doms_new', we can leave
6731  * it as it is.
6732  *
6733  * The passed in 'doms_new' should be allocated using
6734  * alloc_sched_domains.  This routine takes ownership of it and will
6735  * free_sched_domains it when done with it. If the caller failed the
6736  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
6737  * and partition_sched_domains() will fallback to the single partition
6738  * 'fallback_doms', it also forces the domains to be rebuilt.
6739  *
6740  * If doms_new == NULL it will be replaced with cpu_online_mask.
6741  * ndoms_new == 0 is a special case for destroying existing domains,
6742  * and it will not create the default domain.
6743  *
6744  * Call with hotplug lock held
6745  */
6746 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
6747                              struct sched_domain_attr *dattr_new)
6748 {
6749         int i, j, n;
6750         int new_topology;
6751
6752         mutex_lock(&sched_domains_mutex);
6753
6754         /* always unregister in case we don't destroy any domains */
6755         unregister_sched_domain_sysctl();
6756
6757         /* Let architecture update cpu core mappings. */
6758         new_topology = arch_update_cpu_topology();
6759
6760         n = doms_new ? ndoms_new : 0;
6761
6762         /* Destroy deleted domains */
6763         for (i = 0; i < ndoms_cur; i++) {
6764                 for (j = 0; j < n && !new_topology; j++) {
6765                         if (cpumask_equal(doms_cur[i], doms_new[j])
6766                             && dattrs_equal(dattr_cur, i, dattr_new, j))
6767                                 goto match1;
6768                 }
6769                 /* no match - a current sched domain not in new doms_new[] */
6770                 detach_destroy_domains(doms_cur[i]);
6771 match1:
6772                 ;
6773         }
6774
6775         if (doms_new == NULL) {
6776                 ndoms_cur = 0;
6777                 doms_new = &fallback_doms;
6778                 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
6779                 WARN_ON_ONCE(dattr_new);
6780         }
6781
6782         /* Build new domains */
6783         for (i = 0; i < ndoms_new; i++) {
6784                 for (j = 0; j < ndoms_cur && !new_topology; j++) {
6785                         if (cpumask_equal(doms_new[i], doms_cur[j])
6786                             && dattrs_equal(dattr_new, i, dattr_cur, j))
6787                                 goto match2;
6788                 }
6789                 /* no match - add a new doms_new */
6790                 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
6791 match2:
6792                 ;
6793         }
6794
6795         /* Remember the new sched domains */
6796         if (doms_cur != &fallback_doms)
6797                 free_sched_domains(doms_cur, ndoms_cur);
6798         kfree(dattr_cur);       /* kfree(NULL) is safe */
6799         doms_cur = doms_new;
6800         dattr_cur = dattr_new;
6801         ndoms_cur = ndoms_new;
6802
6803         register_sched_domain_sysctl();
6804
6805         mutex_unlock(&sched_domains_mutex);
6806 }
6807
6808 static int num_cpus_frozen;     /* used to mark begin/end of suspend/resume */
6809
6810 /*
6811  * Update cpusets according to cpu_active mask.  If cpusets are
6812  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
6813  * around partition_sched_domains().
6814  *
6815  * If we come here as part of a suspend/resume, don't touch cpusets because we
6816  * want to restore it back to its original state upon resume anyway.
6817  */
6818 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
6819                              void *hcpu)
6820 {
6821         switch (action) {
6822         case CPU_ONLINE_FROZEN:
6823         case CPU_DOWN_FAILED_FROZEN:
6824
6825                 /*
6826                  * num_cpus_frozen tracks how many CPUs are involved in suspend
6827                  * resume sequence. As long as this is not the last online
6828                  * operation in the resume sequence, just build a single sched
6829                  * domain, ignoring cpusets.
6830                  */
6831                 num_cpus_frozen--;
6832                 if (likely(num_cpus_frozen)) {
6833                         partition_sched_domains(1, NULL, NULL);
6834                         break;
6835                 }
6836
6837                 /*
6838                  * This is the last CPU online operation. So fall through and
6839                  * restore the original sched domains by considering the
6840                  * cpuset configurations.
6841                  */
6842
6843         case CPU_ONLINE:
6844         case CPU_DOWN_FAILED:
6845                 cpuset_update_active_cpus(true);
6846                 break;
6847         default:
6848                 return NOTIFY_DONE;
6849         }
6850         return NOTIFY_OK;
6851 }
6852
6853 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
6854                                void *hcpu)
6855 {
6856         switch (action) {
6857         case CPU_DOWN_PREPARE:
6858                 cpuset_update_active_cpus(false);
6859                 break;
6860         case CPU_DOWN_PREPARE_FROZEN:
6861                 num_cpus_frozen++;
6862                 partition_sched_domains(1, NULL, NULL);
6863                 break;
6864         default:
6865                 return NOTIFY_DONE;
6866         }
6867         return NOTIFY_OK;
6868 }
6869
6870 void __init sched_init_smp(void)
6871 {
6872         cpumask_var_t non_isolated_cpus;
6873
6874         alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
6875         alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
6876
6877         sched_init_numa();
6878
6879         get_online_cpus();
6880         mutex_lock(&sched_domains_mutex);
6881         init_sched_domains(cpu_active_mask);
6882         cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
6883         if (cpumask_empty(non_isolated_cpus))
6884                 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
6885         mutex_unlock(&sched_domains_mutex);
6886         put_online_cpus();
6887
6888         hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
6889         hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
6890         hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
6891
6892         /* RT runtime code needs to handle some hotplug events */
6893         hotcpu_notifier(update_runtime, 0);
6894
6895         init_hrtick();
6896
6897         /* Move init over to a non-isolated CPU */
6898         if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
6899                 BUG();
6900         sched_init_granularity();
6901         free_cpumask_var(non_isolated_cpus);
6902
6903         init_sched_rt_class();
6904 }
6905 #else
6906 void __init sched_init_smp(void)
6907 {
6908         sched_init_granularity();
6909 }
6910 #endif /* CONFIG_SMP */
6911
6912 const_debug unsigned int sysctl_timer_migration = 1;
6913
6914 int in_sched_functions(unsigned long addr)
6915 {
6916         return in_lock_functions(addr) ||
6917                 (addr >= (unsigned long)__sched_text_start
6918                 && addr < (unsigned long)__sched_text_end);
6919 }
6920
6921 #ifdef CONFIG_CGROUP_SCHED
6922 /*
6923  * Default task group.
6924  * Every task in system belongs to this group at bootup.
6925  */
6926 struct task_group root_task_group;
6927 LIST_HEAD(task_groups);
6928 #endif
6929
6930 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
6931
6932 void __init sched_init(void)
6933 {
6934         int i, j;
6935         unsigned long alloc_size = 0, ptr;
6936
6937 #ifdef CONFIG_FAIR_GROUP_SCHED
6938         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
6939 #endif
6940 #ifdef CONFIG_RT_GROUP_SCHED
6941         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
6942 #endif
6943 #ifdef CONFIG_CPUMASK_OFFSTACK
6944         alloc_size += num_possible_cpus() * cpumask_size();
6945 #endif
6946         if (alloc_size) {
6947                 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
6948
6949 #ifdef CONFIG_FAIR_GROUP_SCHED
6950                 root_task_group.se = (struct sched_entity **)ptr;
6951                 ptr += nr_cpu_ids * sizeof(void **);
6952
6953                 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
6954                 ptr += nr_cpu_ids * sizeof(void **);
6955
6956 #endif /* CONFIG_FAIR_GROUP_SCHED */
6957 #ifdef CONFIG_RT_GROUP_SCHED
6958                 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
6959                 ptr += nr_cpu_ids * sizeof(void **);
6960
6961                 root_task_group.rt_rq = (struct rt_rq **)ptr;
6962                 ptr += nr_cpu_ids * sizeof(void **);
6963
6964 #endif /* CONFIG_RT_GROUP_SCHED */
6965 #ifdef CONFIG_CPUMASK_OFFSTACK
6966                 for_each_possible_cpu(i) {
6967                         per_cpu(load_balance_mask, i) = (void *)ptr;
6968                         ptr += cpumask_size();
6969                 }
6970 #endif /* CONFIG_CPUMASK_OFFSTACK */
6971         }
6972
6973 #ifdef CONFIG_SMP
6974         init_defrootdomain();
6975 #endif
6976
6977         init_rt_bandwidth(&def_rt_bandwidth,
6978                         global_rt_period(), global_rt_runtime());
6979
6980 #ifdef CONFIG_RT_GROUP_SCHED
6981         init_rt_bandwidth(&root_task_group.rt_bandwidth,
6982                         global_rt_period(), global_rt_runtime());
6983 #endif /* CONFIG_RT_GROUP_SCHED */
6984
6985 #ifdef CONFIG_CGROUP_SCHED
6986         list_add(&root_task_group.list, &task_groups);
6987         INIT_LIST_HEAD(&root_task_group.children);
6988         INIT_LIST_HEAD(&root_task_group.siblings);
6989         autogroup_init(&init_task);
6990
6991 #endif /* CONFIG_CGROUP_SCHED */
6992
6993         for_each_possible_cpu(i) {
6994                 struct rq *rq;
6995
6996                 rq = cpu_rq(i);
6997                 raw_spin_lock_init(&rq->lock);
6998                 rq->nr_running = 0;
6999                 rq->calc_load_active = 0;
7000                 rq->calc_load_update = jiffies + LOAD_FREQ;
7001                 init_cfs_rq(&rq->cfs);
7002                 init_rt_rq(&rq->rt, rq);
7003 #ifdef CONFIG_FAIR_GROUP_SCHED
7004                 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7005                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7006                 /*
7007                  * How much cpu bandwidth does root_task_group get?
7008                  *
7009                  * In case of task-groups formed thr' the cgroup filesystem, it
7010                  * gets 100% of the cpu resources in the system. This overall
7011                  * system cpu resource is divided among the tasks of
7012                  * root_task_group and its child task-groups in a fair manner,
7013                  * based on each entity's (task or task-group's) weight
7014                  * (se->load.weight).
7015                  *
7016                  * In other words, if root_task_group has 10 tasks of weight
7017                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
7018                  * then A0's share of the cpu resource is:
7019                  *
7020                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7021                  *
7022                  * We achieve this by letting root_task_group's tasks sit
7023                  * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7024                  */
7025                 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7026                 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7027 #endif /* CONFIG_FAIR_GROUP_SCHED */
7028
7029                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7030 #ifdef CONFIG_RT_GROUP_SCHED
7031                 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7032                 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7033 #endif
7034
7035                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7036                         rq->cpu_load[j] = 0;
7037
7038                 rq->last_load_update_tick = jiffies;
7039
7040 #ifdef CONFIG_SMP
7041                 rq->sd = NULL;
7042                 rq->rd = NULL;
7043                 rq->cpu_power = SCHED_POWER_SCALE;
7044                 rq->post_schedule = 0;
7045                 rq->active_balance = 0;
7046                 rq->next_balance = jiffies;
7047                 rq->push_cpu = 0;
7048                 rq->cpu = i;
7049                 rq->online = 0;
7050                 rq->idle_stamp = 0;
7051                 rq->avg_idle = 2*sysctl_sched_migration_cost;
7052
7053                 INIT_LIST_HEAD(&rq->cfs_tasks);
7054
7055                 rq_attach_root(rq, &def_root_domain);
7056 #ifdef CONFIG_NO_HZ_COMMON
7057                 rq->nohz_flags = 0;
7058 #endif
7059 #ifdef CONFIG_NO_HZ_FULL
7060                 rq->last_sched_tick = 0;
7061 #endif
7062 #endif
7063                 init_rq_hrtick(rq);
7064                 atomic_set(&rq->nr_iowait, 0);
7065         }
7066
7067         set_load_weight(&init_task);
7068
7069 #ifdef CONFIG_PREEMPT_NOTIFIERS
7070         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7071 #endif
7072
7073 #ifdef CONFIG_RT_MUTEXES
7074         plist_head_init(&init_task.pi_waiters);
7075 #endif
7076
7077         /*
7078          * The boot idle thread does lazy MMU switching as well:
7079          */
7080         atomic_inc(&init_mm.mm_count);
7081         enter_lazy_tlb(&init_mm, current);
7082
7083         /*
7084          * Make us the idle thread. Technically, schedule() should not be
7085          * called from this thread, however somewhere below it might be,
7086          * but because we are the idle thread, we just pick up running again
7087          * when this runqueue becomes "idle".
7088          */
7089         init_idle(current, smp_processor_id());
7090
7091         calc_load_update = jiffies + LOAD_FREQ;
7092
7093         /*
7094          * During early bootup we pretend to be a normal task:
7095          */
7096         current->sched_class = &fair_sched_class;
7097
7098 #ifdef CONFIG_SMP
7099         zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7100         /* May be allocated at isolcpus cmdline parse time */
7101         if (cpu_isolated_map == NULL)
7102                 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7103         idle_thread_set_boot_cpu();
7104 #endif
7105         init_sched_fair_class();
7106
7107         scheduler_running = 1;
7108 }
7109
7110 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7111 static inline int preempt_count_equals(int preempt_offset)
7112 {
7113         int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7114
7115         return (nested == preempt_offset);
7116 }
7117
7118 static int __might_sleep_init_called;
7119 int __init __might_sleep_init(void)
7120 {
7121         __might_sleep_init_called = 1;
7122         return 0;
7123 }
7124 early_initcall(__might_sleep_init);
7125
7126 void __might_sleep(const char *file, int line, int preempt_offset)
7127 {
7128         static unsigned long prev_jiffy;        /* ratelimiting */
7129
7130         rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7131         if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7132             oops_in_progress)
7133                 return;
7134         if (system_state != SYSTEM_RUNNING &&
7135             (!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
7136                 return;
7137         if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7138                 return;
7139         prev_jiffy = jiffies;
7140
7141         printk(KERN_ERR
7142                 "BUG: sleeping function called from invalid context at %s:%d\n",
7143                         file, line);
7144         printk(KERN_ERR
7145                 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7146                         in_atomic(), irqs_disabled(),
7147                         current->pid, current->comm);
7148
7149         debug_show_held_locks(current);
7150         if (irqs_disabled())
7151                 print_irqtrace_events(current);
7152         dump_stack();
7153 }
7154 EXPORT_SYMBOL(__might_sleep);
7155 #endif
7156
7157 #ifdef CONFIG_MAGIC_SYSRQ
7158 static void normalize_task(struct rq *rq, struct task_struct *p)
7159 {
7160         const struct sched_class *prev_class = p->sched_class;
7161         int old_prio = p->prio;
7162         int on_rq;
7163
7164         on_rq = p->on_rq;
7165         if (on_rq)
7166                 dequeue_task(rq, p, 0);
7167         __setscheduler(rq, p, SCHED_NORMAL, 0);
7168         if (on_rq) {
7169                 enqueue_task(rq, p, 0);
7170                 resched_task(rq->curr);
7171         }
7172
7173         check_class_changed(rq, p, prev_class, old_prio);
7174 }
7175
7176 void normalize_rt_tasks(void)
7177 {
7178         struct task_struct *g, *p;
7179         unsigned long flags;
7180         struct rq *rq;
7181
7182         read_lock_irqsave(&tasklist_lock, flags);
7183         do_each_thread(g, p) {
7184                 /*
7185                  * Only normalize user tasks:
7186                  */
7187                 if (!p->mm)
7188                         continue;
7189
7190                 p->se.exec_start                = 0;
7191 #ifdef CONFIG_SCHEDSTATS
7192                 p->se.statistics.wait_start     = 0;
7193                 p->se.statistics.sleep_start    = 0;
7194                 p->se.statistics.block_start    = 0;
7195 #endif
7196
7197                 if (!rt_task(p)) {
7198                         /*
7199                          * Renice negative nice level userspace
7200                          * tasks back to 0:
7201                          */
7202                         if (TASK_NICE(p) < 0 && p->mm)
7203                                 set_user_nice(p, 0);
7204                         continue;
7205                 }
7206
7207                 raw_spin_lock(&p->pi_lock);
7208                 rq = __task_rq_lock(p);
7209
7210                 normalize_task(rq, p);
7211
7212                 __task_rq_unlock(rq);
7213                 raw_spin_unlock(&p->pi_lock);
7214         } while_each_thread(g, p);
7215
7216         read_unlock_irqrestore(&tasklist_lock, flags);
7217 }
7218
7219 #endif /* CONFIG_MAGIC_SYSRQ */
7220
7221 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7222 /*
7223  * These functions are only useful for the IA64 MCA handling, or kdb.
7224  *
7225  * They can only be called when the whole system has been
7226  * stopped - every CPU needs to be quiescent, and no scheduling
7227  * activity can take place. Using them for anything else would
7228  * be a serious bug, and as a result, they aren't even visible
7229  * under any other configuration.
7230  */
7231
7232 /**
7233  * curr_task - return the current task for a given cpu.
7234  * @cpu: the processor in question.
7235  *
7236  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7237  */
7238 struct task_struct *curr_task(int cpu)
7239 {
7240         return cpu_curr(cpu);
7241 }
7242
7243 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7244
7245 #ifdef CONFIG_IA64
7246 /**
7247  * set_curr_task - set the current task for a given cpu.
7248  * @cpu: the processor in question.
7249  * @p: the task pointer to set.
7250  *
7251  * Description: This function must only be used when non-maskable interrupts
7252  * are serviced on a separate stack. It allows the architecture to switch the
7253  * notion of the current task on a cpu in a non-blocking manner. This function
7254  * must be called with all CPU's synchronized, and interrupts disabled, the
7255  * and caller must save the original value of the current task (see
7256  * curr_task() above) and restore that value before reenabling interrupts and
7257  * re-starting the system.
7258  *
7259  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7260  */
7261 void set_curr_task(int cpu, struct task_struct *p)
7262 {
7263         cpu_curr(cpu) = p;
7264 }
7265
7266 #endif
7267
7268 #ifdef CONFIG_CGROUP_SCHED
7269 /* task_group_lock serializes the addition/removal of task groups */
7270 static DEFINE_SPINLOCK(task_group_lock);
7271
7272 static void free_sched_group(struct task_group *tg)
7273 {
7274         free_fair_sched_group(tg);
7275         free_rt_sched_group(tg);
7276         autogroup_free(tg);
7277         kfree(tg);
7278 }
7279
7280 /* allocate runqueue etc for a new task group */
7281 struct task_group *sched_create_group(struct task_group *parent)
7282 {
7283         struct task_group *tg;
7284
7285         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7286         if (!tg)
7287                 return ERR_PTR(-ENOMEM);
7288
7289         if (!alloc_fair_sched_group(tg, parent))
7290                 goto err;
7291
7292         if (!alloc_rt_sched_group(tg, parent))
7293                 goto err;
7294
7295         return tg;
7296
7297 err:
7298         free_sched_group(tg);
7299         return ERR_PTR(-ENOMEM);
7300 }
7301
7302 void sched_online_group(struct task_group *tg, struct task_group *parent)
7303 {
7304         unsigned long flags;
7305
7306         spin_lock_irqsave(&task_group_lock, flags);
7307         list_add_rcu(&tg->list, &task_groups);
7308
7309         WARN_ON(!parent); /* root should already exist */
7310
7311         tg->parent = parent;
7312         INIT_LIST_HEAD(&tg->children);
7313         list_add_rcu(&tg->siblings, &parent->children);
7314         spin_unlock_irqrestore(&task_group_lock, flags);
7315 }
7316
7317 /* rcu callback to free various structures associated with a task group */
7318 static void free_sched_group_rcu(struct rcu_head *rhp)
7319 {
7320         /* now it should be safe to free those cfs_rqs */
7321         free_sched_group(container_of(rhp, struct task_group, rcu));
7322 }
7323
7324 /* Destroy runqueue etc associated with a task group */
7325 void sched_destroy_group(struct task_group *tg)
7326 {
7327         /* wait for possible concurrent references to cfs_rqs complete */
7328         call_rcu(&tg->rcu, free_sched_group_rcu);
7329 }
7330
7331 void sched_offline_group(struct task_group *tg)
7332 {
7333         unsigned long flags;
7334         int i;
7335
7336         /* end participation in shares distribution */
7337         for_each_possible_cpu(i)
7338                 unregister_fair_sched_group(tg, i);
7339
7340         spin_lock_irqsave(&task_group_lock, flags);
7341         list_del_rcu(&tg->list);
7342         list_del_rcu(&tg->siblings);
7343         spin_unlock_irqrestore(&task_group_lock, flags);
7344 }
7345
7346 /* change task's runqueue when it moves between groups.
7347  *      The caller of this function should have put the task in its new group
7348  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7349  *      reflect its new group.
7350  */
7351 void sched_move_task(struct task_struct *tsk)
7352 {
7353         struct task_group *tg;
7354         int on_rq, running;
7355         unsigned long flags;
7356         struct rq *rq;
7357
7358         rq = task_rq_lock(tsk, &flags);
7359
7360         running = task_current(rq, tsk);
7361         on_rq = tsk->on_rq;
7362
7363         if (on_rq)
7364                 dequeue_task(rq, tsk, 0);
7365         if (unlikely(running))
7366                 tsk->sched_class->put_prev_task(rq, tsk);
7367
7368         tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id,
7369                                 lockdep_is_held(&tsk->sighand->siglock)),
7370                           struct task_group, css);
7371         tg = autogroup_task_group(tsk, tg);
7372         tsk->sched_task_group = tg;
7373
7374 #ifdef CONFIG_FAIR_GROUP_SCHED
7375         if (tsk->sched_class->task_move_group)
7376                 tsk->sched_class->task_move_group(tsk, on_rq);
7377         else
7378 #endif
7379                 set_task_rq(tsk, task_cpu(tsk));
7380
7381         if (unlikely(running))
7382                 tsk->sched_class->set_curr_task(rq);
7383         if (on_rq)
7384                 enqueue_task(rq, tsk, 0);
7385
7386         task_rq_unlock(rq, tsk, &flags);
7387 }
7388 #endif /* CONFIG_CGROUP_SCHED */
7389
7390 #if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH)
7391 static unsigned long to_ratio(u64 period, u64 runtime)
7392 {
7393         if (runtime == RUNTIME_INF)
7394                 return 1ULL << 20;
7395
7396         return div64_u64(runtime << 20, period);
7397 }
7398 #endif
7399
7400 #ifdef CONFIG_RT_GROUP_SCHED
7401 /*
7402  * Ensure that the real time constraints are schedulable.
7403  */
7404 static DEFINE_MUTEX(rt_constraints_mutex);
7405
7406 /* Must be called with tasklist_lock held */
7407 static inline int tg_has_rt_tasks(struct task_group *tg)
7408 {
7409         struct task_struct *g, *p;
7410
7411         do_each_thread(g, p) {
7412                 if (rt_task(p) && task_rq(p)->rt.tg == tg)
7413                         return 1;
7414         } while_each_thread(g, p);
7415
7416         return 0;
7417 }
7418
7419 struct rt_schedulable_data {
7420         struct task_group *tg;
7421         u64 rt_period;
7422         u64 rt_runtime;
7423 };
7424
7425 static int tg_rt_schedulable(struct task_group *tg, void *data)
7426 {
7427         struct rt_schedulable_data *d = data;
7428         struct task_group *child;
7429         unsigned long total, sum = 0;
7430         u64 period, runtime;
7431
7432         period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7433         runtime = tg->rt_bandwidth.rt_runtime;
7434
7435         if (tg == d->tg) {
7436                 period = d->rt_period;
7437                 runtime = d->rt_runtime;
7438         }
7439
7440         /*
7441          * Cannot have more runtime than the period.
7442          */
7443         if (runtime > period && runtime != RUNTIME_INF)
7444                 return -EINVAL;
7445
7446         /*
7447          * Ensure we don't starve existing RT tasks.
7448          */
7449         if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7450                 return -EBUSY;
7451
7452         total = to_ratio(period, runtime);
7453
7454         /*
7455          * Nobody can have more than the global setting allows.
7456          */
7457         if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7458                 return -EINVAL;
7459
7460         /*
7461          * The sum of our children's runtime should not exceed our own.
7462          */
7463         list_for_each_entry_rcu(child, &tg->children, siblings) {
7464                 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7465                 runtime = child->rt_bandwidth.rt_runtime;
7466
7467                 if (child == d->tg) {
7468                         period = d->rt_period;
7469                         runtime = d->rt_runtime;
7470                 }
7471
7472                 sum += to_ratio(period, runtime);
7473         }
7474
7475         if (sum > total)
7476                 return -EINVAL;
7477
7478         return 0;
7479 }
7480
7481 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7482 {
7483         int ret;
7484
7485         struct rt_schedulable_data data = {
7486                 .tg = tg,
7487                 .rt_period = period,
7488                 .rt_runtime = runtime,
7489         };
7490
7491         rcu_read_lock();
7492         ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7493         rcu_read_unlock();
7494
7495         return ret;
7496 }
7497
7498 static int tg_set_rt_bandwidth(struct task_group *tg,
7499                 u64 rt_period, u64 rt_runtime)
7500 {
7501         int i, err = 0;
7502
7503         mutex_lock(&rt_constraints_mutex);
7504         read_lock(&tasklist_lock);
7505         err = __rt_schedulable(tg, rt_period, rt_runtime);
7506         if (err)
7507                 goto unlock;
7508
7509         raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7510         tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7511         tg->rt_bandwidth.rt_runtime = rt_runtime;
7512
7513         for_each_possible_cpu(i) {
7514                 struct rt_rq *rt_rq = tg->rt_rq[i];
7515
7516                 raw_spin_lock(&rt_rq->rt_runtime_lock);
7517                 rt_rq->rt_runtime = rt_runtime;
7518                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7519         }
7520         raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7521 unlock:
7522         read_unlock(&tasklist_lock);
7523         mutex_unlock(&rt_constraints_mutex);
7524
7525         return err;
7526 }
7527
7528 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7529 {
7530         u64 rt_runtime, rt_period;
7531
7532         rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7533         rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7534         if (rt_runtime_us < 0)
7535                 rt_runtime = RUNTIME_INF;
7536
7537         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7538 }
7539
7540 static long sched_group_rt_runtime(struct task_group *tg)
7541 {
7542         u64 rt_runtime_us;
7543
7544         if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
7545                 return -1;
7546
7547         rt_runtime_us = tg->rt_bandwidth.rt_runtime;
7548         do_div(rt_runtime_us, NSEC_PER_USEC);
7549         return rt_runtime_us;
7550 }
7551
7552 static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
7553 {
7554         u64 rt_runtime, rt_period;
7555
7556         rt_period = (u64)rt_period_us * NSEC_PER_USEC;
7557         rt_runtime = tg->rt_bandwidth.rt_runtime;
7558
7559         if (rt_period == 0)
7560                 return -EINVAL;
7561
7562         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7563 }
7564
7565 static long sched_group_rt_period(struct task_group *tg)
7566 {
7567         u64 rt_period_us;
7568
7569         rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7570         do_div(rt_period_us, NSEC_PER_USEC);
7571         return rt_period_us;
7572 }
7573
7574 static int sched_rt_global_constraints(void)
7575 {
7576         u64 runtime, period;
7577         int ret = 0;
7578
7579         if (sysctl_sched_rt_period <= 0)
7580                 return -EINVAL;
7581
7582         runtime = global_rt_runtime();
7583         period = global_rt_period();
7584
7585         /*
7586          * Sanity check on the sysctl variables.
7587          */
7588         if (runtime > period && runtime != RUNTIME_INF)
7589                 return -EINVAL;
7590
7591         mutex_lock(&rt_constraints_mutex);
7592         read_lock(&tasklist_lock);
7593         ret = __rt_schedulable(NULL, 0, 0);
7594         read_unlock(&tasklist_lock);
7595         mutex_unlock(&rt_constraints_mutex);
7596
7597         return ret;
7598 }
7599
7600 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
7601 {
7602         /* Don't accept realtime tasks when there is no way for them to run */
7603         if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7604                 return 0;
7605
7606         return 1;
7607 }
7608
7609 #else /* !CONFIG_RT_GROUP_SCHED */
7610 static int sched_rt_global_constraints(void)
7611 {
7612         unsigned long flags;
7613         int i;
7614
7615         if (sysctl_sched_rt_period <= 0)
7616                 return -EINVAL;
7617
7618         /*
7619          * There's always some RT tasks in the root group
7620          * -- migration, kstopmachine etc..
7621          */
7622         if (sysctl_sched_rt_runtime == 0)
7623                 return -EBUSY;
7624
7625         raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
7626         for_each_possible_cpu(i) {
7627                 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7628
7629                 raw_spin_lock(&rt_rq->rt_runtime_lock);
7630                 rt_rq->rt_runtime = global_rt_runtime();
7631                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7632         }
7633         raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
7634
7635         return 0;
7636 }
7637 #endif /* CONFIG_RT_GROUP_SCHED */
7638
7639 int sched_rr_handler(struct ctl_table *table, int write,
7640                 void __user *buffer, size_t *lenp,
7641                 loff_t *ppos)
7642 {
7643         int ret;
7644         static DEFINE_MUTEX(mutex);
7645
7646         mutex_lock(&mutex);
7647         ret = proc_dointvec(table, write, buffer, lenp, ppos);
7648         /* make sure that internally we keep jiffies */
7649         /* also, writing zero resets timeslice to default */
7650         if (!ret && write) {
7651                 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
7652                         RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
7653         }
7654         mutex_unlock(&mutex);
7655         return ret;
7656 }
7657
7658 int sched_rt_handler(struct ctl_table *table, int write,
7659                 void __user *buffer, size_t *lenp,
7660                 loff_t *ppos)
7661 {
7662         int ret;
7663         int old_period, old_runtime;
7664         static DEFINE_MUTEX(mutex);
7665
7666         mutex_lock(&mutex);
7667         old_period = sysctl_sched_rt_period;
7668         old_runtime = sysctl_sched_rt_runtime;
7669
7670         ret = proc_dointvec(table, write, buffer, lenp, ppos);
7671
7672         if (!ret && write) {
7673                 ret = sched_rt_global_constraints();
7674                 if (ret) {
7675                         sysctl_sched_rt_period = old_period;
7676                         sysctl_sched_rt_runtime = old_runtime;
7677                 } else {
7678                         def_rt_bandwidth.rt_runtime = global_rt_runtime();
7679                         def_rt_bandwidth.rt_period =
7680                                 ns_to_ktime(global_rt_period());
7681                 }
7682         }
7683         mutex_unlock(&mutex);
7684
7685         return ret;
7686 }
7687
7688 #ifdef CONFIG_CGROUP_SCHED
7689
7690 /* return corresponding task_group object of a cgroup */
7691 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7692 {
7693         return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7694                             struct task_group, css);
7695 }
7696
7697 static struct cgroup_subsys_state *cpu_cgroup_css_alloc(struct cgroup *cgrp)
7698 {
7699         struct task_group *tg, *parent;
7700
7701         if (!cgrp->parent) {
7702                 /* This is early initialization for the top cgroup */
7703                 return &root_task_group.css;
7704         }
7705
7706         parent = cgroup_tg(cgrp->parent);
7707         tg = sched_create_group(parent);
7708         if (IS_ERR(tg))
7709                 return ERR_PTR(-ENOMEM);
7710
7711         return &tg->css;
7712 }
7713
7714 static int cpu_cgroup_css_online(struct cgroup *cgrp)
7715 {
7716         struct task_group *tg = cgroup_tg(cgrp);
7717         struct task_group *parent;
7718
7719         if (!cgrp->parent)
7720                 return 0;
7721
7722         parent = cgroup_tg(cgrp->parent);
7723         sched_online_group(tg, parent);
7724         return 0;
7725 }
7726
7727 static void cpu_cgroup_css_free(struct cgroup *cgrp)
7728 {
7729         struct task_group *tg = cgroup_tg(cgrp);
7730
7731         sched_destroy_group(tg);
7732 }
7733
7734 static void cpu_cgroup_css_offline(struct cgroup *cgrp)
7735 {
7736         struct task_group *tg = cgroup_tg(cgrp);
7737
7738         sched_offline_group(tg);
7739 }
7740
7741 static int
7742 cpu_cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
7743 {
7744         const struct cred *cred = current_cred(), *tcred;
7745         struct task_struct *task;
7746
7747         cgroup_taskset_for_each(task, cgrp, tset) {
7748                 tcred = __task_cred(task);
7749
7750                 if ((current != task) && !capable(CAP_SYS_NICE) &&
7751                     cred->euid != tcred->uid && cred->euid != tcred->suid)
7752                         return -EACCES;
7753         }
7754
7755         return 0;
7756 }
7757
7758 static int cpu_cgroup_can_attach(struct cgroup *cgrp,
7759                                  struct cgroup_taskset *tset)
7760 {
7761         struct task_struct *task;
7762
7763         cgroup_taskset_for_each(task, cgrp, tset) {
7764 #ifdef CONFIG_RT_GROUP_SCHED
7765                 if (!sched_rt_can_attach(cgroup_tg(cgrp), task))
7766                         return -EINVAL;
7767 #else
7768                 /* We don't support RT-tasks being in separate groups */
7769                 if (task->sched_class != &fair_sched_class)
7770                         return -EINVAL;
7771 #endif
7772         }
7773         return 0;
7774 }
7775
7776 static void cpu_cgroup_attach(struct cgroup *cgrp,
7777                               struct cgroup_taskset *tset)
7778 {
7779         struct task_struct *task;
7780
7781         cgroup_taskset_for_each(task, cgrp, tset)
7782                 sched_move_task(task);
7783 }
7784
7785 static void
7786 cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7787                 struct task_struct *task)
7788 {
7789         /*
7790          * cgroup_exit() is called in the copy_process() failure path.
7791          * Ignore this case since the task hasn't ran yet, this avoids
7792          * trying to poke a half freed task state from generic code.
7793          */
7794         if (!(task->flags & PF_EXITING))
7795                 return;
7796
7797         sched_move_task(task);
7798 }
7799
7800 #ifdef CONFIG_FAIR_GROUP_SCHED
7801 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
7802                                 u64 shareval)
7803 {
7804         return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
7805 }
7806
7807 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
7808 {
7809         struct task_group *tg = cgroup_tg(cgrp);
7810
7811         return (u64) scale_load_down(tg->shares);
7812 }
7813
7814 #ifdef CONFIG_CFS_BANDWIDTH
7815 static DEFINE_MUTEX(cfs_constraints_mutex);
7816
7817 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
7818 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
7819
7820 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
7821
7822 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
7823 {
7824         int i, ret = 0, runtime_enabled, runtime_was_enabled;
7825         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7826
7827         if (tg == &root_task_group)
7828                 return -EINVAL;
7829
7830         /*
7831          * Ensure we have at some amount of bandwidth every period.  This is
7832          * to prevent reaching a state of large arrears when throttled via
7833          * entity_tick() resulting in prolonged exit starvation.
7834          */
7835         if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
7836                 return -EINVAL;
7837
7838         /*
7839          * Likewise, bound things on the otherside by preventing insane quota
7840          * periods.  This also allows us to normalize in computing quota
7841          * feasibility.
7842          */
7843         if (period > max_cfs_quota_period)
7844                 return -EINVAL;
7845
7846         mutex_lock(&cfs_constraints_mutex);
7847         ret = __cfs_schedulable(tg, period, quota);
7848         if (ret)
7849                 goto out_unlock;
7850
7851         runtime_enabled = quota != RUNTIME_INF;
7852         runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
7853         account_cfs_bandwidth_used(runtime_enabled, runtime_was_enabled);
7854         raw_spin_lock_irq(&cfs_b->lock);
7855         cfs_b->period = ns_to_ktime(period);
7856         cfs_b->quota = quota;
7857
7858         __refill_cfs_bandwidth_runtime(cfs_b);
7859         /* restart the period timer (if active) to handle new period expiry */
7860         if (runtime_enabled && cfs_b->timer_active) {
7861                 /* force a reprogram */
7862                 cfs_b->timer_active = 0;
7863                 __start_cfs_bandwidth(cfs_b);
7864         }
7865         raw_spin_unlock_irq(&cfs_b->lock);
7866
7867         for_each_possible_cpu(i) {
7868                 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
7869                 struct rq *rq = cfs_rq->rq;
7870
7871                 raw_spin_lock_irq(&rq->lock);
7872                 cfs_rq->runtime_enabled = runtime_enabled;
7873                 cfs_rq->runtime_remaining = 0;
7874
7875                 if (cfs_rq->throttled)
7876                         unthrottle_cfs_rq(cfs_rq);
7877                 raw_spin_unlock_irq(&rq->lock);
7878         }
7879 out_unlock:
7880         mutex_unlock(&cfs_constraints_mutex);
7881
7882         return ret;
7883 }
7884
7885 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
7886 {
7887         u64 quota, period;
7888
7889         period = ktime_to_ns(tg->cfs_bandwidth.period);
7890         if (cfs_quota_us < 0)
7891                 quota = RUNTIME_INF;
7892         else
7893                 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
7894
7895         return tg_set_cfs_bandwidth(tg, period, quota);
7896 }
7897
7898 long tg_get_cfs_quota(struct task_group *tg)
7899 {
7900         u64 quota_us;
7901
7902         if (tg->cfs_bandwidth.quota == RUNTIME_INF)
7903                 return -1;
7904
7905         quota_us = tg->cfs_bandwidth.quota;
7906         do_div(quota_us, NSEC_PER_USEC);
7907
7908         return quota_us;
7909 }
7910
7911 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
7912 {
7913         u64 quota, period;
7914
7915         period = (u64)cfs_period_us * NSEC_PER_USEC;
7916         quota = tg->cfs_bandwidth.quota;
7917
7918         return tg_set_cfs_bandwidth(tg, period, quota);
7919 }
7920
7921 long tg_get_cfs_period(struct task_group *tg)
7922 {
7923         u64 cfs_period_us;
7924
7925         cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
7926         do_div(cfs_period_us, NSEC_PER_USEC);
7927
7928         return cfs_period_us;
7929 }
7930
7931 static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft)
7932 {
7933         return tg_get_cfs_quota(cgroup_tg(cgrp));
7934 }
7935
7936 static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype,
7937                                 s64 cfs_quota_us)
7938 {
7939         return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us);
7940 }
7941
7942 static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft)
7943 {
7944         return tg_get_cfs_period(cgroup_tg(cgrp));
7945 }
7946
7947 static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype,
7948                                 u64 cfs_period_us)
7949 {
7950         return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us);
7951 }
7952
7953 struct cfs_schedulable_data {
7954         struct task_group *tg;
7955         u64 period, quota;
7956 };
7957
7958 /*
7959  * normalize group quota/period to be quota/max_period
7960  * note: units are usecs
7961  */
7962 static u64 normalize_cfs_quota(struct task_group *tg,
7963                                struct cfs_schedulable_data *d)
7964 {
7965         u64 quota, period;
7966
7967         if (tg == d->tg) {
7968                 period = d->period;
7969                 quota = d->quota;
7970         } else {
7971                 period = tg_get_cfs_period(tg);
7972                 quota = tg_get_cfs_quota(tg);
7973         }
7974
7975         /* note: these should typically be equivalent */
7976         if (quota == RUNTIME_INF || quota == -1)
7977                 return RUNTIME_INF;
7978
7979         return to_ratio(period, quota);
7980 }
7981
7982 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
7983 {
7984         struct cfs_schedulable_data *d = data;
7985         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7986         s64 quota = 0, parent_quota = -1;
7987
7988         if (!tg->parent) {
7989                 quota = RUNTIME_INF;
7990         } else {
7991                 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
7992
7993                 quota = normalize_cfs_quota(tg, d);
7994                 parent_quota = parent_b->hierarchal_quota;
7995
7996                 /*
7997                  * ensure max(child_quota) <= parent_quota, inherit when no
7998                  * limit is set
7999                  */
8000                 if (quota == RUNTIME_INF)
8001                         quota = parent_quota;
8002                 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8003                         return -EINVAL;
8004         }
8005         cfs_b->hierarchal_quota = quota;
8006
8007         return 0;
8008 }
8009
8010 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8011 {
8012         int ret;
8013         struct cfs_schedulable_data data = {
8014                 .tg = tg,
8015                 .period = period,
8016                 .quota = quota,
8017         };
8018
8019         if (quota != RUNTIME_INF) {
8020                 do_div(data.period, NSEC_PER_USEC);
8021                 do_div(data.quota, NSEC_PER_USEC);
8022         }
8023
8024         rcu_read_lock();
8025         ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8026         rcu_read_unlock();
8027
8028         return ret;
8029 }
8030
8031 static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft,
8032                 struct cgroup_map_cb *cb)
8033 {
8034         struct task_group *tg = cgroup_tg(cgrp);
8035         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8036
8037         cb->fill(cb, "nr_periods", cfs_b->nr_periods);
8038         cb->fill(cb, "nr_throttled", cfs_b->nr_throttled);
8039         cb->fill(cb, "throttled_time", cfs_b->throttled_time);
8040
8041         return 0;
8042 }
8043 #endif /* CONFIG_CFS_BANDWIDTH */
8044 #endif /* CONFIG_FAIR_GROUP_SCHED */
8045
8046 #ifdef CONFIG_RT_GROUP_SCHED
8047 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8048                                 s64 val)
8049 {
8050         return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8051 }
8052
8053 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8054 {
8055         return sched_group_rt_runtime(cgroup_tg(cgrp));
8056 }
8057
8058 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8059                 u64 rt_period_us)
8060 {
8061         return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8062 }
8063
8064 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8065 {
8066         return sched_group_rt_period(cgroup_tg(cgrp));
8067 }
8068 #endif /* CONFIG_RT_GROUP_SCHED */
8069
8070 static struct cftype cpu_files[] = {
8071 #ifdef CONFIG_FAIR_GROUP_SCHED
8072         {
8073                 .name = "shares",
8074                 .read_u64 = cpu_shares_read_u64,
8075                 .write_u64 = cpu_shares_write_u64,
8076         },
8077 #endif
8078 #ifdef CONFIG_CFS_BANDWIDTH
8079         {
8080                 .name = "cfs_quota_us",
8081                 .read_s64 = cpu_cfs_quota_read_s64,
8082                 .write_s64 = cpu_cfs_quota_write_s64,
8083         },
8084         {
8085                 .name = "cfs_period_us",
8086                 .read_u64 = cpu_cfs_period_read_u64,
8087                 .write_u64 = cpu_cfs_period_write_u64,
8088         },
8089         {
8090                 .name = "stat",
8091                 .read_map = cpu_stats_show,
8092         },
8093 #endif
8094 #ifdef CONFIG_RT_GROUP_SCHED
8095         {
8096                 .name = "rt_runtime_us",
8097                 .read_s64 = cpu_rt_runtime_read,
8098                 .write_s64 = cpu_rt_runtime_write,
8099         },
8100         {
8101                 .name = "rt_period_us",
8102                 .read_u64 = cpu_rt_period_read_uint,
8103                 .write_u64 = cpu_rt_period_write_uint,
8104         },
8105 #endif
8106         { }     /* terminate */
8107 };
8108
8109 struct cgroup_subsys cpu_cgroup_subsys = {
8110         .name           = "cpu",
8111         .css_alloc      = cpu_cgroup_css_alloc,
8112         .css_free       = cpu_cgroup_css_free,
8113         .css_online     = cpu_cgroup_css_online,
8114         .css_offline    = cpu_cgroup_css_offline,
8115         .can_attach     = cpu_cgroup_can_attach,
8116         .attach         = cpu_cgroup_attach,
8117         .allow_attach   = cpu_cgroup_allow_attach,
8118         .exit           = cpu_cgroup_exit,
8119         .subsys_id      = cpu_cgroup_subsys_id,
8120         .base_cftypes   = cpu_files,
8121         .early_init     = 1,
8122 };
8123
8124 #endif  /* CONFIG_CGROUP_SCHED */
8125
8126 void dump_cpu_task(int cpu)
8127 {
8128         pr_info("Task dump for CPU %d:\n", cpu);
8129         sched_show_task(cpu_curr(cpu));
8130 }