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