]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame_incremental - kernel/sched.c
sched: fair: weight calculations
[mirror_ubuntu-zesty-kernel.git] / kernel / sched.c
... / ...
CommitLineData
1/*
2 * kernel/sched.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 <linux/smp_lock.h>
36#include <asm/mmu_context.h>
37#include <linux/interrupt.h>
38#include <linux/capability.h>
39#include <linux/completion.h>
40#include <linux/kernel_stat.h>
41#include <linux/debug_locks.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/kthread.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/reciprocal_div.h>
66#include <linux/unistd.h>
67#include <linux/pagemap.h>
68#include <linux/hrtimer.h>
69#include <linux/tick.h>
70#include <linux/bootmem.h>
71
72#include <asm/tlb.h>
73#include <asm/irq_regs.h>
74
75/*
76 * Scheduler clock - returns current time in nanosec units.
77 * This is default implementation.
78 * Architectures and sub-architectures can override this.
79 */
80unsigned long long __attribute__((weak)) sched_clock(void)
81{
82 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
83}
84
85/*
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
88 * and back.
89 */
90#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92#define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93
94/*
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
98 */
99#define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102
103/*
104 * Helpers for converting nanosecond timing to jiffy resolution
105 */
106#define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
107
108#define NICE_0_LOAD SCHED_LOAD_SCALE
109#define NICE_0_SHIFT SCHED_LOAD_SHIFT
110
111/*
112 * These are the 'tuning knobs' of the scheduler:
113 *
114 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
115 * Timeslices get refilled after they expire.
116 */
117#define DEF_TIMESLICE (100 * HZ / 1000)
118
119/*
120 * single value that denotes runtime == period, ie unlimited time.
121 */
122#define RUNTIME_INF ((u64)~0ULL)
123
124#ifdef CONFIG_SMP
125/*
126 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
127 * Since cpu_power is a 'constant', we can use a reciprocal divide.
128 */
129static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
130{
131 return reciprocal_divide(load, sg->reciprocal_cpu_power);
132}
133
134/*
135 * Each time a sched group cpu_power is changed,
136 * we must compute its reciprocal value
137 */
138static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
139{
140 sg->__cpu_power += val;
141 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
142}
143#endif
144
145static inline int rt_policy(int policy)
146{
147 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
148 return 1;
149 return 0;
150}
151
152static inline int task_has_rt_policy(struct task_struct *p)
153{
154 return rt_policy(p->policy);
155}
156
157/*
158 * This is the priority-queue data structure of the RT scheduling class:
159 */
160struct rt_prio_array {
161 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
162 struct list_head queue[MAX_RT_PRIO];
163};
164
165struct rt_bandwidth {
166 /* nests inside the rq lock: */
167 spinlock_t rt_runtime_lock;
168 ktime_t rt_period;
169 u64 rt_runtime;
170 struct hrtimer rt_period_timer;
171};
172
173static struct rt_bandwidth def_rt_bandwidth;
174
175static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
176
177static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
178{
179 struct rt_bandwidth *rt_b =
180 container_of(timer, struct rt_bandwidth, rt_period_timer);
181 ktime_t now;
182 int overrun;
183 int idle = 0;
184
185 for (;;) {
186 now = hrtimer_cb_get_time(timer);
187 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
188
189 if (!overrun)
190 break;
191
192 idle = do_sched_rt_period_timer(rt_b, overrun);
193 }
194
195 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
196}
197
198static
199void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
200{
201 rt_b->rt_period = ns_to_ktime(period);
202 rt_b->rt_runtime = runtime;
203
204 spin_lock_init(&rt_b->rt_runtime_lock);
205
206 hrtimer_init(&rt_b->rt_period_timer,
207 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
208 rt_b->rt_period_timer.function = sched_rt_period_timer;
209 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
210}
211
212static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
213{
214 ktime_t now;
215
216 if (rt_b->rt_runtime == RUNTIME_INF)
217 return;
218
219 if (hrtimer_active(&rt_b->rt_period_timer))
220 return;
221
222 spin_lock(&rt_b->rt_runtime_lock);
223 for (;;) {
224 if (hrtimer_active(&rt_b->rt_period_timer))
225 break;
226
227 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
228 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
229 hrtimer_start(&rt_b->rt_period_timer,
230 rt_b->rt_period_timer.expires,
231 HRTIMER_MODE_ABS);
232 }
233 spin_unlock(&rt_b->rt_runtime_lock);
234}
235
236#ifdef CONFIG_RT_GROUP_SCHED
237static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
238{
239 hrtimer_cancel(&rt_b->rt_period_timer);
240}
241#endif
242
243#ifdef CONFIG_GROUP_SCHED
244
245#include <linux/cgroup.h>
246
247struct cfs_rq;
248
249static LIST_HEAD(task_groups);
250
251/* task group related information */
252struct task_group {
253#ifdef CONFIG_CGROUP_SCHED
254 struct cgroup_subsys_state css;
255#endif
256
257#ifdef CONFIG_FAIR_GROUP_SCHED
258 /* schedulable entities of this group on each cpu */
259 struct sched_entity **se;
260 /* runqueue "owned" by this group on each cpu */
261 struct cfs_rq **cfs_rq;
262 unsigned long shares;
263#endif
264
265#ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity **rt_se;
267 struct rt_rq **rt_rq;
268
269 struct rt_bandwidth rt_bandwidth;
270#endif
271
272 struct rcu_head rcu;
273 struct list_head list;
274
275 struct task_group *parent;
276 struct list_head siblings;
277 struct list_head children;
278};
279
280#ifdef CONFIG_USER_SCHED
281
282/*
283 * Root task group.
284 * Every UID task group (including init_task_group aka UID-0) will
285 * be a child to this group.
286 */
287struct task_group root_task_group;
288
289#ifdef CONFIG_FAIR_GROUP_SCHED
290/* Default task group's sched entity on each cpu */
291static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
292/* Default task group's cfs_rq on each cpu */
293static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
294#endif
295
296#ifdef CONFIG_RT_GROUP_SCHED
297static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
298static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
299#endif
300#else
301#define root_task_group init_task_group
302#endif
303
304/* task_group_lock serializes add/remove of task groups and also changes to
305 * a task group's cpu shares.
306 */
307static DEFINE_SPINLOCK(task_group_lock);
308
309/* doms_cur_mutex serializes access to doms_cur[] array */
310static DEFINE_MUTEX(doms_cur_mutex);
311
312#ifdef CONFIG_FAIR_GROUP_SCHED
313#ifdef CONFIG_USER_SCHED
314# define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
315#else
316# define INIT_TASK_GROUP_LOAD NICE_0_LOAD
317#endif
318
319#define MIN_SHARES 2
320
321static int init_task_group_load = INIT_TASK_GROUP_LOAD;
322#endif
323
324/* Default task group.
325 * Every task in system belong to this group at bootup.
326 */
327struct task_group init_task_group;
328
329/* return group to which a task belongs */
330static inline struct task_group *task_group(struct task_struct *p)
331{
332 struct task_group *tg;
333
334#ifdef CONFIG_USER_SCHED
335 tg = p->user->tg;
336#elif defined(CONFIG_CGROUP_SCHED)
337 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
338 struct task_group, css);
339#else
340 tg = &init_task_group;
341#endif
342 return tg;
343}
344
345/* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
346static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
347{
348#ifdef CONFIG_FAIR_GROUP_SCHED
349 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
350 p->se.parent = task_group(p)->se[cpu];
351#endif
352
353#ifdef CONFIG_RT_GROUP_SCHED
354 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
355 p->rt.parent = task_group(p)->rt_se[cpu];
356#endif
357}
358
359static inline void lock_doms_cur(void)
360{
361 mutex_lock(&doms_cur_mutex);
362}
363
364static inline void unlock_doms_cur(void)
365{
366 mutex_unlock(&doms_cur_mutex);
367}
368
369#else
370
371static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
372static inline void lock_doms_cur(void) { }
373static inline void unlock_doms_cur(void) { }
374
375#endif /* CONFIG_GROUP_SCHED */
376
377/* CFS-related fields in a runqueue */
378struct cfs_rq {
379 struct load_weight load;
380 unsigned long nr_running;
381
382 u64 exec_clock;
383 u64 min_vruntime;
384
385 struct rb_root tasks_timeline;
386 struct rb_node *rb_leftmost;
387
388 struct list_head tasks;
389 struct list_head *balance_iterator;
390
391 /*
392 * 'curr' points to currently running entity on this cfs_rq.
393 * It is set to NULL otherwise (i.e when none are currently running).
394 */
395 struct sched_entity *curr, *next;
396
397 unsigned long nr_spread_over;
398
399#ifdef CONFIG_FAIR_GROUP_SCHED
400 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
401
402 /*
403 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
404 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
405 * (like users, containers etc.)
406 *
407 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
408 * list is used during load balance.
409 */
410 struct list_head leaf_cfs_rq_list;
411 struct task_group *tg; /* group that "owns" this runqueue */
412
413#ifdef CONFIG_SMP
414 unsigned long task_weight;
415 unsigned long shares;
416 /*
417 * We need space to build a sched_domain wide view of the full task
418 * group tree, in order to avoid depending on dynamic memory allocation
419 * during the load balancing we place this in the per cpu task group
420 * hierarchy. This limits the load balancing to one instance per cpu,
421 * but more should not be needed anyway.
422 */
423 struct aggregate_struct {
424 /*
425 * load = weight(cpus) * f(tg)
426 *
427 * Where f(tg) is the recursive weight fraction assigned to
428 * this group.
429 */
430 unsigned long load;
431
432 /*
433 * part of the group weight distributed to this span.
434 */
435 unsigned long shares;
436
437 /*
438 * The sum of all runqueue weights within this span.
439 */
440 unsigned long rq_weight;
441
442 /*
443 * Weight contributed by tasks; this is the part we can
444 * influence by moving tasks around.
445 */
446 unsigned long task_weight;
447 } aggregate;
448#endif
449#endif
450};
451
452/* Real-Time classes' related field in a runqueue: */
453struct rt_rq {
454 struct rt_prio_array active;
455 unsigned long rt_nr_running;
456#if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
457 int highest_prio; /* highest queued rt task prio */
458#endif
459#ifdef CONFIG_SMP
460 unsigned long rt_nr_migratory;
461 int overloaded;
462#endif
463 int rt_throttled;
464 u64 rt_time;
465 u64 rt_runtime;
466 /* Nests inside the rq lock: */
467 spinlock_t rt_runtime_lock;
468
469#ifdef CONFIG_RT_GROUP_SCHED
470 unsigned long rt_nr_boosted;
471
472 struct rq *rq;
473 struct list_head leaf_rt_rq_list;
474 struct task_group *tg;
475 struct sched_rt_entity *rt_se;
476#endif
477};
478
479#ifdef CONFIG_SMP
480
481/*
482 * We add the notion of a root-domain which will be used to define per-domain
483 * variables. Each exclusive cpuset essentially defines an island domain by
484 * fully partitioning the member cpus from any other cpuset. Whenever a new
485 * exclusive cpuset is created, we also create and attach a new root-domain
486 * object.
487 *
488 */
489struct root_domain {
490 atomic_t refcount;
491 cpumask_t span;
492 cpumask_t online;
493
494 /*
495 * The "RT overload" flag: it gets set if a CPU has more than
496 * one runnable RT task.
497 */
498 cpumask_t rto_mask;
499 atomic_t rto_count;
500};
501
502/*
503 * By default the system creates a single root-domain with all cpus as
504 * members (mimicking the global state we have today).
505 */
506static struct root_domain def_root_domain;
507
508#endif
509
510/*
511 * This is the main, per-CPU runqueue data structure.
512 *
513 * Locking rule: those places that want to lock multiple runqueues
514 * (such as the load balancing or the thread migration code), lock
515 * acquire operations must be ordered by ascending &runqueue.
516 */
517struct rq {
518 /* runqueue lock: */
519 spinlock_t lock;
520
521 /*
522 * nr_running and cpu_load should be in the same cacheline because
523 * remote CPUs use both these fields when doing load calculation.
524 */
525 unsigned long nr_running;
526 #define CPU_LOAD_IDX_MAX 5
527 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
528 unsigned char idle_at_tick;
529#ifdef CONFIG_NO_HZ
530 unsigned long last_tick_seen;
531 unsigned char in_nohz_recently;
532#endif
533 /* capture load from *all* tasks on this cpu: */
534 struct load_weight load;
535 unsigned long nr_load_updates;
536 u64 nr_switches;
537
538 struct cfs_rq cfs;
539 struct rt_rq rt;
540
541#ifdef CONFIG_FAIR_GROUP_SCHED
542 /* list of leaf cfs_rq on this cpu: */
543 struct list_head leaf_cfs_rq_list;
544#endif
545#ifdef CONFIG_RT_GROUP_SCHED
546 struct list_head leaf_rt_rq_list;
547#endif
548
549 /*
550 * This is part of a global counter where only the total sum
551 * over all CPUs matters. A task can increase this counter on
552 * one CPU and if it got migrated afterwards it may decrease
553 * it on another CPU. Always updated under the runqueue lock:
554 */
555 unsigned long nr_uninterruptible;
556
557 struct task_struct *curr, *idle;
558 unsigned long next_balance;
559 struct mm_struct *prev_mm;
560
561 u64 clock, prev_clock_raw;
562 s64 clock_max_delta;
563
564 unsigned int clock_warps, clock_overflows, clock_underflows;
565 u64 idle_clock;
566 unsigned int clock_deep_idle_events;
567 u64 tick_timestamp;
568
569 atomic_t nr_iowait;
570
571#ifdef CONFIG_SMP
572 struct root_domain *rd;
573 struct sched_domain *sd;
574
575 /* For active balancing */
576 int active_balance;
577 int push_cpu;
578 /* cpu of this runqueue: */
579 int cpu;
580
581 struct task_struct *migration_thread;
582 struct list_head migration_queue;
583#endif
584
585#ifdef CONFIG_SCHED_HRTICK
586 unsigned long hrtick_flags;
587 ktime_t hrtick_expire;
588 struct hrtimer hrtick_timer;
589#endif
590
591#ifdef CONFIG_SCHEDSTATS
592 /* latency stats */
593 struct sched_info rq_sched_info;
594
595 /* sys_sched_yield() stats */
596 unsigned int yld_exp_empty;
597 unsigned int yld_act_empty;
598 unsigned int yld_both_empty;
599 unsigned int yld_count;
600
601 /* schedule() stats */
602 unsigned int sched_switch;
603 unsigned int sched_count;
604 unsigned int sched_goidle;
605
606 /* try_to_wake_up() stats */
607 unsigned int ttwu_count;
608 unsigned int ttwu_local;
609
610 /* BKL stats */
611 unsigned int bkl_count;
612#endif
613 struct lock_class_key rq_lock_key;
614};
615
616static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
617
618static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
619{
620 rq->curr->sched_class->check_preempt_curr(rq, p);
621}
622
623static inline int cpu_of(struct rq *rq)
624{
625#ifdef CONFIG_SMP
626 return rq->cpu;
627#else
628 return 0;
629#endif
630}
631
632#ifdef CONFIG_NO_HZ
633static inline bool nohz_on(int cpu)
634{
635 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
636}
637
638static inline u64 max_skipped_ticks(struct rq *rq)
639{
640 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
641}
642
643static inline void update_last_tick_seen(struct rq *rq)
644{
645 rq->last_tick_seen = jiffies;
646}
647#else
648static inline u64 max_skipped_ticks(struct rq *rq)
649{
650 return 1;
651}
652
653static inline void update_last_tick_seen(struct rq *rq)
654{
655}
656#endif
657
658/*
659 * Update the per-runqueue clock, as finegrained as the platform can give
660 * us, but without assuming monotonicity, etc.:
661 */
662static void __update_rq_clock(struct rq *rq)
663{
664 u64 prev_raw = rq->prev_clock_raw;
665 u64 now = sched_clock();
666 s64 delta = now - prev_raw;
667 u64 clock = rq->clock;
668
669#ifdef CONFIG_SCHED_DEBUG
670 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
671#endif
672 /*
673 * Protect against sched_clock() occasionally going backwards:
674 */
675 if (unlikely(delta < 0)) {
676 clock++;
677 rq->clock_warps++;
678 } else {
679 /*
680 * Catch too large forward jumps too:
681 */
682 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
683 u64 max_time = rq->tick_timestamp + max_jump;
684
685 if (unlikely(clock + delta > max_time)) {
686 if (clock < max_time)
687 clock = max_time;
688 else
689 clock++;
690 rq->clock_overflows++;
691 } else {
692 if (unlikely(delta > rq->clock_max_delta))
693 rq->clock_max_delta = delta;
694 clock += delta;
695 }
696 }
697
698 rq->prev_clock_raw = now;
699 rq->clock = clock;
700}
701
702static void update_rq_clock(struct rq *rq)
703{
704 if (likely(smp_processor_id() == cpu_of(rq)))
705 __update_rq_clock(rq);
706}
707
708/*
709 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
710 * See detach_destroy_domains: synchronize_sched for details.
711 *
712 * The domain tree of any CPU may only be accessed from within
713 * preempt-disabled sections.
714 */
715#define for_each_domain(cpu, __sd) \
716 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
717
718#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
719#define this_rq() (&__get_cpu_var(runqueues))
720#define task_rq(p) cpu_rq(task_cpu(p))
721#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
722
723/*
724 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
725 */
726#ifdef CONFIG_SCHED_DEBUG
727# define const_debug __read_mostly
728#else
729# define const_debug static const
730#endif
731
732/*
733 * Debugging: various feature bits
734 */
735enum {
736 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
737 SCHED_FEAT_WAKEUP_PREEMPT = 2,
738 SCHED_FEAT_START_DEBIT = 4,
739 SCHED_FEAT_AFFINE_WAKEUPS = 8,
740 SCHED_FEAT_CACHE_HOT_BUDDY = 16,
741 SCHED_FEAT_SYNC_WAKEUPS = 32,
742 SCHED_FEAT_HRTICK = 64,
743 SCHED_FEAT_DOUBLE_TICK = 128,
744 SCHED_FEAT_NORMALIZED_SLEEPER = 256,
745};
746
747const_debug unsigned int sysctl_sched_features =
748 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
749 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
750 SCHED_FEAT_START_DEBIT * 1 |
751 SCHED_FEAT_AFFINE_WAKEUPS * 1 |
752 SCHED_FEAT_CACHE_HOT_BUDDY * 1 |
753 SCHED_FEAT_SYNC_WAKEUPS * 1 |
754 SCHED_FEAT_HRTICK * 1 |
755 SCHED_FEAT_DOUBLE_TICK * 0 |
756 SCHED_FEAT_NORMALIZED_SLEEPER * 1;
757
758#define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
759
760/*
761 * Number of tasks to iterate in a single balance run.
762 * Limited because this is done with IRQs disabled.
763 */
764const_debug unsigned int sysctl_sched_nr_migrate = 32;
765
766/*
767 * period over which we measure -rt task cpu usage in us.
768 * default: 1s
769 */
770unsigned int sysctl_sched_rt_period = 1000000;
771
772static __read_mostly int scheduler_running;
773
774/*
775 * part of the period that we allow rt tasks to run in us.
776 * default: 0.95s
777 */
778int sysctl_sched_rt_runtime = 950000;
779
780static inline u64 global_rt_period(void)
781{
782 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
783}
784
785static inline u64 global_rt_runtime(void)
786{
787 if (sysctl_sched_rt_period < 0)
788 return RUNTIME_INF;
789
790 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
791}
792
793static const unsigned long long time_sync_thresh = 100000;
794
795static DEFINE_PER_CPU(unsigned long long, time_offset);
796static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
797
798/*
799 * Global lock which we take every now and then to synchronize
800 * the CPUs time. This method is not warp-safe, but it's good
801 * enough to synchronize slowly diverging time sources and thus
802 * it's good enough for tracing:
803 */
804static DEFINE_SPINLOCK(time_sync_lock);
805static unsigned long long prev_global_time;
806
807static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
808{
809 unsigned long flags;
810
811 spin_lock_irqsave(&time_sync_lock, flags);
812
813 if (time < prev_global_time) {
814 per_cpu(time_offset, cpu) += prev_global_time - time;
815 time = prev_global_time;
816 } else {
817 prev_global_time = time;
818 }
819
820 spin_unlock_irqrestore(&time_sync_lock, flags);
821
822 return time;
823}
824
825static unsigned long long __cpu_clock(int cpu)
826{
827 unsigned long long now;
828 unsigned long flags;
829 struct rq *rq;
830
831 /*
832 * Only call sched_clock() if the scheduler has already been
833 * initialized (some code might call cpu_clock() very early):
834 */
835 if (unlikely(!scheduler_running))
836 return 0;
837
838 local_irq_save(flags);
839 rq = cpu_rq(cpu);
840 update_rq_clock(rq);
841 now = rq->clock;
842 local_irq_restore(flags);
843
844 return now;
845}
846
847/*
848 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
849 * clock constructed from sched_clock():
850 */
851unsigned long long cpu_clock(int cpu)
852{
853 unsigned long long prev_cpu_time, time, delta_time;
854
855 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
856 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
857 delta_time = time-prev_cpu_time;
858
859 if (unlikely(delta_time > time_sync_thresh))
860 time = __sync_cpu_clock(time, cpu);
861
862 return time;
863}
864EXPORT_SYMBOL_GPL(cpu_clock);
865
866#ifndef prepare_arch_switch
867# define prepare_arch_switch(next) do { } while (0)
868#endif
869#ifndef finish_arch_switch
870# define finish_arch_switch(prev) do { } while (0)
871#endif
872
873static inline int task_current(struct rq *rq, struct task_struct *p)
874{
875 return rq->curr == p;
876}
877
878#ifndef __ARCH_WANT_UNLOCKED_CTXSW
879static inline int task_running(struct rq *rq, struct task_struct *p)
880{
881 return task_current(rq, p);
882}
883
884static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
885{
886}
887
888static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
889{
890#ifdef CONFIG_DEBUG_SPINLOCK
891 /* this is a valid case when another task releases the spinlock */
892 rq->lock.owner = current;
893#endif
894 /*
895 * If we are tracking spinlock dependencies then we have to
896 * fix up the runqueue lock - which gets 'carried over' from
897 * prev into current:
898 */
899 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
900
901 spin_unlock_irq(&rq->lock);
902}
903
904#else /* __ARCH_WANT_UNLOCKED_CTXSW */
905static inline int task_running(struct rq *rq, struct task_struct *p)
906{
907#ifdef CONFIG_SMP
908 return p->oncpu;
909#else
910 return task_current(rq, p);
911#endif
912}
913
914static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
915{
916#ifdef CONFIG_SMP
917 /*
918 * We can optimise this out completely for !SMP, because the
919 * SMP rebalancing from interrupt is the only thing that cares
920 * here.
921 */
922 next->oncpu = 1;
923#endif
924#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
925 spin_unlock_irq(&rq->lock);
926#else
927 spin_unlock(&rq->lock);
928#endif
929}
930
931static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
932{
933#ifdef CONFIG_SMP
934 /*
935 * After ->oncpu is cleared, the task can be moved to a different CPU.
936 * We must ensure this doesn't happen until the switch is completely
937 * finished.
938 */
939 smp_wmb();
940 prev->oncpu = 0;
941#endif
942#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
943 local_irq_enable();
944#endif
945}
946#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
947
948/*
949 * __task_rq_lock - lock the runqueue a given task resides on.
950 * Must be called interrupts disabled.
951 */
952static inline struct rq *__task_rq_lock(struct task_struct *p)
953 __acquires(rq->lock)
954{
955 for (;;) {
956 struct rq *rq = task_rq(p);
957 spin_lock(&rq->lock);
958 if (likely(rq == task_rq(p)))
959 return rq;
960 spin_unlock(&rq->lock);
961 }
962}
963
964/*
965 * task_rq_lock - lock the runqueue a given task resides on and disable
966 * interrupts. Note the ordering: we can safely lookup the task_rq without
967 * explicitly disabling preemption.
968 */
969static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
970 __acquires(rq->lock)
971{
972 struct rq *rq;
973
974 for (;;) {
975 local_irq_save(*flags);
976 rq = task_rq(p);
977 spin_lock(&rq->lock);
978 if (likely(rq == task_rq(p)))
979 return rq;
980 spin_unlock_irqrestore(&rq->lock, *flags);
981 }
982}
983
984static void __task_rq_unlock(struct rq *rq)
985 __releases(rq->lock)
986{
987 spin_unlock(&rq->lock);
988}
989
990static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
991 __releases(rq->lock)
992{
993 spin_unlock_irqrestore(&rq->lock, *flags);
994}
995
996/*
997 * this_rq_lock - lock this runqueue and disable interrupts.
998 */
999static struct rq *this_rq_lock(void)
1000 __acquires(rq->lock)
1001{
1002 struct rq *rq;
1003
1004 local_irq_disable();
1005 rq = this_rq();
1006 spin_lock(&rq->lock);
1007
1008 return rq;
1009}
1010
1011/*
1012 * We are going deep-idle (irqs are disabled):
1013 */
1014void sched_clock_idle_sleep_event(void)
1015{
1016 struct rq *rq = cpu_rq(smp_processor_id());
1017
1018 spin_lock(&rq->lock);
1019 __update_rq_clock(rq);
1020 spin_unlock(&rq->lock);
1021 rq->clock_deep_idle_events++;
1022}
1023EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1024
1025/*
1026 * We just idled delta nanoseconds (called with irqs disabled):
1027 */
1028void sched_clock_idle_wakeup_event(u64 delta_ns)
1029{
1030 struct rq *rq = cpu_rq(smp_processor_id());
1031 u64 now = sched_clock();
1032
1033 rq->idle_clock += delta_ns;
1034 /*
1035 * Override the previous timestamp and ignore all
1036 * sched_clock() deltas that occured while we idled,
1037 * and use the PM-provided delta_ns to advance the
1038 * rq clock:
1039 */
1040 spin_lock(&rq->lock);
1041 rq->prev_clock_raw = now;
1042 rq->clock += delta_ns;
1043 spin_unlock(&rq->lock);
1044 touch_softlockup_watchdog();
1045}
1046EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1047
1048static void __resched_task(struct task_struct *p, int tif_bit);
1049
1050static inline void resched_task(struct task_struct *p)
1051{
1052 __resched_task(p, TIF_NEED_RESCHED);
1053}
1054
1055#ifdef CONFIG_SCHED_HRTICK
1056/*
1057 * Use HR-timers to deliver accurate preemption points.
1058 *
1059 * Its all a bit involved since we cannot program an hrt while holding the
1060 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1061 * reschedule event.
1062 *
1063 * When we get rescheduled we reprogram the hrtick_timer outside of the
1064 * rq->lock.
1065 */
1066static inline void resched_hrt(struct task_struct *p)
1067{
1068 __resched_task(p, TIF_HRTICK_RESCHED);
1069}
1070
1071static inline void resched_rq(struct rq *rq)
1072{
1073 unsigned long flags;
1074
1075 spin_lock_irqsave(&rq->lock, flags);
1076 resched_task(rq->curr);
1077 spin_unlock_irqrestore(&rq->lock, flags);
1078}
1079
1080enum {
1081 HRTICK_SET, /* re-programm hrtick_timer */
1082 HRTICK_RESET, /* not a new slice */
1083};
1084
1085/*
1086 * Use hrtick when:
1087 * - enabled by features
1088 * - hrtimer is actually high res
1089 */
1090static inline int hrtick_enabled(struct rq *rq)
1091{
1092 if (!sched_feat(HRTICK))
1093 return 0;
1094 return hrtimer_is_hres_active(&rq->hrtick_timer);
1095}
1096
1097/*
1098 * Called to set the hrtick timer state.
1099 *
1100 * called with rq->lock held and irqs disabled
1101 */
1102static void hrtick_start(struct rq *rq, u64 delay, int reset)
1103{
1104 assert_spin_locked(&rq->lock);
1105
1106 /*
1107 * preempt at: now + delay
1108 */
1109 rq->hrtick_expire =
1110 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1111 /*
1112 * indicate we need to program the timer
1113 */
1114 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1115 if (reset)
1116 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1117
1118 /*
1119 * New slices are called from the schedule path and don't need a
1120 * forced reschedule.
1121 */
1122 if (reset)
1123 resched_hrt(rq->curr);
1124}
1125
1126static void hrtick_clear(struct rq *rq)
1127{
1128 if (hrtimer_active(&rq->hrtick_timer))
1129 hrtimer_cancel(&rq->hrtick_timer);
1130}
1131
1132/*
1133 * Update the timer from the possible pending state.
1134 */
1135static void hrtick_set(struct rq *rq)
1136{
1137 ktime_t time;
1138 int set, reset;
1139 unsigned long flags;
1140
1141 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1142
1143 spin_lock_irqsave(&rq->lock, flags);
1144 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1145 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1146 time = rq->hrtick_expire;
1147 clear_thread_flag(TIF_HRTICK_RESCHED);
1148 spin_unlock_irqrestore(&rq->lock, flags);
1149
1150 if (set) {
1151 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1152 if (reset && !hrtimer_active(&rq->hrtick_timer))
1153 resched_rq(rq);
1154 } else
1155 hrtick_clear(rq);
1156}
1157
1158/*
1159 * High-resolution timer tick.
1160 * Runs from hardirq context with interrupts disabled.
1161 */
1162static enum hrtimer_restart hrtick(struct hrtimer *timer)
1163{
1164 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1165
1166 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1167
1168 spin_lock(&rq->lock);
1169 __update_rq_clock(rq);
1170 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1171 spin_unlock(&rq->lock);
1172
1173 return HRTIMER_NORESTART;
1174}
1175
1176static inline void init_rq_hrtick(struct rq *rq)
1177{
1178 rq->hrtick_flags = 0;
1179 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1180 rq->hrtick_timer.function = hrtick;
1181 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1182}
1183
1184void hrtick_resched(void)
1185{
1186 struct rq *rq;
1187 unsigned long flags;
1188
1189 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1190 return;
1191
1192 local_irq_save(flags);
1193 rq = cpu_rq(smp_processor_id());
1194 hrtick_set(rq);
1195 local_irq_restore(flags);
1196}
1197#else
1198static inline void hrtick_clear(struct rq *rq)
1199{
1200}
1201
1202static inline void hrtick_set(struct rq *rq)
1203{
1204}
1205
1206static inline void init_rq_hrtick(struct rq *rq)
1207{
1208}
1209
1210void hrtick_resched(void)
1211{
1212}
1213#endif
1214
1215/*
1216 * resched_task - mark a task 'to be rescheduled now'.
1217 *
1218 * On UP this means the setting of the need_resched flag, on SMP it
1219 * might also involve a cross-CPU call to trigger the scheduler on
1220 * the target CPU.
1221 */
1222#ifdef CONFIG_SMP
1223
1224#ifndef tsk_is_polling
1225#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1226#endif
1227
1228static void __resched_task(struct task_struct *p, int tif_bit)
1229{
1230 int cpu;
1231
1232 assert_spin_locked(&task_rq(p)->lock);
1233
1234 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1235 return;
1236
1237 set_tsk_thread_flag(p, tif_bit);
1238
1239 cpu = task_cpu(p);
1240 if (cpu == smp_processor_id())
1241 return;
1242
1243 /* NEED_RESCHED must be visible before we test polling */
1244 smp_mb();
1245 if (!tsk_is_polling(p))
1246 smp_send_reschedule(cpu);
1247}
1248
1249static void resched_cpu(int cpu)
1250{
1251 struct rq *rq = cpu_rq(cpu);
1252 unsigned long flags;
1253
1254 if (!spin_trylock_irqsave(&rq->lock, flags))
1255 return;
1256 resched_task(cpu_curr(cpu));
1257 spin_unlock_irqrestore(&rq->lock, flags);
1258}
1259
1260#ifdef CONFIG_NO_HZ
1261/*
1262 * When add_timer_on() enqueues a timer into the timer wheel of an
1263 * idle CPU then this timer might expire before the next timer event
1264 * which is scheduled to wake up that CPU. In case of a completely
1265 * idle system the next event might even be infinite time into the
1266 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1267 * leaves the inner idle loop so the newly added timer is taken into
1268 * account when the CPU goes back to idle and evaluates the timer
1269 * wheel for the next timer event.
1270 */
1271void wake_up_idle_cpu(int cpu)
1272{
1273 struct rq *rq = cpu_rq(cpu);
1274
1275 if (cpu == smp_processor_id())
1276 return;
1277
1278 /*
1279 * This is safe, as this function is called with the timer
1280 * wheel base lock of (cpu) held. When the CPU is on the way
1281 * to idle and has not yet set rq->curr to idle then it will
1282 * be serialized on the timer wheel base lock and take the new
1283 * timer into account automatically.
1284 */
1285 if (rq->curr != rq->idle)
1286 return;
1287
1288 /*
1289 * We can set TIF_RESCHED on the idle task of the other CPU
1290 * lockless. The worst case is that the other CPU runs the
1291 * idle task through an additional NOOP schedule()
1292 */
1293 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1294
1295 /* NEED_RESCHED must be visible before we test polling */
1296 smp_mb();
1297 if (!tsk_is_polling(rq->idle))
1298 smp_send_reschedule(cpu);
1299}
1300#endif
1301
1302#else
1303static void __resched_task(struct task_struct *p, int tif_bit)
1304{
1305 assert_spin_locked(&task_rq(p)->lock);
1306 set_tsk_thread_flag(p, tif_bit);
1307}
1308#endif
1309
1310#if BITS_PER_LONG == 32
1311# define WMULT_CONST (~0UL)
1312#else
1313# define WMULT_CONST (1UL << 32)
1314#endif
1315
1316#define WMULT_SHIFT 32
1317
1318/*
1319 * Shift right and round:
1320 */
1321#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1322
1323/*
1324 * delta *= weight / lw
1325 */
1326static unsigned long
1327calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1328 struct load_weight *lw)
1329{
1330 u64 tmp;
1331
1332 if (unlikely(!lw->inv_weight))
1333 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1334
1335 tmp = (u64)delta_exec * weight;
1336 /*
1337 * Check whether we'd overflow the 64-bit multiplication:
1338 */
1339 if (unlikely(tmp > WMULT_CONST))
1340 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1341 WMULT_SHIFT/2);
1342 else
1343 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1344
1345 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1346}
1347
1348static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1349{
1350 lw->weight += inc;
1351 lw->inv_weight = 0;
1352}
1353
1354static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1355{
1356 lw->weight -= dec;
1357 lw->inv_weight = 0;
1358}
1359
1360/*
1361 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1362 * of tasks with abnormal "nice" values across CPUs the contribution that
1363 * each task makes to its run queue's load is weighted according to its
1364 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1365 * scaled version of the new time slice allocation that they receive on time
1366 * slice expiry etc.
1367 */
1368
1369#define WEIGHT_IDLEPRIO 2
1370#define WMULT_IDLEPRIO (1 << 31)
1371
1372/*
1373 * Nice levels are multiplicative, with a gentle 10% change for every
1374 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1375 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1376 * that remained on nice 0.
1377 *
1378 * The "10% effect" is relative and cumulative: from _any_ nice level,
1379 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1380 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1381 * If a task goes up by ~10% and another task goes down by ~10% then
1382 * the relative distance between them is ~25%.)
1383 */
1384static const int prio_to_weight[40] = {
1385 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1386 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1387 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1388 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1389 /* 0 */ 1024, 820, 655, 526, 423,
1390 /* 5 */ 335, 272, 215, 172, 137,
1391 /* 10 */ 110, 87, 70, 56, 45,
1392 /* 15 */ 36, 29, 23, 18, 15,
1393};
1394
1395/*
1396 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1397 *
1398 * In cases where the weight does not change often, we can use the
1399 * precalculated inverse to speed up arithmetics by turning divisions
1400 * into multiplications:
1401 */
1402static const u32 prio_to_wmult[40] = {
1403 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1404 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1405 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1406 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1407 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1408 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1409 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1410 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1411};
1412
1413static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1414
1415/*
1416 * runqueue iterator, to support SMP load-balancing between different
1417 * scheduling classes, without having to expose their internal data
1418 * structures to the load-balancing proper:
1419 */
1420struct rq_iterator {
1421 void *arg;
1422 struct task_struct *(*start)(void *);
1423 struct task_struct *(*next)(void *);
1424};
1425
1426#ifdef CONFIG_SMP
1427static unsigned long
1428balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1429 unsigned long max_load_move, struct sched_domain *sd,
1430 enum cpu_idle_type idle, int *all_pinned,
1431 int *this_best_prio, struct rq_iterator *iterator);
1432
1433static int
1434iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1435 struct sched_domain *sd, enum cpu_idle_type idle,
1436 struct rq_iterator *iterator);
1437#endif
1438
1439#ifdef CONFIG_CGROUP_CPUACCT
1440static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1441#else
1442static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1443#endif
1444
1445static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1446{
1447 update_load_add(&rq->load, load);
1448}
1449
1450static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1451{
1452 update_load_sub(&rq->load, load);
1453}
1454
1455#ifdef CONFIG_SMP
1456static unsigned long source_load(int cpu, int type);
1457static unsigned long target_load(int cpu, int type);
1458static unsigned long cpu_avg_load_per_task(int cpu);
1459static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1460
1461#ifdef CONFIG_FAIR_GROUP_SCHED
1462
1463/*
1464 * Group load balancing.
1465 *
1466 * We calculate a few balance domain wide aggregate numbers; load and weight.
1467 * Given the pictures below, and assuming each item has equal weight:
1468 *
1469 * root 1 - thread
1470 * / | \ A - group
1471 * A 1 B
1472 * /|\ / \
1473 * C 2 D 3 4
1474 * | |
1475 * 5 6
1476 *
1477 * load:
1478 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1479 * which equals 1/9-th of the total load.
1480 *
1481 * shares:
1482 * The weight of this group on the selected cpus.
1483 *
1484 * rq_weight:
1485 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1486 * B would get 2.
1487 *
1488 * task_weight:
1489 * Part of the rq_weight contributed by tasks; all groups except B would
1490 * get 1, B gets 2.
1491 */
1492
1493static inline struct aggregate_struct *
1494aggregate(struct task_group *tg, struct sched_domain *sd)
1495{
1496 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1497}
1498
1499typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1500
1501/*
1502 * Iterate the full tree, calling @down when first entering a node and @up when
1503 * leaving it for the final time.
1504 */
1505static
1506void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1507 struct sched_domain *sd)
1508{
1509 struct task_group *parent, *child;
1510
1511 rcu_read_lock();
1512 parent = &root_task_group;
1513down:
1514 (*down)(parent, sd);
1515 list_for_each_entry_rcu(child, &parent->children, siblings) {
1516 parent = child;
1517 goto down;
1518
1519up:
1520 continue;
1521 }
1522 (*up)(parent, sd);
1523
1524 child = parent;
1525 parent = parent->parent;
1526 if (parent)
1527 goto up;
1528 rcu_read_unlock();
1529}
1530
1531/*
1532 * Calculate the aggregate runqueue weight.
1533 */
1534static
1535void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1536{
1537 unsigned long rq_weight = 0;
1538 unsigned long task_weight = 0;
1539 int i;
1540
1541 for_each_cpu_mask(i, sd->span) {
1542 rq_weight += tg->cfs_rq[i]->load.weight;
1543 task_weight += tg->cfs_rq[i]->task_weight;
1544 }
1545
1546 aggregate(tg, sd)->rq_weight = rq_weight;
1547 aggregate(tg, sd)->task_weight = task_weight;
1548}
1549
1550/*
1551 * Redistribute tg->shares amongst all tg->cfs_rq[]s.
1552 */
1553static void __aggregate_redistribute_shares(struct task_group *tg)
1554{
1555 int i, max_cpu = smp_processor_id();
1556 unsigned long rq_weight = 0;
1557 unsigned long shares, max_shares = 0, shares_rem = tg->shares;
1558
1559 for_each_possible_cpu(i)
1560 rq_weight += tg->cfs_rq[i]->load.weight;
1561
1562 for_each_possible_cpu(i) {
1563 /*
1564 * divide shares proportional to the rq_weights.
1565 */
1566 shares = tg->shares * tg->cfs_rq[i]->load.weight;
1567 shares /= rq_weight + 1;
1568
1569 tg->cfs_rq[i]->shares = shares;
1570
1571 if (shares > max_shares) {
1572 max_shares = shares;
1573 max_cpu = i;
1574 }
1575 shares_rem -= shares;
1576 }
1577
1578 /*
1579 * Ensure it all adds up to tg->shares; we can loose a few
1580 * due to rounding down when computing the per-cpu shares.
1581 */
1582 if (shares_rem)
1583 tg->cfs_rq[max_cpu]->shares += shares_rem;
1584}
1585
1586/*
1587 * Compute the weight of this group on the given cpus.
1588 */
1589static
1590void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1591{
1592 unsigned long shares = 0;
1593 int i;
1594
1595again:
1596 for_each_cpu_mask(i, sd->span)
1597 shares += tg->cfs_rq[i]->shares;
1598
1599 /*
1600 * When the span doesn't have any shares assigned, but does have
1601 * tasks to run do a machine wide rebalance (should be rare).
1602 */
1603 if (unlikely(!shares && aggregate(tg, sd)->rq_weight)) {
1604 __aggregate_redistribute_shares(tg);
1605 goto again;
1606 }
1607
1608 aggregate(tg, sd)->shares = shares;
1609}
1610
1611/*
1612 * Compute the load fraction assigned to this group, relies on the aggregate
1613 * weight and this group's parent's load, i.e. top-down.
1614 */
1615static
1616void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1617{
1618 unsigned long load;
1619
1620 if (!tg->parent) {
1621 int i;
1622
1623 load = 0;
1624 for_each_cpu_mask(i, sd->span)
1625 load += cpu_rq(i)->load.weight;
1626
1627 } else {
1628 load = aggregate(tg->parent, sd)->load;
1629
1630 /*
1631 * shares is our weight in the parent's rq so
1632 * shares/parent->rq_weight gives our fraction of the load
1633 */
1634 load *= aggregate(tg, sd)->shares;
1635 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1636 }
1637
1638 aggregate(tg, sd)->load = load;
1639}
1640
1641static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1642
1643/*
1644 * Calculate and set the cpu's group shares.
1645 */
1646static void
1647__update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1648 int tcpu)
1649{
1650 int boost = 0;
1651 unsigned long shares;
1652 unsigned long rq_weight;
1653
1654 if (!tg->se[tcpu])
1655 return;
1656
1657 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1658
1659 /*
1660 * If there are currently no tasks on the cpu pretend there is one of
1661 * average load so that when a new task gets to run here it will not
1662 * get delayed by group starvation.
1663 */
1664 if (!rq_weight) {
1665 boost = 1;
1666 rq_weight = NICE_0_LOAD;
1667 }
1668
1669 /*
1670 * \Sum shares * rq_weight
1671 * shares = -----------------------
1672 * \Sum rq_weight
1673 *
1674 */
1675 shares = aggregate(tg, sd)->shares * rq_weight;
1676 shares /= aggregate(tg, sd)->rq_weight + 1;
1677
1678 /*
1679 * record the actual number of shares, not the boosted amount.
1680 */
1681 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1682
1683 if (shares < MIN_SHARES)
1684 shares = MIN_SHARES;
1685
1686 __set_se_shares(tg->se[tcpu], shares);
1687}
1688
1689/*
1690 * Re-adjust the weights on the cpu the task came from and on the cpu the
1691 * task went to.
1692 */
1693static void
1694__move_group_shares(struct task_group *tg, struct sched_domain *sd,
1695 int scpu, int dcpu)
1696{
1697 unsigned long shares;
1698
1699 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1700
1701 __update_group_shares_cpu(tg, sd, scpu);
1702 __update_group_shares_cpu(tg, sd, dcpu);
1703
1704 /*
1705 * ensure we never loose shares due to rounding errors in the
1706 * above redistribution.
1707 */
1708 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1709 if (shares)
1710 tg->cfs_rq[dcpu]->shares += shares;
1711}
1712
1713/*
1714 * Because changing a group's shares changes the weight of the super-group
1715 * we need to walk up the tree and change all shares until we hit the root.
1716 */
1717static void
1718move_group_shares(struct task_group *tg, struct sched_domain *sd,
1719 int scpu, int dcpu)
1720{
1721 while (tg) {
1722 __move_group_shares(tg, sd, scpu, dcpu);
1723 tg = tg->parent;
1724 }
1725}
1726
1727static
1728void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1729{
1730 unsigned long shares = aggregate(tg, sd)->shares;
1731 int i;
1732
1733 for_each_cpu_mask(i, sd->span) {
1734 struct rq *rq = cpu_rq(i);
1735 unsigned long flags;
1736
1737 spin_lock_irqsave(&rq->lock, flags);
1738 __update_group_shares_cpu(tg, sd, i);
1739 spin_unlock_irqrestore(&rq->lock, flags);
1740 }
1741
1742 aggregate_group_shares(tg, sd);
1743
1744 /*
1745 * ensure we never loose shares due to rounding errors in the
1746 * above redistribution.
1747 */
1748 shares -= aggregate(tg, sd)->shares;
1749 if (shares) {
1750 tg->cfs_rq[sd->first_cpu]->shares += shares;
1751 aggregate(tg, sd)->shares += shares;
1752 }
1753}
1754
1755/*
1756 * Calculate the accumulative weight and recursive load of each task group
1757 * while walking down the tree.
1758 */
1759static
1760void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1761{
1762 aggregate_group_weight(tg, sd);
1763 aggregate_group_shares(tg, sd);
1764 aggregate_group_load(tg, sd);
1765}
1766
1767/*
1768 * Rebalance the cpu shares while walking back up the tree.
1769 */
1770static
1771void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1772{
1773 aggregate_group_set_shares(tg, sd);
1774}
1775
1776static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1777
1778static void __init init_aggregate(void)
1779{
1780 int i;
1781
1782 for_each_possible_cpu(i)
1783 spin_lock_init(&per_cpu(aggregate_lock, i));
1784}
1785
1786static int get_aggregate(struct sched_domain *sd)
1787{
1788 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1789 return 0;
1790
1791 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1792 return 1;
1793}
1794
1795static void put_aggregate(struct sched_domain *sd)
1796{
1797 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1798}
1799
1800static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1801{
1802 cfs_rq->shares = shares;
1803}
1804
1805#else
1806
1807static inline void init_aggregate(void)
1808{
1809}
1810
1811static inline int get_aggregate(struct sched_domain *sd)
1812{
1813 return 0;
1814}
1815
1816static inline void put_aggregate(struct sched_domain *sd)
1817{
1818}
1819#endif
1820
1821#else /* CONFIG_SMP */
1822
1823#ifdef CONFIG_FAIR_GROUP_SCHED
1824static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1825{
1826}
1827#endif
1828
1829#endif /* CONFIG_SMP */
1830
1831#include "sched_stats.h"
1832#include "sched_idletask.c"
1833#include "sched_fair.c"
1834#include "sched_rt.c"
1835#ifdef CONFIG_SCHED_DEBUG
1836# include "sched_debug.c"
1837#endif
1838
1839#define sched_class_highest (&rt_sched_class)
1840
1841static void inc_nr_running(struct rq *rq)
1842{
1843 rq->nr_running++;
1844}
1845
1846static void dec_nr_running(struct rq *rq)
1847{
1848 rq->nr_running--;
1849}
1850
1851static void set_load_weight(struct task_struct *p)
1852{
1853 if (task_has_rt_policy(p)) {
1854 p->se.load.weight = prio_to_weight[0] * 2;
1855 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1856 return;
1857 }
1858
1859 /*
1860 * SCHED_IDLE tasks get minimal weight:
1861 */
1862 if (p->policy == SCHED_IDLE) {
1863 p->se.load.weight = WEIGHT_IDLEPRIO;
1864 p->se.load.inv_weight = WMULT_IDLEPRIO;
1865 return;
1866 }
1867
1868 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1869 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1870}
1871
1872static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1873{
1874 sched_info_queued(p);
1875 p->sched_class->enqueue_task(rq, p, wakeup);
1876 p->se.on_rq = 1;
1877}
1878
1879static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1880{
1881 p->sched_class->dequeue_task(rq, p, sleep);
1882 p->se.on_rq = 0;
1883}
1884
1885/*
1886 * __normal_prio - return the priority that is based on the static prio
1887 */
1888static inline int __normal_prio(struct task_struct *p)
1889{
1890 return p->static_prio;
1891}
1892
1893/*
1894 * Calculate the expected normal priority: i.e. priority
1895 * without taking RT-inheritance into account. Might be
1896 * boosted by interactivity modifiers. Changes upon fork,
1897 * setprio syscalls, and whenever the interactivity
1898 * estimator recalculates.
1899 */
1900static inline int normal_prio(struct task_struct *p)
1901{
1902 int prio;
1903
1904 if (task_has_rt_policy(p))
1905 prio = MAX_RT_PRIO-1 - p->rt_priority;
1906 else
1907 prio = __normal_prio(p);
1908 return prio;
1909}
1910
1911/*
1912 * Calculate the current priority, i.e. the priority
1913 * taken into account by the scheduler. This value might
1914 * be boosted by RT tasks, or might be boosted by
1915 * interactivity modifiers. Will be RT if the task got
1916 * RT-boosted. If not then it returns p->normal_prio.
1917 */
1918static int effective_prio(struct task_struct *p)
1919{
1920 p->normal_prio = normal_prio(p);
1921 /*
1922 * If we are RT tasks or we were boosted to RT priority,
1923 * keep the priority unchanged. Otherwise, update priority
1924 * to the normal priority:
1925 */
1926 if (!rt_prio(p->prio))
1927 return p->normal_prio;
1928 return p->prio;
1929}
1930
1931/*
1932 * activate_task - move a task to the runqueue.
1933 */
1934static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1935{
1936 if (task_contributes_to_load(p))
1937 rq->nr_uninterruptible--;
1938
1939 enqueue_task(rq, p, wakeup);
1940 inc_nr_running(rq);
1941}
1942
1943/*
1944 * deactivate_task - remove a task from the runqueue.
1945 */
1946static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1947{
1948 if (task_contributes_to_load(p))
1949 rq->nr_uninterruptible++;
1950
1951 dequeue_task(rq, p, sleep);
1952 dec_nr_running(rq);
1953}
1954
1955/**
1956 * task_curr - is this task currently executing on a CPU?
1957 * @p: the task in question.
1958 */
1959inline int task_curr(const struct task_struct *p)
1960{
1961 return cpu_curr(task_cpu(p)) == p;
1962}
1963
1964/* Used instead of source_load when we know the type == 0 */
1965unsigned long weighted_cpuload(const int cpu)
1966{
1967 return cpu_rq(cpu)->load.weight;
1968}
1969
1970static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1971{
1972 set_task_rq(p, cpu);
1973#ifdef CONFIG_SMP
1974 /*
1975 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1976 * successfuly executed on another CPU. We must ensure that updates of
1977 * per-task data have been completed by this moment.
1978 */
1979 smp_wmb();
1980 task_thread_info(p)->cpu = cpu;
1981#endif
1982}
1983
1984static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1985 const struct sched_class *prev_class,
1986 int oldprio, int running)
1987{
1988 if (prev_class != p->sched_class) {
1989 if (prev_class->switched_from)
1990 prev_class->switched_from(rq, p, running);
1991 p->sched_class->switched_to(rq, p, running);
1992 } else
1993 p->sched_class->prio_changed(rq, p, oldprio, running);
1994}
1995
1996#ifdef CONFIG_SMP
1997
1998/*
1999 * Is this task likely cache-hot:
2000 */
2001static int
2002task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2003{
2004 s64 delta;
2005
2006 /*
2007 * Buddy candidates are cache hot:
2008 */
2009 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2010 return 1;
2011
2012 if (p->sched_class != &fair_sched_class)
2013 return 0;
2014
2015 if (sysctl_sched_migration_cost == -1)
2016 return 1;
2017 if (sysctl_sched_migration_cost == 0)
2018 return 0;
2019
2020 delta = now - p->se.exec_start;
2021
2022 return delta < (s64)sysctl_sched_migration_cost;
2023}
2024
2025
2026void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2027{
2028 int old_cpu = task_cpu(p);
2029 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2030 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2031 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2032 u64 clock_offset;
2033
2034 clock_offset = old_rq->clock - new_rq->clock;
2035
2036#ifdef CONFIG_SCHEDSTATS
2037 if (p->se.wait_start)
2038 p->se.wait_start -= clock_offset;
2039 if (p->se.sleep_start)
2040 p->se.sleep_start -= clock_offset;
2041 if (p->se.block_start)
2042 p->se.block_start -= clock_offset;
2043 if (old_cpu != new_cpu) {
2044 schedstat_inc(p, se.nr_migrations);
2045 if (task_hot(p, old_rq->clock, NULL))
2046 schedstat_inc(p, se.nr_forced2_migrations);
2047 }
2048#endif
2049 p->se.vruntime -= old_cfsrq->min_vruntime -
2050 new_cfsrq->min_vruntime;
2051
2052 __set_task_cpu(p, new_cpu);
2053}
2054
2055struct migration_req {
2056 struct list_head list;
2057
2058 struct task_struct *task;
2059 int dest_cpu;
2060
2061 struct completion done;
2062};
2063
2064/*
2065 * The task's runqueue lock must be held.
2066 * Returns true if you have to wait for migration thread.
2067 */
2068static int
2069migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2070{
2071 struct rq *rq = task_rq(p);
2072
2073 /*
2074 * If the task is not on a runqueue (and not running), then
2075 * it is sufficient to simply update the task's cpu field.
2076 */
2077 if (!p->se.on_rq && !task_running(rq, p)) {
2078 set_task_cpu(p, dest_cpu);
2079 return 0;
2080 }
2081
2082 init_completion(&req->done);
2083 req->task = p;
2084 req->dest_cpu = dest_cpu;
2085 list_add(&req->list, &rq->migration_queue);
2086
2087 return 1;
2088}
2089
2090/*
2091 * wait_task_inactive - wait for a thread to unschedule.
2092 *
2093 * The caller must ensure that the task *will* unschedule sometime soon,
2094 * else this function might spin for a *long* time. This function can't
2095 * be called with interrupts off, or it may introduce deadlock with
2096 * smp_call_function() if an IPI is sent by the same process we are
2097 * waiting to become inactive.
2098 */
2099void wait_task_inactive(struct task_struct *p)
2100{
2101 unsigned long flags;
2102 int running, on_rq;
2103 struct rq *rq;
2104
2105 for (;;) {
2106 /*
2107 * We do the initial early heuristics without holding
2108 * any task-queue locks at all. We'll only try to get
2109 * the runqueue lock when things look like they will
2110 * work out!
2111 */
2112 rq = task_rq(p);
2113
2114 /*
2115 * If the task is actively running on another CPU
2116 * still, just relax and busy-wait without holding
2117 * any locks.
2118 *
2119 * NOTE! Since we don't hold any locks, it's not
2120 * even sure that "rq" stays as the right runqueue!
2121 * But we don't care, since "task_running()" will
2122 * return false if the runqueue has changed and p
2123 * is actually now running somewhere else!
2124 */
2125 while (task_running(rq, p))
2126 cpu_relax();
2127
2128 /*
2129 * Ok, time to look more closely! We need the rq
2130 * lock now, to be *sure*. If we're wrong, we'll
2131 * just go back and repeat.
2132 */
2133 rq = task_rq_lock(p, &flags);
2134 running = task_running(rq, p);
2135 on_rq = p->se.on_rq;
2136 task_rq_unlock(rq, &flags);
2137
2138 /*
2139 * Was it really running after all now that we
2140 * checked with the proper locks actually held?
2141 *
2142 * Oops. Go back and try again..
2143 */
2144 if (unlikely(running)) {
2145 cpu_relax();
2146 continue;
2147 }
2148
2149 /*
2150 * It's not enough that it's not actively running,
2151 * it must be off the runqueue _entirely_, and not
2152 * preempted!
2153 *
2154 * So if it wa still runnable (but just not actively
2155 * running right now), it's preempted, and we should
2156 * yield - it could be a while.
2157 */
2158 if (unlikely(on_rq)) {
2159 schedule_timeout_uninterruptible(1);
2160 continue;
2161 }
2162
2163 /*
2164 * Ahh, all good. It wasn't running, and it wasn't
2165 * runnable, which means that it will never become
2166 * running in the future either. We're all done!
2167 */
2168 break;
2169 }
2170}
2171
2172/***
2173 * kick_process - kick a running thread to enter/exit the kernel
2174 * @p: the to-be-kicked thread
2175 *
2176 * Cause a process which is running on another CPU to enter
2177 * kernel-mode, without any delay. (to get signals handled.)
2178 *
2179 * NOTE: this function doesnt have to take the runqueue lock,
2180 * because all it wants to ensure is that the remote task enters
2181 * the kernel. If the IPI races and the task has been migrated
2182 * to another CPU then no harm is done and the purpose has been
2183 * achieved as well.
2184 */
2185void kick_process(struct task_struct *p)
2186{
2187 int cpu;
2188
2189 preempt_disable();
2190 cpu = task_cpu(p);
2191 if ((cpu != smp_processor_id()) && task_curr(p))
2192 smp_send_reschedule(cpu);
2193 preempt_enable();
2194}
2195
2196/*
2197 * Return a low guess at the load of a migration-source cpu weighted
2198 * according to the scheduling class and "nice" value.
2199 *
2200 * We want to under-estimate the load of migration sources, to
2201 * balance conservatively.
2202 */
2203static unsigned long source_load(int cpu, int type)
2204{
2205 struct rq *rq = cpu_rq(cpu);
2206 unsigned long total = weighted_cpuload(cpu);
2207
2208 if (type == 0)
2209 return total;
2210
2211 return min(rq->cpu_load[type-1], total);
2212}
2213
2214/*
2215 * Return a high guess at the load of a migration-target cpu weighted
2216 * according to the scheduling class and "nice" value.
2217 */
2218static unsigned long target_load(int cpu, int type)
2219{
2220 struct rq *rq = cpu_rq(cpu);
2221 unsigned long total = weighted_cpuload(cpu);
2222
2223 if (type == 0)
2224 return total;
2225
2226 return max(rq->cpu_load[type-1], total);
2227}
2228
2229/*
2230 * Return the average load per task on the cpu's run queue
2231 */
2232static unsigned long cpu_avg_load_per_task(int cpu)
2233{
2234 struct rq *rq = cpu_rq(cpu);
2235 unsigned long total = weighted_cpuload(cpu);
2236 unsigned long n = rq->nr_running;
2237
2238 return n ? total / n : SCHED_LOAD_SCALE;
2239}
2240
2241/*
2242 * find_idlest_group finds and returns the least busy CPU group within the
2243 * domain.
2244 */
2245static struct sched_group *
2246find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2247{
2248 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2249 unsigned long min_load = ULONG_MAX, this_load = 0;
2250 int load_idx = sd->forkexec_idx;
2251 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2252
2253 do {
2254 unsigned long load, avg_load;
2255 int local_group;
2256 int i;
2257
2258 /* Skip over this group if it has no CPUs allowed */
2259 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2260 continue;
2261
2262 local_group = cpu_isset(this_cpu, group->cpumask);
2263
2264 /* Tally up the load of all CPUs in the group */
2265 avg_load = 0;
2266
2267 for_each_cpu_mask(i, group->cpumask) {
2268 /* Bias balancing toward cpus of our domain */
2269 if (local_group)
2270 load = source_load(i, load_idx);
2271 else
2272 load = target_load(i, load_idx);
2273
2274 avg_load += load;
2275 }
2276
2277 /* Adjust by relative CPU power of the group */
2278 avg_load = sg_div_cpu_power(group,
2279 avg_load * SCHED_LOAD_SCALE);
2280
2281 if (local_group) {
2282 this_load = avg_load;
2283 this = group;
2284 } else if (avg_load < min_load) {
2285 min_load = avg_load;
2286 idlest = group;
2287 }
2288 } while (group = group->next, group != sd->groups);
2289
2290 if (!idlest || 100*this_load < imbalance*min_load)
2291 return NULL;
2292 return idlest;
2293}
2294
2295/*
2296 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2297 */
2298static int
2299find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2300 cpumask_t *tmp)
2301{
2302 unsigned long load, min_load = ULONG_MAX;
2303 int idlest = -1;
2304 int i;
2305
2306 /* Traverse only the allowed CPUs */
2307 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2308
2309 for_each_cpu_mask(i, *tmp) {
2310 load = weighted_cpuload(i);
2311
2312 if (load < min_load || (load == min_load && i == this_cpu)) {
2313 min_load = load;
2314 idlest = i;
2315 }
2316 }
2317
2318 return idlest;
2319}
2320
2321/*
2322 * sched_balance_self: balance the current task (running on cpu) in domains
2323 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2324 * SD_BALANCE_EXEC.
2325 *
2326 * Balance, ie. select the least loaded group.
2327 *
2328 * Returns the target CPU number, or the same CPU if no balancing is needed.
2329 *
2330 * preempt must be disabled.
2331 */
2332static int sched_balance_self(int cpu, int flag)
2333{
2334 struct task_struct *t = current;
2335 struct sched_domain *tmp, *sd = NULL;
2336
2337 for_each_domain(cpu, tmp) {
2338 /*
2339 * If power savings logic is enabled for a domain, stop there.
2340 */
2341 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2342 break;
2343 if (tmp->flags & flag)
2344 sd = tmp;
2345 }
2346
2347 while (sd) {
2348 cpumask_t span, tmpmask;
2349 struct sched_group *group;
2350 int new_cpu, weight;
2351
2352 if (!(sd->flags & flag)) {
2353 sd = sd->child;
2354 continue;
2355 }
2356
2357 span = sd->span;
2358 group = find_idlest_group(sd, t, cpu);
2359 if (!group) {
2360 sd = sd->child;
2361 continue;
2362 }
2363
2364 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2365 if (new_cpu == -1 || new_cpu == cpu) {
2366 /* Now try balancing at a lower domain level of cpu */
2367 sd = sd->child;
2368 continue;
2369 }
2370
2371 /* Now try balancing at a lower domain level of new_cpu */
2372 cpu = new_cpu;
2373 sd = NULL;
2374 weight = cpus_weight(span);
2375 for_each_domain(cpu, tmp) {
2376 if (weight <= cpus_weight(tmp->span))
2377 break;
2378 if (tmp->flags & flag)
2379 sd = tmp;
2380 }
2381 /* while loop will break here if sd == NULL */
2382 }
2383
2384 return cpu;
2385}
2386
2387#endif /* CONFIG_SMP */
2388
2389/***
2390 * try_to_wake_up - wake up a thread
2391 * @p: the to-be-woken-up thread
2392 * @state: the mask of task states that can be woken
2393 * @sync: do a synchronous wakeup?
2394 *
2395 * Put it on the run-queue if it's not already there. The "current"
2396 * thread is always on the run-queue (except when the actual
2397 * re-schedule is in progress), and as such you're allowed to do
2398 * the simpler "current->state = TASK_RUNNING" to mark yourself
2399 * runnable without the overhead of this.
2400 *
2401 * returns failure only if the task is already active.
2402 */
2403static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2404{
2405 int cpu, orig_cpu, this_cpu, success = 0;
2406 unsigned long flags;
2407 long old_state;
2408 struct rq *rq;
2409
2410 if (!sched_feat(SYNC_WAKEUPS))
2411 sync = 0;
2412
2413 smp_wmb();
2414 rq = task_rq_lock(p, &flags);
2415 old_state = p->state;
2416 if (!(old_state & state))
2417 goto out;
2418
2419 if (p->se.on_rq)
2420 goto out_running;
2421
2422 cpu = task_cpu(p);
2423 orig_cpu = cpu;
2424 this_cpu = smp_processor_id();
2425
2426#ifdef CONFIG_SMP
2427 if (unlikely(task_running(rq, p)))
2428 goto out_activate;
2429
2430 cpu = p->sched_class->select_task_rq(p, sync);
2431 if (cpu != orig_cpu) {
2432 set_task_cpu(p, cpu);
2433 task_rq_unlock(rq, &flags);
2434 /* might preempt at this point */
2435 rq = task_rq_lock(p, &flags);
2436 old_state = p->state;
2437 if (!(old_state & state))
2438 goto out;
2439 if (p->se.on_rq)
2440 goto out_running;
2441
2442 this_cpu = smp_processor_id();
2443 cpu = task_cpu(p);
2444 }
2445
2446#ifdef CONFIG_SCHEDSTATS
2447 schedstat_inc(rq, ttwu_count);
2448 if (cpu == this_cpu)
2449 schedstat_inc(rq, ttwu_local);
2450 else {
2451 struct sched_domain *sd;
2452 for_each_domain(this_cpu, sd) {
2453 if (cpu_isset(cpu, sd->span)) {
2454 schedstat_inc(sd, ttwu_wake_remote);
2455 break;
2456 }
2457 }
2458 }
2459#endif
2460
2461out_activate:
2462#endif /* CONFIG_SMP */
2463 schedstat_inc(p, se.nr_wakeups);
2464 if (sync)
2465 schedstat_inc(p, se.nr_wakeups_sync);
2466 if (orig_cpu != cpu)
2467 schedstat_inc(p, se.nr_wakeups_migrate);
2468 if (cpu == this_cpu)
2469 schedstat_inc(p, se.nr_wakeups_local);
2470 else
2471 schedstat_inc(p, se.nr_wakeups_remote);
2472 update_rq_clock(rq);
2473 activate_task(rq, p, 1);
2474 success = 1;
2475
2476out_running:
2477 check_preempt_curr(rq, p);
2478
2479 p->state = TASK_RUNNING;
2480#ifdef CONFIG_SMP
2481 if (p->sched_class->task_wake_up)
2482 p->sched_class->task_wake_up(rq, p);
2483#endif
2484out:
2485 task_rq_unlock(rq, &flags);
2486
2487 return success;
2488}
2489
2490int wake_up_process(struct task_struct *p)
2491{
2492 return try_to_wake_up(p, TASK_ALL, 0);
2493}
2494EXPORT_SYMBOL(wake_up_process);
2495
2496int wake_up_state(struct task_struct *p, unsigned int state)
2497{
2498 return try_to_wake_up(p, state, 0);
2499}
2500
2501/*
2502 * Perform scheduler related setup for a newly forked process p.
2503 * p is forked by current.
2504 *
2505 * __sched_fork() is basic setup used by init_idle() too:
2506 */
2507static void __sched_fork(struct task_struct *p)
2508{
2509 p->se.exec_start = 0;
2510 p->se.sum_exec_runtime = 0;
2511 p->se.prev_sum_exec_runtime = 0;
2512 p->se.last_wakeup = 0;
2513 p->se.avg_overlap = 0;
2514
2515#ifdef CONFIG_SCHEDSTATS
2516 p->se.wait_start = 0;
2517 p->se.sum_sleep_runtime = 0;
2518 p->se.sleep_start = 0;
2519 p->se.block_start = 0;
2520 p->se.sleep_max = 0;
2521 p->se.block_max = 0;
2522 p->se.exec_max = 0;
2523 p->se.slice_max = 0;
2524 p->se.wait_max = 0;
2525#endif
2526
2527 INIT_LIST_HEAD(&p->rt.run_list);
2528 p->se.on_rq = 0;
2529 INIT_LIST_HEAD(&p->se.group_node);
2530
2531#ifdef CONFIG_PREEMPT_NOTIFIERS
2532 INIT_HLIST_HEAD(&p->preempt_notifiers);
2533#endif
2534
2535 /*
2536 * We mark the process as running here, but have not actually
2537 * inserted it onto the runqueue yet. This guarantees that
2538 * nobody will actually run it, and a signal or other external
2539 * event cannot wake it up and insert it on the runqueue either.
2540 */
2541 p->state = TASK_RUNNING;
2542}
2543
2544/*
2545 * fork()/clone()-time setup:
2546 */
2547void sched_fork(struct task_struct *p, int clone_flags)
2548{
2549 int cpu = get_cpu();
2550
2551 __sched_fork(p);
2552
2553#ifdef CONFIG_SMP
2554 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2555#endif
2556 set_task_cpu(p, cpu);
2557
2558 /*
2559 * Make sure we do not leak PI boosting priority to the child:
2560 */
2561 p->prio = current->normal_prio;
2562 if (!rt_prio(p->prio))
2563 p->sched_class = &fair_sched_class;
2564
2565#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2566 if (likely(sched_info_on()))
2567 memset(&p->sched_info, 0, sizeof(p->sched_info));
2568#endif
2569#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2570 p->oncpu = 0;
2571#endif
2572#ifdef CONFIG_PREEMPT
2573 /* Want to start with kernel preemption disabled. */
2574 task_thread_info(p)->preempt_count = 1;
2575#endif
2576 put_cpu();
2577}
2578
2579/*
2580 * wake_up_new_task - wake up a newly created task for the first time.
2581 *
2582 * This function will do some initial scheduler statistics housekeeping
2583 * that must be done for every newly created context, then puts the task
2584 * on the runqueue and wakes it.
2585 */
2586void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2587{
2588 unsigned long flags;
2589 struct rq *rq;
2590
2591 rq = task_rq_lock(p, &flags);
2592 BUG_ON(p->state != TASK_RUNNING);
2593 update_rq_clock(rq);
2594
2595 p->prio = effective_prio(p);
2596
2597 if (!p->sched_class->task_new || !current->se.on_rq) {
2598 activate_task(rq, p, 0);
2599 } else {
2600 /*
2601 * Let the scheduling class do new task startup
2602 * management (if any):
2603 */
2604 p->sched_class->task_new(rq, p);
2605 inc_nr_running(rq);
2606 }
2607 check_preempt_curr(rq, p);
2608#ifdef CONFIG_SMP
2609 if (p->sched_class->task_wake_up)
2610 p->sched_class->task_wake_up(rq, p);
2611#endif
2612 task_rq_unlock(rq, &flags);
2613}
2614
2615#ifdef CONFIG_PREEMPT_NOTIFIERS
2616
2617/**
2618 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2619 * @notifier: notifier struct to register
2620 */
2621void preempt_notifier_register(struct preempt_notifier *notifier)
2622{
2623 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2624}
2625EXPORT_SYMBOL_GPL(preempt_notifier_register);
2626
2627/**
2628 * preempt_notifier_unregister - no longer interested in preemption notifications
2629 * @notifier: notifier struct to unregister
2630 *
2631 * This is safe to call from within a preemption notifier.
2632 */
2633void preempt_notifier_unregister(struct preempt_notifier *notifier)
2634{
2635 hlist_del(&notifier->link);
2636}
2637EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2638
2639static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2640{
2641 struct preempt_notifier *notifier;
2642 struct hlist_node *node;
2643
2644 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2645 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2646}
2647
2648static void
2649fire_sched_out_preempt_notifiers(struct task_struct *curr,
2650 struct task_struct *next)
2651{
2652 struct preempt_notifier *notifier;
2653 struct hlist_node *node;
2654
2655 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2656 notifier->ops->sched_out(notifier, next);
2657}
2658
2659#else
2660
2661static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2662{
2663}
2664
2665static void
2666fire_sched_out_preempt_notifiers(struct task_struct *curr,
2667 struct task_struct *next)
2668{
2669}
2670
2671#endif
2672
2673/**
2674 * prepare_task_switch - prepare to switch tasks
2675 * @rq: the runqueue preparing to switch
2676 * @prev: the current task that is being switched out
2677 * @next: the task we are going to switch to.
2678 *
2679 * This is called with the rq lock held and interrupts off. It must
2680 * be paired with a subsequent finish_task_switch after the context
2681 * switch.
2682 *
2683 * prepare_task_switch sets up locking and calls architecture specific
2684 * hooks.
2685 */
2686static inline void
2687prepare_task_switch(struct rq *rq, struct task_struct *prev,
2688 struct task_struct *next)
2689{
2690 fire_sched_out_preempt_notifiers(prev, next);
2691 prepare_lock_switch(rq, next);
2692 prepare_arch_switch(next);
2693}
2694
2695/**
2696 * finish_task_switch - clean up after a task-switch
2697 * @rq: runqueue associated with task-switch
2698 * @prev: the thread we just switched away from.
2699 *
2700 * finish_task_switch must be called after the context switch, paired
2701 * with a prepare_task_switch call before the context switch.
2702 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2703 * and do any other architecture-specific cleanup actions.
2704 *
2705 * Note that we may have delayed dropping an mm in context_switch(). If
2706 * so, we finish that here outside of the runqueue lock. (Doing it
2707 * with the lock held can cause deadlocks; see schedule() for
2708 * details.)
2709 */
2710static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2711 __releases(rq->lock)
2712{
2713 struct mm_struct *mm = rq->prev_mm;
2714 long prev_state;
2715
2716 rq->prev_mm = NULL;
2717
2718 /*
2719 * A task struct has one reference for the use as "current".
2720 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2721 * schedule one last time. The schedule call will never return, and
2722 * the scheduled task must drop that reference.
2723 * The test for TASK_DEAD must occur while the runqueue locks are
2724 * still held, otherwise prev could be scheduled on another cpu, die
2725 * there before we look at prev->state, and then the reference would
2726 * be dropped twice.
2727 * Manfred Spraul <manfred@colorfullife.com>
2728 */
2729 prev_state = prev->state;
2730 finish_arch_switch(prev);
2731 finish_lock_switch(rq, prev);
2732#ifdef CONFIG_SMP
2733 if (current->sched_class->post_schedule)
2734 current->sched_class->post_schedule(rq);
2735#endif
2736
2737 fire_sched_in_preempt_notifiers(current);
2738 if (mm)
2739 mmdrop(mm);
2740 if (unlikely(prev_state == TASK_DEAD)) {
2741 /*
2742 * Remove function-return probe instances associated with this
2743 * task and put them back on the free list.
2744 */
2745 kprobe_flush_task(prev);
2746 put_task_struct(prev);
2747 }
2748}
2749
2750/**
2751 * schedule_tail - first thing a freshly forked thread must call.
2752 * @prev: the thread we just switched away from.
2753 */
2754asmlinkage void schedule_tail(struct task_struct *prev)
2755 __releases(rq->lock)
2756{
2757 struct rq *rq = this_rq();
2758
2759 finish_task_switch(rq, prev);
2760#ifdef __ARCH_WANT_UNLOCKED_CTXSW
2761 /* In this case, finish_task_switch does not reenable preemption */
2762 preempt_enable();
2763#endif
2764 if (current->set_child_tid)
2765 put_user(task_pid_vnr(current), current->set_child_tid);
2766}
2767
2768/*
2769 * context_switch - switch to the new MM and the new
2770 * thread's register state.
2771 */
2772static inline void
2773context_switch(struct rq *rq, struct task_struct *prev,
2774 struct task_struct *next)
2775{
2776 struct mm_struct *mm, *oldmm;
2777
2778 prepare_task_switch(rq, prev, next);
2779 mm = next->mm;
2780 oldmm = prev->active_mm;
2781 /*
2782 * For paravirt, this is coupled with an exit in switch_to to
2783 * combine the page table reload and the switch backend into
2784 * one hypercall.
2785 */
2786 arch_enter_lazy_cpu_mode();
2787
2788 if (unlikely(!mm)) {
2789 next->active_mm = oldmm;
2790 atomic_inc(&oldmm->mm_count);
2791 enter_lazy_tlb(oldmm, next);
2792 } else
2793 switch_mm(oldmm, mm, next);
2794
2795 if (unlikely(!prev->mm)) {
2796 prev->active_mm = NULL;
2797 rq->prev_mm = oldmm;
2798 }
2799 /*
2800 * Since the runqueue lock will be released by the next
2801 * task (which is an invalid locking op but in the case
2802 * of the scheduler it's an obvious special-case), so we
2803 * do an early lockdep release here:
2804 */
2805#ifndef __ARCH_WANT_UNLOCKED_CTXSW
2806 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2807#endif
2808
2809 /* Here we just switch the register state and the stack. */
2810 switch_to(prev, next, prev);
2811
2812 barrier();
2813 /*
2814 * this_rq must be evaluated again because prev may have moved
2815 * CPUs since it called schedule(), thus the 'rq' on its stack
2816 * frame will be invalid.
2817 */
2818 finish_task_switch(this_rq(), prev);
2819}
2820
2821/*
2822 * nr_running, nr_uninterruptible and nr_context_switches:
2823 *
2824 * externally visible scheduler statistics: current number of runnable
2825 * threads, current number of uninterruptible-sleeping threads, total
2826 * number of context switches performed since bootup.
2827 */
2828unsigned long nr_running(void)
2829{
2830 unsigned long i, sum = 0;
2831
2832 for_each_online_cpu(i)
2833 sum += cpu_rq(i)->nr_running;
2834
2835 return sum;
2836}
2837
2838unsigned long nr_uninterruptible(void)
2839{
2840 unsigned long i, sum = 0;
2841
2842 for_each_possible_cpu(i)
2843 sum += cpu_rq(i)->nr_uninterruptible;
2844
2845 /*
2846 * Since we read the counters lockless, it might be slightly
2847 * inaccurate. Do not allow it to go below zero though:
2848 */
2849 if (unlikely((long)sum < 0))
2850 sum = 0;
2851
2852 return sum;
2853}
2854
2855unsigned long long nr_context_switches(void)
2856{
2857 int i;
2858 unsigned long long sum = 0;
2859
2860 for_each_possible_cpu(i)
2861 sum += cpu_rq(i)->nr_switches;
2862
2863 return sum;
2864}
2865
2866unsigned long nr_iowait(void)
2867{
2868 unsigned long i, sum = 0;
2869
2870 for_each_possible_cpu(i)
2871 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2872
2873 return sum;
2874}
2875
2876unsigned long nr_active(void)
2877{
2878 unsigned long i, running = 0, uninterruptible = 0;
2879
2880 for_each_online_cpu(i) {
2881 running += cpu_rq(i)->nr_running;
2882 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2883 }
2884
2885 if (unlikely((long)uninterruptible < 0))
2886 uninterruptible = 0;
2887
2888 return running + uninterruptible;
2889}
2890
2891/*
2892 * Update rq->cpu_load[] statistics. This function is usually called every
2893 * scheduler tick (TICK_NSEC).
2894 */
2895static void update_cpu_load(struct rq *this_rq)
2896{
2897 unsigned long this_load = this_rq->load.weight;
2898 int i, scale;
2899
2900 this_rq->nr_load_updates++;
2901
2902 /* Update our load: */
2903 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2904 unsigned long old_load, new_load;
2905
2906 /* scale is effectively 1 << i now, and >> i divides by scale */
2907
2908 old_load = this_rq->cpu_load[i];
2909 new_load = this_load;
2910 /*
2911 * Round up the averaging division if load is increasing. This
2912 * prevents us from getting stuck on 9 if the load is 10, for
2913 * example.
2914 */
2915 if (new_load > old_load)
2916 new_load += scale-1;
2917 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2918 }
2919}
2920
2921#ifdef CONFIG_SMP
2922
2923/*
2924 * double_rq_lock - safely lock two runqueues
2925 *
2926 * Note this does not disable interrupts like task_rq_lock,
2927 * you need to do so manually before calling.
2928 */
2929static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2930 __acquires(rq1->lock)
2931 __acquires(rq2->lock)
2932{
2933 BUG_ON(!irqs_disabled());
2934 if (rq1 == rq2) {
2935 spin_lock(&rq1->lock);
2936 __acquire(rq2->lock); /* Fake it out ;) */
2937 } else {
2938 if (rq1 < rq2) {
2939 spin_lock(&rq1->lock);
2940 spin_lock(&rq2->lock);
2941 } else {
2942 spin_lock(&rq2->lock);
2943 spin_lock(&rq1->lock);
2944 }
2945 }
2946 update_rq_clock(rq1);
2947 update_rq_clock(rq2);
2948}
2949
2950/*
2951 * double_rq_unlock - safely unlock two runqueues
2952 *
2953 * Note this does not restore interrupts like task_rq_unlock,
2954 * you need to do so manually after calling.
2955 */
2956static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2957 __releases(rq1->lock)
2958 __releases(rq2->lock)
2959{
2960 spin_unlock(&rq1->lock);
2961 if (rq1 != rq2)
2962 spin_unlock(&rq2->lock);
2963 else
2964 __release(rq2->lock);
2965}
2966
2967/*
2968 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2969 */
2970static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2971 __releases(this_rq->lock)
2972 __acquires(busiest->lock)
2973 __acquires(this_rq->lock)
2974{
2975 int ret = 0;
2976
2977 if (unlikely(!irqs_disabled())) {
2978 /* printk() doesn't work good under rq->lock */
2979 spin_unlock(&this_rq->lock);
2980 BUG_ON(1);
2981 }
2982 if (unlikely(!spin_trylock(&busiest->lock))) {
2983 if (busiest < this_rq) {
2984 spin_unlock(&this_rq->lock);
2985 spin_lock(&busiest->lock);
2986 spin_lock(&this_rq->lock);
2987 ret = 1;
2988 } else
2989 spin_lock(&busiest->lock);
2990 }
2991 return ret;
2992}
2993
2994/*
2995 * If dest_cpu is allowed for this process, migrate the task to it.
2996 * This is accomplished by forcing the cpu_allowed mask to only
2997 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2998 * the cpu_allowed mask is restored.
2999 */
3000static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3001{
3002 struct migration_req req;
3003 unsigned long flags;
3004 struct rq *rq;
3005
3006 rq = task_rq_lock(p, &flags);
3007 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3008 || unlikely(cpu_is_offline(dest_cpu)))
3009 goto out;
3010
3011 /* force the process onto the specified CPU */
3012 if (migrate_task(p, dest_cpu, &req)) {
3013 /* Need to wait for migration thread (might exit: take ref). */
3014 struct task_struct *mt = rq->migration_thread;
3015
3016 get_task_struct(mt);
3017 task_rq_unlock(rq, &flags);
3018 wake_up_process(mt);
3019 put_task_struct(mt);
3020 wait_for_completion(&req.done);
3021
3022 return;
3023 }
3024out:
3025 task_rq_unlock(rq, &flags);
3026}
3027
3028/*
3029 * sched_exec - execve() is a valuable balancing opportunity, because at
3030 * this point the task has the smallest effective memory and cache footprint.
3031 */
3032void sched_exec(void)
3033{
3034 int new_cpu, this_cpu = get_cpu();
3035 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3036 put_cpu();
3037 if (new_cpu != this_cpu)
3038 sched_migrate_task(current, new_cpu);
3039}
3040
3041/*
3042 * pull_task - move a task from a remote runqueue to the local runqueue.
3043 * Both runqueues must be locked.
3044 */
3045static void pull_task(struct rq *src_rq, struct task_struct *p,
3046 struct rq *this_rq, int this_cpu)
3047{
3048 deactivate_task(src_rq, p, 0);
3049 set_task_cpu(p, this_cpu);
3050 activate_task(this_rq, p, 0);
3051 /*
3052 * Note that idle threads have a prio of MAX_PRIO, for this test
3053 * to be always true for them.
3054 */
3055 check_preempt_curr(this_rq, p);
3056}
3057
3058/*
3059 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3060 */
3061static
3062int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3063 struct sched_domain *sd, enum cpu_idle_type idle,
3064 int *all_pinned)
3065{
3066 /*
3067 * We do not migrate tasks that are:
3068 * 1) running (obviously), or
3069 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3070 * 3) are cache-hot on their current CPU.
3071 */
3072 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3073 schedstat_inc(p, se.nr_failed_migrations_affine);
3074 return 0;
3075 }
3076 *all_pinned = 0;
3077
3078 if (task_running(rq, p)) {
3079 schedstat_inc(p, se.nr_failed_migrations_running);
3080 return 0;
3081 }
3082
3083 /*
3084 * Aggressive migration if:
3085 * 1) task is cache cold, or
3086 * 2) too many balance attempts have failed.
3087 */
3088
3089 if (!task_hot(p, rq->clock, sd) ||
3090 sd->nr_balance_failed > sd->cache_nice_tries) {
3091#ifdef CONFIG_SCHEDSTATS
3092 if (task_hot(p, rq->clock, sd)) {
3093 schedstat_inc(sd, lb_hot_gained[idle]);
3094 schedstat_inc(p, se.nr_forced_migrations);
3095 }
3096#endif
3097 return 1;
3098 }
3099
3100 if (task_hot(p, rq->clock, sd)) {
3101 schedstat_inc(p, se.nr_failed_migrations_hot);
3102 return 0;
3103 }
3104 return 1;
3105}
3106
3107static unsigned long
3108balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3109 unsigned long max_load_move, struct sched_domain *sd,
3110 enum cpu_idle_type idle, int *all_pinned,
3111 int *this_best_prio, struct rq_iterator *iterator)
3112{
3113 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3114 struct task_struct *p;
3115 long rem_load_move = max_load_move;
3116
3117 if (max_load_move == 0)
3118 goto out;
3119
3120 pinned = 1;
3121
3122 /*
3123 * Start the load-balancing iterator:
3124 */
3125 p = iterator->start(iterator->arg);
3126next:
3127 if (!p || loops++ > sysctl_sched_nr_migrate)
3128 goto out;
3129 /*
3130 * To help distribute high priority tasks across CPUs we don't
3131 * skip a task if it will be the highest priority task (i.e. smallest
3132 * prio value) on its new queue regardless of its load weight
3133 */
3134 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3135 SCHED_LOAD_SCALE_FUZZ;
3136 if ((skip_for_load && p->prio >= *this_best_prio) ||
3137 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3138 p = iterator->next(iterator->arg);
3139 goto next;
3140 }
3141
3142 pull_task(busiest, p, this_rq, this_cpu);
3143 pulled++;
3144 rem_load_move -= p->se.load.weight;
3145
3146 /*
3147 * We only want to steal up to the prescribed amount of weighted load.
3148 */
3149 if (rem_load_move > 0) {
3150 if (p->prio < *this_best_prio)
3151 *this_best_prio = p->prio;
3152 p = iterator->next(iterator->arg);
3153 goto next;
3154 }
3155out:
3156 /*
3157 * Right now, this is one of only two places pull_task() is called,
3158 * so we can safely collect pull_task() stats here rather than
3159 * inside pull_task().
3160 */
3161 schedstat_add(sd, lb_gained[idle], pulled);
3162
3163 if (all_pinned)
3164 *all_pinned = pinned;
3165
3166 return max_load_move - rem_load_move;
3167}
3168
3169/*
3170 * move_tasks tries to move up to max_load_move weighted load from busiest to
3171 * this_rq, as part of a balancing operation within domain "sd".
3172 * Returns 1 if successful and 0 otherwise.
3173 *
3174 * Called with both runqueues locked.
3175 */
3176static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3177 unsigned long max_load_move,
3178 struct sched_domain *sd, enum cpu_idle_type idle,
3179 int *all_pinned)
3180{
3181 const struct sched_class *class = sched_class_highest;
3182 unsigned long total_load_moved = 0;
3183 int this_best_prio = this_rq->curr->prio;
3184
3185 do {
3186 total_load_moved +=
3187 class->load_balance(this_rq, this_cpu, busiest,
3188 max_load_move - total_load_moved,
3189 sd, idle, all_pinned, &this_best_prio);
3190 class = class->next;
3191 } while (class && max_load_move > total_load_moved);
3192
3193 return total_load_moved > 0;
3194}
3195
3196static int
3197iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3198 struct sched_domain *sd, enum cpu_idle_type idle,
3199 struct rq_iterator *iterator)
3200{
3201 struct task_struct *p = iterator->start(iterator->arg);
3202 int pinned = 0;
3203
3204 while (p) {
3205 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3206 pull_task(busiest, p, this_rq, this_cpu);
3207 /*
3208 * Right now, this is only the second place pull_task()
3209 * is called, so we can safely collect pull_task()
3210 * stats here rather than inside pull_task().
3211 */
3212 schedstat_inc(sd, lb_gained[idle]);
3213
3214 return 1;
3215 }
3216 p = iterator->next(iterator->arg);
3217 }
3218
3219 return 0;
3220}
3221
3222/*
3223 * move_one_task tries to move exactly one task from busiest to this_rq, as
3224 * part of active balancing operations within "domain".
3225 * Returns 1 if successful and 0 otherwise.
3226 *
3227 * Called with both runqueues locked.
3228 */
3229static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3230 struct sched_domain *sd, enum cpu_idle_type idle)
3231{
3232 const struct sched_class *class;
3233
3234 for (class = sched_class_highest; class; class = class->next)
3235 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3236 return 1;
3237
3238 return 0;
3239}
3240
3241/*
3242 * find_busiest_group finds and returns the busiest CPU group within the
3243 * domain. It calculates and returns the amount of weighted load which
3244 * should be moved to restore balance via the imbalance parameter.
3245 */
3246static struct sched_group *
3247find_busiest_group(struct sched_domain *sd, int this_cpu,
3248 unsigned long *imbalance, enum cpu_idle_type idle,
3249 int *sd_idle, const cpumask_t *cpus, int *balance)
3250{
3251 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3252 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3253 unsigned long max_pull;
3254 unsigned long busiest_load_per_task, busiest_nr_running;
3255 unsigned long this_load_per_task, this_nr_running;
3256 int load_idx, group_imb = 0;
3257#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3258 int power_savings_balance = 1;
3259 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3260 unsigned long min_nr_running = ULONG_MAX;
3261 struct sched_group *group_min = NULL, *group_leader = NULL;
3262#endif
3263
3264 max_load = this_load = total_load = total_pwr = 0;
3265 busiest_load_per_task = busiest_nr_running = 0;
3266 this_load_per_task = this_nr_running = 0;
3267 if (idle == CPU_NOT_IDLE)
3268 load_idx = sd->busy_idx;
3269 else if (idle == CPU_NEWLY_IDLE)
3270 load_idx = sd->newidle_idx;
3271 else
3272 load_idx = sd->idle_idx;
3273
3274 do {
3275 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3276 int local_group;
3277 int i;
3278 int __group_imb = 0;
3279 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3280 unsigned long sum_nr_running, sum_weighted_load;
3281
3282 local_group = cpu_isset(this_cpu, group->cpumask);
3283
3284 if (local_group)
3285 balance_cpu = first_cpu(group->cpumask);
3286
3287 /* Tally up the load of all CPUs in the group */
3288 sum_weighted_load = sum_nr_running = avg_load = 0;
3289 max_cpu_load = 0;
3290 min_cpu_load = ~0UL;
3291
3292 for_each_cpu_mask(i, group->cpumask) {
3293 struct rq *rq;
3294
3295 if (!cpu_isset(i, *cpus))
3296 continue;
3297
3298 rq = cpu_rq(i);
3299
3300 if (*sd_idle && rq->nr_running)
3301 *sd_idle = 0;
3302
3303 /* Bias balancing toward cpus of our domain */
3304 if (local_group) {
3305 if (idle_cpu(i) && !first_idle_cpu) {
3306 first_idle_cpu = 1;
3307 balance_cpu = i;
3308 }
3309
3310 load = target_load(i, load_idx);
3311 } else {
3312 load = source_load(i, load_idx);
3313 if (load > max_cpu_load)
3314 max_cpu_load = load;
3315 if (min_cpu_load > load)
3316 min_cpu_load = load;
3317 }
3318
3319 avg_load += load;
3320 sum_nr_running += rq->nr_running;
3321 sum_weighted_load += weighted_cpuload(i);
3322 }
3323
3324 /*
3325 * First idle cpu or the first cpu(busiest) in this sched group
3326 * is eligible for doing load balancing at this and above
3327 * domains. In the newly idle case, we will allow all the cpu's
3328 * to do the newly idle load balance.
3329 */
3330 if (idle != CPU_NEWLY_IDLE && local_group &&
3331 balance_cpu != this_cpu && balance) {
3332 *balance = 0;
3333 goto ret;
3334 }
3335
3336 total_load += avg_load;
3337 total_pwr += group->__cpu_power;
3338
3339 /* Adjust by relative CPU power of the group */
3340 avg_load = sg_div_cpu_power(group,
3341 avg_load * SCHED_LOAD_SCALE);
3342
3343 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3344 __group_imb = 1;
3345
3346 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3347
3348 if (local_group) {
3349 this_load = avg_load;
3350 this = group;
3351 this_nr_running = sum_nr_running;
3352 this_load_per_task = sum_weighted_load;
3353 } else if (avg_load > max_load &&
3354 (sum_nr_running > group_capacity || __group_imb)) {
3355 max_load = avg_load;
3356 busiest = group;
3357 busiest_nr_running = sum_nr_running;
3358 busiest_load_per_task = sum_weighted_load;
3359 group_imb = __group_imb;
3360 }
3361
3362#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3363 /*
3364 * Busy processors will not participate in power savings
3365 * balance.
3366 */
3367 if (idle == CPU_NOT_IDLE ||
3368 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3369 goto group_next;
3370
3371 /*
3372 * If the local group is idle or completely loaded
3373 * no need to do power savings balance at this domain
3374 */
3375 if (local_group && (this_nr_running >= group_capacity ||
3376 !this_nr_running))
3377 power_savings_balance = 0;
3378
3379 /*
3380 * If a group is already running at full capacity or idle,
3381 * don't include that group in power savings calculations
3382 */
3383 if (!power_savings_balance || sum_nr_running >= group_capacity
3384 || !sum_nr_running)
3385 goto group_next;
3386
3387 /*
3388 * Calculate the group which has the least non-idle load.
3389 * This is the group from where we need to pick up the load
3390 * for saving power
3391 */
3392 if ((sum_nr_running < min_nr_running) ||
3393 (sum_nr_running == min_nr_running &&
3394 first_cpu(group->cpumask) <
3395 first_cpu(group_min->cpumask))) {
3396 group_min = group;
3397 min_nr_running = sum_nr_running;
3398 min_load_per_task = sum_weighted_load /
3399 sum_nr_running;
3400 }
3401
3402 /*
3403 * Calculate the group which is almost near its
3404 * capacity but still has some space to pick up some load
3405 * from other group and save more power
3406 */
3407 if (sum_nr_running <= group_capacity - 1) {
3408 if (sum_nr_running > leader_nr_running ||
3409 (sum_nr_running == leader_nr_running &&
3410 first_cpu(group->cpumask) >
3411 first_cpu(group_leader->cpumask))) {
3412 group_leader = group;
3413 leader_nr_running = sum_nr_running;
3414 }
3415 }
3416group_next:
3417#endif
3418 group = group->next;
3419 } while (group != sd->groups);
3420
3421 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3422 goto out_balanced;
3423
3424 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3425
3426 if (this_load >= avg_load ||
3427 100*max_load <= sd->imbalance_pct*this_load)
3428 goto out_balanced;
3429
3430 busiest_load_per_task /= busiest_nr_running;
3431 if (group_imb)
3432 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3433
3434 /*
3435 * We're trying to get all the cpus to the average_load, so we don't
3436 * want to push ourselves above the average load, nor do we wish to
3437 * reduce the max loaded cpu below the average load, as either of these
3438 * actions would just result in more rebalancing later, and ping-pong
3439 * tasks around. Thus we look for the minimum possible imbalance.
3440 * Negative imbalances (*we* are more loaded than anyone else) will
3441 * be counted as no imbalance for these purposes -- we can't fix that
3442 * by pulling tasks to us. Be careful of negative numbers as they'll
3443 * appear as very large values with unsigned longs.
3444 */
3445 if (max_load <= busiest_load_per_task)
3446 goto out_balanced;
3447
3448 /*
3449 * In the presence of smp nice balancing, certain scenarios can have
3450 * max load less than avg load(as we skip the groups at or below
3451 * its cpu_power, while calculating max_load..)
3452 */
3453 if (max_load < avg_load) {
3454 *imbalance = 0;
3455 goto small_imbalance;
3456 }
3457
3458 /* Don't want to pull so many tasks that a group would go idle */
3459 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3460
3461 /* How much load to actually move to equalise the imbalance */
3462 *imbalance = min(max_pull * busiest->__cpu_power,
3463 (avg_load - this_load) * this->__cpu_power)
3464 / SCHED_LOAD_SCALE;
3465
3466 /*
3467 * if *imbalance is less than the average load per runnable task
3468 * there is no gaurantee that any tasks will be moved so we'll have
3469 * a think about bumping its value to force at least one task to be
3470 * moved
3471 */
3472 if (*imbalance < busiest_load_per_task) {
3473 unsigned long tmp, pwr_now, pwr_move;
3474 unsigned int imbn;
3475
3476small_imbalance:
3477 pwr_move = pwr_now = 0;
3478 imbn = 2;
3479 if (this_nr_running) {
3480 this_load_per_task /= this_nr_running;
3481 if (busiest_load_per_task > this_load_per_task)
3482 imbn = 1;
3483 } else
3484 this_load_per_task = SCHED_LOAD_SCALE;
3485
3486 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3487 busiest_load_per_task * imbn) {
3488 *imbalance = busiest_load_per_task;
3489 return busiest;
3490 }
3491
3492 /*
3493 * OK, we don't have enough imbalance to justify moving tasks,
3494 * however we may be able to increase total CPU power used by
3495 * moving them.
3496 */
3497
3498 pwr_now += busiest->__cpu_power *
3499 min(busiest_load_per_task, max_load);
3500 pwr_now += this->__cpu_power *
3501 min(this_load_per_task, this_load);
3502 pwr_now /= SCHED_LOAD_SCALE;
3503
3504 /* Amount of load we'd subtract */
3505 tmp = sg_div_cpu_power(busiest,
3506 busiest_load_per_task * SCHED_LOAD_SCALE);
3507 if (max_load > tmp)
3508 pwr_move += busiest->__cpu_power *
3509 min(busiest_load_per_task, max_load - tmp);
3510
3511 /* Amount of load we'd add */
3512 if (max_load * busiest->__cpu_power <
3513 busiest_load_per_task * SCHED_LOAD_SCALE)
3514 tmp = sg_div_cpu_power(this,
3515 max_load * busiest->__cpu_power);
3516 else
3517 tmp = sg_div_cpu_power(this,
3518 busiest_load_per_task * SCHED_LOAD_SCALE);
3519 pwr_move += this->__cpu_power *
3520 min(this_load_per_task, this_load + tmp);
3521 pwr_move /= SCHED_LOAD_SCALE;
3522
3523 /* Move if we gain throughput */
3524 if (pwr_move > pwr_now)
3525 *imbalance = busiest_load_per_task;
3526 }
3527
3528 return busiest;
3529
3530out_balanced:
3531#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3532 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3533 goto ret;
3534
3535 if (this == group_leader && group_leader != group_min) {
3536 *imbalance = min_load_per_task;
3537 return group_min;
3538 }
3539#endif
3540ret:
3541 *imbalance = 0;
3542 return NULL;
3543}
3544
3545/*
3546 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3547 */
3548static struct rq *
3549find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3550 unsigned long imbalance, const cpumask_t *cpus)
3551{
3552 struct rq *busiest = NULL, *rq;
3553 unsigned long max_load = 0;
3554 int i;
3555
3556 for_each_cpu_mask(i, group->cpumask) {
3557 unsigned long wl;
3558
3559 if (!cpu_isset(i, *cpus))
3560 continue;
3561
3562 rq = cpu_rq(i);
3563 wl = weighted_cpuload(i);
3564
3565 if (rq->nr_running == 1 && wl > imbalance)
3566 continue;
3567
3568 if (wl > max_load) {
3569 max_load = wl;
3570 busiest = rq;
3571 }
3572 }
3573
3574 return busiest;
3575}
3576
3577/*
3578 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3579 * so long as it is large enough.
3580 */
3581#define MAX_PINNED_INTERVAL 512
3582
3583/*
3584 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3585 * tasks if there is an imbalance.
3586 */
3587static int load_balance(int this_cpu, struct rq *this_rq,
3588 struct sched_domain *sd, enum cpu_idle_type idle,
3589 int *balance, cpumask_t *cpus)
3590{
3591 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3592 struct sched_group *group;
3593 unsigned long imbalance;
3594 struct rq *busiest;
3595 unsigned long flags;
3596 int unlock_aggregate;
3597
3598 cpus_setall(*cpus);
3599
3600 unlock_aggregate = get_aggregate(sd);
3601
3602 /*
3603 * When power savings policy is enabled for the parent domain, idle
3604 * sibling can pick up load irrespective of busy siblings. In this case,
3605 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3606 * portraying it as CPU_NOT_IDLE.
3607 */
3608 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3609 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3610 sd_idle = 1;
3611
3612 schedstat_inc(sd, lb_count[idle]);
3613
3614redo:
3615 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3616 cpus, balance);
3617
3618 if (*balance == 0)
3619 goto out_balanced;
3620
3621 if (!group) {
3622 schedstat_inc(sd, lb_nobusyg[idle]);
3623 goto out_balanced;
3624 }
3625
3626 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3627 if (!busiest) {
3628 schedstat_inc(sd, lb_nobusyq[idle]);
3629 goto out_balanced;
3630 }
3631
3632 BUG_ON(busiest == this_rq);
3633
3634 schedstat_add(sd, lb_imbalance[idle], imbalance);
3635
3636 ld_moved = 0;
3637 if (busiest->nr_running > 1) {
3638 /*
3639 * Attempt to move tasks. If find_busiest_group has found
3640 * an imbalance but busiest->nr_running <= 1, the group is
3641 * still unbalanced. ld_moved simply stays zero, so it is
3642 * correctly treated as an imbalance.
3643 */
3644 local_irq_save(flags);
3645 double_rq_lock(this_rq, busiest);
3646 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3647 imbalance, sd, idle, &all_pinned);
3648 double_rq_unlock(this_rq, busiest);
3649 local_irq_restore(flags);
3650
3651 /*
3652 * some other cpu did the load balance for us.
3653 */
3654 if (ld_moved && this_cpu != smp_processor_id())
3655 resched_cpu(this_cpu);
3656
3657 /* All tasks on this runqueue were pinned by CPU affinity */
3658 if (unlikely(all_pinned)) {
3659 cpu_clear(cpu_of(busiest), *cpus);
3660 if (!cpus_empty(*cpus))
3661 goto redo;
3662 goto out_balanced;
3663 }
3664 }
3665
3666 if (!ld_moved) {
3667 schedstat_inc(sd, lb_failed[idle]);
3668 sd->nr_balance_failed++;
3669
3670 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3671
3672 spin_lock_irqsave(&busiest->lock, flags);
3673
3674 /* don't kick the migration_thread, if the curr
3675 * task on busiest cpu can't be moved to this_cpu
3676 */
3677 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3678 spin_unlock_irqrestore(&busiest->lock, flags);
3679 all_pinned = 1;
3680 goto out_one_pinned;
3681 }
3682
3683 if (!busiest->active_balance) {
3684 busiest->active_balance = 1;
3685 busiest->push_cpu = this_cpu;
3686 active_balance = 1;
3687 }
3688 spin_unlock_irqrestore(&busiest->lock, flags);
3689 if (active_balance)
3690 wake_up_process(busiest->migration_thread);
3691
3692 /*
3693 * We've kicked active balancing, reset the failure
3694 * counter.
3695 */
3696 sd->nr_balance_failed = sd->cache_nice_tries+1;
3697 }
3698 } else
3699 sd->nr_balance_failed = 0;
3700
3701 if (likely(!active_balance)) {
3702 /* We were unbalanced, so reset the balancing interval */
3703 sd->balance_interval = sd->min_interval;
3704 } else {
3705 /*
3706 * If we've begun active balancing, start to back off. This
3707 * case may not be covered by the all_pinned logic if there
3708 * is only 1 task on the busy runqueue (because we don't call
3709 * move_tasks).
3710 */
3711 if (sd->balance_interval < sd->max_interval)
3712 sd->balance_interval *= 2;
3713 }
3714
3715 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3716 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3717 ld_moved = -1;
3718
3719 goto out;
3720
3721out_balanced:
3722 schedstat_inc(sd, lb_balanced[idle]);
3723
3724 sd->nr_balance_failed = 0;
3725
3726out_one_pinned:
3727 /* tune up the balancing interval */
3728 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3729 (sd->balance_interval < sd->max_interval))
3730 sd->balance_interval *= 2;
3731
3732 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3733 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3734 ld_moved = -1;
3735 else
3736 ld_moved = 0;
3737out:
3738 if (unlock_aggregate)
3739 put_aggregate(sd);
3740 return ld_moved;
3741}
3742
3743/*
3744 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3745 * tasks if there is an imbalance.
3746 *
3747 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3748 * this_rq is locked.
3749 */
3750static int
3751load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3752 cpumask_t *cpus)
3753{
3754 struct sched_group *group;
3755 struct rq *busiest = NULL;
3756 unsigned long imbalance;
3757 int ld_moved = 0;
3758 int sd_idle = 0;
3759 int all_pinned = 0;
3760
3761 cpus_setall(*cpus);
3762
3763 /*
3764 * When power savings policy is enabled for the parent domain, idle
3765 * sibling can pick up load irrespective of busy siblings. In this case,
3766 * let the state of idle sibling percolate up as IDLE, instead of
3767 * portraying it as CPU_NOT_IDLE.
3768 */
3769 if (sd->flags & SD_SHARE_CPUPOWER &&
3770 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3771 sd_idle = 1;
3772
3773 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3774redo:
3775 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3776 &sd_idle, cpus, NULL);
3777 if (!group) {
3778 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3779 goto out_balanced;
3780 }
3781
3782 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3783 if (!busiest) {
3784 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3785 goto out_balanced;
3786 }
3787
3788 BUG_ON(busiest == this_rq);
3789
3790 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3791
3792 ld_moved = 0;
3793 if (busiest->nr_running > 1) {
3794 /* Attempt to move tasks */
3795 double_lock_balance(this_rq, busiest);
3796 /* this_rq->clock is already updated */
3797 update_rq_clock(busiest);
3798 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3799 imbalance, sd, CPU_NEWLY_IDLE,
3800 &all_pinned);
3801 spin_unlock(&busiest->lock);
3802
3803 if (unlikely(all_pinned)) {
3804 cpu_clear(cpu_of(busiest), *cpus);
3805 if (!cpus_empty(*cpus))
3806 goto redo;
3807 }
3808 }
3809
3810 if (!ld_moved) {
3811 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3812 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3813 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3814 return -1;
3815 } else
3816 sd->nr_balance_failed = 0;
3817
3818 return ld_moved;
3819
3820out_balanced:
3821 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3822 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3823 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3824 return -1;
3825 sd->nr_balance_failed = 0;
3826
3827 return 0;
3828}
3829
3830/*
3831 * idle_balance is called by schedule() if this_cpu is about to become
3832 * idle. Attempts to pull tasks from other CPUs.
3833 */
3834static void idle_balance(int this_cpu, struct rq *this_rq)
3835{
3836 struct sched_domain *sd;
3837 int pulled_task = -1;
3838 unsigned long next_balance = jiffies + HZ;
3839 cpumask_t tmpmask;
3840
3841 for_each_domain(this_cpu, sd) {
3842 unsigned long interval;
3843
3844 if (!(sd->flags & SD_LOAD_BALANCE))
3845 continue;
3846
3847 if (sd->flags & SD_BALANCE_NEWIDLE)
3848 /* If we've pulled tasks over stop searching: */
3849 pulled_task = load_balance_newidle(this_cpu, this_rq,
3850 sd, &tmpmask);
3851
3852 interval = msecs_to_jiffies(sd->balance_interval);
3853 if (time_after(next_balance, sd->last_balance + interval))
3854 next_balance = sd->last_balance + interval;
3855 if (pulled_task)
3856 break;
3857 }
3858 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3859 /*
3860 * We are going idle. next_balance may be set based on
3861 * a busy processor. So reset next_balance.
3862 */
3863 this_rq->next_balance = next_balance;
3864 }
3865}
3866
3867/*
3868 * active_load_balance is run by migration threads. It pushes running tasks
3869 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3870 * running on each physical CPU where possible, and avoids physical /
3871 * logical imbalances.
3872 *
3873 * Called with busiest_rq locked.
3874 */
3875static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3876{
3877 int target_cpu = busiest_rq->push_cpu;
3878 struct sched_domain *sd;
3879 struct rq *target_rq;
3880
3881 /* Is there any task to move? */
3882 if (busiest_rq->nr_running <= 1)
3883 return;
3884
3885 target_rq = cpu_rq(target_cpu);
3886
3887 /*
3888 * This condition is "impossible", if it occurs
3889 * we need to fix it. Originally reported by
3890 * Bjorn Helgaas on a 128-cpu setup.
3891 */
3892 BUG_ON(busiest_rq == target_rq);
3893
3894 /* move a task from busiest_rq to target_rq */
3895 double_lock_balance(busiest_rq, target_rq);
3896 update_rq_clock(busiest_rq);
3897 update_rq_clock(target_rq);
3898
3899 /* Search for an sd spanning us and the target CPU. */
3900 for_each_domain(target_cpu, sd) {
3901 if ((sd->flags & SD_LOAD_BALANCE) &&
3902 cpu_isset(busiest_cpu, sd->span))
3903 break;
3904 }
3905
3906 if (likely(sd)) {
3907 schedstat_inc(sd, alb_count);
3908
3909 if (move_one_task(target_rq, target_cpu, busiest_rq,
3910 sd, CPU_IDLE))
3911 schedstat_inc(sd, alb_pushed);
3912 else
3913 schedstat_inc(sd, alb_failed);
3914 }
3915 spin_unlock(&target_rq->lock);
3916}
3917
3918#ifdef CONFIG_NO_HZ
3919static struct {
3920 atomic_t load_balancer;
3921 cpumask_t cpu_mask;
3922} nohz ____cacheline_aligned = {
3923 .load_balancer = ATOMIC_INIT(-1),
3924 .cpu_mask = CPU_MASK_NONE,
3925};
3926
3927/*
3928 * This routine will try to nominate the ilb (idle load balancing)
3929 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3930 * load balancing on behalf of all those cpus. If all the cpus in the system
3931 * go into this tickless mode, then there will be no ilb owner (as there is
3932 * no need for one) and all the cpus will sleep till the next wakeup event
3933 * arrives...
3934 *
3935 * For the ilb owner, tick is not stopped. And this tick will be used
3936 * for idle load balancing. ilb owner will still be part of
3937 * nohz.cpu_mask..
3938 *
3939 * While stopping the tick, this cpu will become the ilb owner if there
3940 * is no other owner. And will be the owner till that cpu becomes busy
3941 * or if all cpus in the system stop their ticks at which point
3942 * there is no need for ilb owner.
3943 *
3944 * When the ilb owner becomes busy, it nominates another owner, during the
3945 * next busy scheduler_tick()
3946 */
3947int select_nohz_load_balancer(int stop_tick)
3948{
3949 int cpu = smp_processor_id();
3950
3951 if (stop_tick) {
3952 cpu_set(cpu, nohz.cpu_mask);
3953 cpu_rq(cpu)->in_nohz_recently = 1;
3954
3955 /*
3956 * If we are going offline and still the leader, give up!
3957 */
3958 if (cpu_is_offline(cpu) &&
3959 atomic_read(&nohz.load_balancer) == cpu) {
3960 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3961 BUG();
3962 return 0;
3963 }
3964
3965 /* time for ilb owner also to sleep */
3966 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3967 if (atomic_read(&nohz.load_balancer) == cpu)
3968 atomic_set(&nohz.load_balancer, -1);
3969 return 0;
3970 }
3971
3972 if (atomic_read(&nohz.load_balancer) == -1) {
3973 /* make me the ilb owner */
3974 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3975 return 1;
3976 } else if (atomic_read(&nohz.load_balancer) == cpu)
3977 return 1;
3978 } else {
3979 if (!cpu_isset(cpu, nohz.cpu_mask))
3980 return 0;
3981
3982 cpu_clear(cpu, nohz.cpu_mask);
3983
3984 if (atomic_read(&nohz.load_balancer) == cpu)
3985 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3986 BUG();
3987 }
3988 return 0;
3989}
3990#endif
3991
3992static DEFINE_SPINLOCK(balancing);
3993
3994/*
3995 * It checks each scheduling domain to see if it is due to be balanced,
3996 * and initiates a balancing operation if so.
3997 *
3998 * Balancing parameters are set up in arch_init_sched_domains.
3999 */
4000static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4001{
4002 int balance = 1;
4003 struct rq *rq = cpu_rq(cpu);
4004 unsigned long interval;
4005 struct sched_domain *sd;
4006 /* Earliest time when we have to do rebalance again */
4007 unsigned long next_balance = jiffies + 60*HZ;
4008 int update_next_balance = 0;
4009 cpumask_t tmp;
4010
4011 for_each_domain(cpu, sd) {
4012 if (!(sd->flags & SD_LOAD_BALANCE))
4013 continue;
4014
4015 interval = sd->balance_interval;
4016 if (idle != CPU_IDLE)
4017 interval *= sd->busy_factor;
4018
4019 /* scale ms to jiffies */
4020 interval = msecs_to_jiffies(interval);
4021 if (unlikely(!interval))
4022 interval = 1;
4023 if (interval > HZ*NR_CPUS/10)
4024 interval = HZ*NR_CPUS/10;
4025
4026
4027 if (sd->flags & SD_SERIALIZE) {
4028 if (!spin_trylock(&balancing))
4029 goto out;
4030 }
4031
4032 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4033 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4034 /*
4035 * We've pulled tasks over so either we're no
4036 * longer idle, or one of our SMT siblings is
4037 * not idle.
4038 */
4039 idle = CPU_NOT_IDLE;
4040 }
4041 sd->last_balance = jiffies;
4042 }
4043 if (sd->flags & SD_SERIALIZE)
4044 spin_unlock(&balancing);
4045out:
4046 if (time_after(next_balance, sd->last_balance + interval)) {
4047 next_balance = sd->last_balance + interval;
4048 update_next_balance = 1;
4049 }
4050
4051 /*
4052 * Stop the load balance at this level. There is another
4053 * CPU in our sched group which is doing load balancing more
4054 * actively.
4055 */
4056 if (!balance)
4057 break;
4058 }
4059
4060 /*
4061 * next_balance will be updated only when there is a need.
4062 * When the cpu is attached to null domain for ex, it will not be
4063 * updated.
4064 */
4065 if (likely(update_next_balance))
4066 rq->next_balance = next_balance;
4067}
4068
4069/*
4070 * run_rebalance_domains is triggered when needed from the scheduler tick.
4071 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4072 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4073 */
4074static void run_rebalance_domains(struct softirq_action *h)
4075{
4076 int this_cpu = smp_processor_id();
4077 struct rq *this_rq = cpu_rq(this_cpu);
4078 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4079 CPU_IDLE : CPU_NOT_IDLE;
4080
4081 rebalance_domains(this_cpu, idle);
4082
4083#ifdef CONFIG_NO_HZ
4084 /*
4085 * If this cpu is the owner for idle load balancing, then do the
4086 * balancing on behalf of the other idle cpus whose ticks are
4087 * stopped.
4088 */
4089 if (this_rq->idle_at_tick &&
4090 atomic_read(&nohz.load_balancer) == this_cpu) {
4091 cpumask_t cpus = nohz.cpu_mask;
4092 struct rq *rq;
4093 int balance_cpu;
4094
4095 cpu_clear(this_cpu, cpus);
4096 for_each_cpu_mask(balance_cpu, cpus) {
4097 /*
4098 * If this cpu gets work to do, stop the load balancing
4099 * work being done for other cpus. Next load
4100 * balancing owner will pick it up.
4101 */
4102 if (need_resched())
4103 break;
4104
4105 rebalance_domains(balance_cpu, CPU_IDLE);
4106
4107 rq = cpu_rq(balance_cpu);
4108 if (time_after(this_rq->next_balance, rq->next_balance))
4109 this_rq->next_balance = rq->next_balance;
4110 }
4111 }
4112#endif
4113}
4114
4115/*
4116 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4117 *
4118 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4119 * idle load balancing owner or decide to stop the periodic load balancing,
4120 * if the whole system is idle.
4121 */
4122static inline void trigger_load_balance(struct rq *rq, int cpu)
4123{
4124#ifdef CONFIG_NO_HZ
4125 /*
4126 * If we were in the nohz mode recently and busy at the current
4127 * scheduler tick, then check if we need to nominate new idle
4128 * load balancer.
4129 */
4130 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4131 rq->in_nohz_recently = 0;
4132
4133 if (atomic_read(&nohz.load_balancer) == cpu) {
4134 cpu_clear(cpu, nohz.cpu_mask);
4135 atomic_set(&nohz.load_balancer, -1);
4136 }
4137
4138 if (atomic_read(&nohz.load_balancer) == -1) {
4139 /*
4140 * simple selection for now: Nominate the
4141 * first cpu in the nohz list to be the next
4142 * ilb owner.
4143 *
4144 * TBD: Traverse the sched domains and nominate
4145 * the nearest cpu in the nohz.cpu_mask.
4146 */
4147 int ilb = first_cpu(nohz.cpu_mask);
4148
4149 if (ilb < nr_cpu_ids)
4150 resched_cpu(ilb);
4151 }
4152 }
4153
4154 /*
4155 * If this cpu is idle and doing idle load balancing for all the
4156 * cpus with ticks stopped, is it time for that to stop?
4157 */
4158 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4159 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4160 resched_cpu(cpu);
4161 return;
4162 }
4163
4164 /*
4165 * If this cpu is idle and the idle load balancing is done by
4166 * someone else, then no need raise the SCHED_SOFTIRQ
4167 */
4168 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4169 cpu_isset(cpu, nohz.cpu_mask))
4170 return;
4171#endif
4172 if (time_after_eq(jiffies, rq->next_balance))
4173 raise_softirq(SCHED_SOFTIRQ);
4174}
4175
4176#else /* CONFIG_SMP */
4177
4178/*
4179 * on UP we do not need to balance between CPUs:
4180 */
4181static inline void idle_balance(int cpu, struct rq *rq)
4182{
4183}
4184
4185#endif
4186
4187DEFINE_PER_CPU(struct kernel_stat, kstat);
4188
4189EXPORT_PER_CPU_SYMBOL(kstat);
4190
4191/*
4192 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4193 * that have not yet been banked in case the task is currently running.
4194 */
4195unsigned long long task_sched_runtime(struct task_struct *p)
4196{
4197 unsigned long flags;
4198 u64 ns, delta_exec;
4199 struct rq *rq;
4200
4201 rq = task_rq_lock(p, &flags);
4202 ns = p->se.sum_exec_runtime;
4203 if (task_current(rq, p)) {
4204 update_rq_clock(rq);
4205 delta_exec = rq->clock - p->se.exec_start;
4206 if ((s64)delta_exec > 0)
4207 ns += delta_exec;
4208 }
4209 task_rq_unlock(rq, &flags);
4210
4211 return ns;
4212}
4213
4214/*
4215 * Account user cpu time to a process.
4216 * @p: the process that the cpu time gets accounted to
4217 * @cputime: the cpu time spent in user space since the last update
4218 */
4219void account_user_time(struct task_struct *p, cputime_t cputime)
4220{
4221 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4222 cputime64_t tmp;
4223
4224 p->utime = cputime_add(p->utime, cputime);
4225
4226 /* Add user time to cpustat. */
4227 tmp = cputime_to_cputime64(cputime);
4228 if (TASK_NICE(p) > 0)
4229 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4230 else
4231 cpustat->user = cputime64_add(cpustat->user, tmp);
4232}
4233
4234/*
4235 * Account guest cpu time to a process.
4236 * @p: the process that the cpu time gets accounted to
4237 * @cputime: the cpu time spent in virtual machine since the last update
4238 */
4239static void account_guest_time(struct task_struct *p, cputime_t cputime)
4240{
4241 cputime64_t tmp;
4242 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4243
4244 tmp = cputime_to_cputime64(cputime);
4245
4246 p->utime = cputime_add(p->utime, cputime);
4247 p->gtime = cputime_add(p->gtime, cputime);
4248
4249 cpustat->user = cputime64_add(cpustat->user, tmp);
4250 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4251}
4252
4253/*
4254 * Account scaled user cpu time to a process.
4255 * @p: the process that the cpu time gets accounted to
4256 * @cputime: the cpu time spent in user space since the last update
4257 */
4258void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4259{
4260 p->utimescaled = cputime_add(p->utimescaled, cputime);
4261}
4262
4263/*
4264 * Account system cpu time to a process.
4265 * @p: the process that the cpu time gets accounted to
4266 * @hardirq_offset: the offset to subtract from hardirq_count()
4267 * @cputime: the cpu time spent in kernel space since the last update
4268 */
4269void account_system_time(struct task_struct *p, int hardirq_offset,
4270 cputime_t cputime)
4271{
4272 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4273 struct rq *rq = this_rq();
4274 cputime64_t tmp;
4275
4276 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
4277 return account_guest_time(p, cputime);
4278
4279 p->stime = cputime_add(p->stime, cputime);
4280
4281 /* Add system time to cpustat. */
4282 tmp = cputime_to_cputime64(cputime);
4283 if (hardirq_count() - hardirq_offset)
4284 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4285 else if (softirq_count())
4286 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4287 else if (p != rq->idle)
4288 cpustat->system = cputime64_add(cpustat->system, tmp);
4289 else if (atomic_read(&rq->nr_iowait) > 0)
4290 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4291 else
4292 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4293 /* Account for system time used */
4294 acct_update_integrals(p);
4295}
4296
4297/*
4298 * Account scaled system cpu time to a process.
4299 * @p: the process that the cpu time gets accounted to
4300 * @hardirq_offset: the offset to subtract from hardirq_count()
4301 * @cputime: the cpu time spent in kernel space since the last update
4302 */
4303void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4304{
4305 p->stimescaled = cputime_add(p->stimescaled, cputime);
4306}
4307
4308/*
4309 * Account for involuntary wait time.
4310 * @p: the process from which the cpu time has been stolen
4311 * @steal: the cpu time spent in involuntary wait
4312 */
4313void account_steal_time(struct task_struct *p, cputime_t steal)
4314{
4315 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4316 cputime64_t tmp = cputime_to_cputime64(steal);
4317 struct rq *rq = this_rq();
4318
4319 if (p == rq->idle) {
4320 p->stime = cputime_add(p->stime, steal);
4321 if (atomic_read(&rq->nr_iowait) > 0)
4322 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4323 else
4324 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4325 } else
4326 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4327}
4328
4329/*
4330 * This function gets called by the timer code, with HZ frequency.
4331 * We call it with interrupts disabled.
4332 *
4333 * It also gets called by the fork code, when changing the parent's
4334 * timeslices.
4335 */
4336void scheduler_tick(void)
4337{
4338 int cpu = smp_processor_id();
4339 struct rq *rq = cpu_rq(cpu);
4340 struct task_struct *curr = rq->curr;
4341 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4342
4343 spin_lock(&rq->lock);
4344 __update_rq_clock(rq);
4345 /*
4346 * Let rq->clock advance by at least TICK_NSEC:
4347 */
4348 if (unlikely(rq->clock < next_tick)) {
4349 rq->clock = next_tick;
4350 rq->clock_underflows++;
4351 }
4352 rq->tick_timestamp = rq->clock;
4353 update_last_tick_seen(rq);
4354 update_cpu_load(rq);
4355 curr->sched_class->task_tick(rq, curr, 0);
4356 spin_unlock(&rq->lock);
4357
4358#ifdef CONFIG_SMP
4359 rq->idle_at_tick = idle_cpu(cpu);
4360 trigger_load_balance(rq, cpu);
4361#endif
4362}
4363
4364#if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4365
4366void __kprobes add_preempt_count(int val)
4367{
4368 /*
4369 * Underflow?
4370 */
4371 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4372 return;
4373 preempt_count() += val;
4374 /*
4375 * Spinlock count overflowing soon?
4376 */
4377 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4378 PREEMPT_MASK - 10);
4379}
4380EXPORT_SYMBOL(add_preempt_count);
4381
4382void __kprobes sub_preempt_count(int val)
4383{
4384 /*
4385 * Underflow?
4386 */
4387 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4388 return;
4389 /*
4390 * Is the spinlock portion underflowing?
4391 */
4392 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4393 !(preempt_count() & PREEMPT_MASK)))
4394 return;
4395
4396 preempt_count() -= val;
4397}
4398EXPORT_SYMBOL(sub_preempt_count);
4399
4400#endif
4401
4402/*
4403 * Print scheduling while atomic bug:
4404 */
4405static noinline void __schedule_bug(struct task_struct *prev)
4406{
4407 struct pt_regs *regs = get_irq_regs();
4408
4409 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4410 prev->comm, prev->pid, preempt_count());
4411
4412 debug_show_held_locks(prev);
4413 if (irqs_disabled())
4414 print_irqtrace_events(prev);
4415
4416 if (regs)
4417 show_regs(regs);
4418 else
4419 dump_stack();
4420}
4421
4422/*
4423 * Various schedule()-time debugging checks and statistics:
4424 */
4425static inline void schedule_debug(struct task_struct *prev)
4426{
4427 /*
4428 * Test if we are atomic. Since do_exit() needs to call into
4429 * schedule() atomically, we ignore that path for now.
4430 * Otherwise, whine if we are scheduling when we should not be.
4431 */
4432 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4433 __schedule_bug(prev);
4434
4435 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4436
4437 schedstat_inc(this_rq(), sched_count);
4438#ifdef CONFIG_SCHEDSTATS
4439 if (unlikely(prev->lock_depth >= 0)) {
4440 schedstat_inc(this_rq(), bkl_count);
4441 schedstat_inc(prev, sched_info.bkl_count);
4442 }
4443#endif
4444}
4445
4446/*
4447 * Pick up the highest-prio task:
4448 */
4449static inline struct task_struct *
4450pick_next_task(struct rq *rq, struct task_struct *prev)
4451{
4452 const struct sched_class *class;
4453 struct task_struct *p;
4454
4455 /*
4456 * Optimization: we know that if all tasks are in
4457 * the fair class we can call that function directly:
4458 */
4459 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4460 p = fair_sched_class.pick_next_task(rq);
4461 if (likely(p))
4462 return p;
4463 }
4464
4465 class = sched_class_highest;
4466 for ( ; ; ) {
4467 p = class->pick_next_task(rq);
4468 if (p)
4469 return p;
4470 /*
4471 * Will never be NULL as the idle class always
4472 * returns a non-NULL p:
4473 */
4474 class = class->next;
4475 }
4476}
4477
4478/*
4479 * schedule() is the main scheduler function.
4480 */
4481asmlinkage void __sched schedule(void)
4482{
4483 struct task_struct *prev, *next;
4484 unsigned long *switch_count;
4485 struct rq *rq;
4486 int cpu;
4487
4488need_resched:
4489 preempt_disable();
4490 cpu = smp_processor_id();
4491 rq = cpu_rq(cpu);
4492 rcu_qsctr_inc(cpu);
4493 prev = rq->curr;
4494 switch_count = &prev->nivcsw;
4495
4496 release_kernel_lock(prev);
4497need_resched_nonpreemptible:
4498
4499 schedule_debug(prev);
4500
4501 hrtick_clear(rq);
4502
4503 /*
4504 * Do the rq-clock update outside the rq lock:
4505 */
4506 local_irq_disable();
4507 __update_rq_clock(rq);
4508 spin_lock(&rq->lock);
4509 clear_tsk_need_resched(prev);
4510
4511 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4512 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4513 signal_pending(prev))) {
4514 prev->state = TASK_RUNNING;
4515 } else {
4516 deactivate_task(rq, prev, 1);
4517 }
4518 switch_count = &prev->nvcsw;
4519 }
4520
4521#ifdef CONFIG_SMP
4522 if (prev->sched_class->pre_schedule)
4523 prev->sched_class->pre_schedule(rq, prev);
4524#endif
4525
4526 if (unlikely(!rq->nr_running))
4527 idle_balance(cpu, rq);
4528
4529 prev->sched_class->put_prev_task(rq, prev);
4530 next = pick_next_task(rq, prev);
4531
4532 sched_info_switch(prev, next);
4533
4534 if (likely(prev != next)) {
4535 rq->nr_switches++;
4536 rq->curr = next;
4537 ++*switch_count;
4538
4539 context_switch(rq, prev, next); /* unlocks the rq */
4540 /*
4541 * the context switch might have flipped the stack from under
4542 * us, hence refresh the local variables.
4543 */
4544 cpu = smp_processor_id();
4545 rq = cpu_rq(cpu);
4546 } else
4547 spin_unlock_irq(&rq->lock);
4548
4549 hrtick_set(rq);
4550
4551 if (unlikely(reacquire_kernel_lock(current) < 0))
4552 goto need_resched_nonpreemptible;
4553
4554 preempt_enable_no_resched();
4555 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4556 goto need_resched;
4557}
4558EXPORT_SYMBOL(schedule);
4559
4560#ifdef CONFIG_PREEMPT
4561/*
4562 * this is the entry point to schedule() from in-kernel preemption
4563 * off of preempt_enable. Kernel preemptions off return from interrupt
4564 * occur there and call schedule directly.
4565 */
4566asmlinkage void __sched preempt_schedule(void)
4567{
4568 struct thread_info *ti = current_thread_info();
4569 struct task_struct *task = current;
4570 int saved_lock_depth;
4571
4572 /*
4573 * If there is a non-zero preempt_count or interrupts are disabled,
4574 * we do not want to preempt the current task. Just return..
4575 */
4576 if (likely(ti->preempt_count || irqs_disabled()))
4577 return;
4578
4579 do {
4580 add_preempt_count(PREEMPT_ACTIVE);
4581
4582 /*
4583 * We keep the big kernel semaphore locked, but we
4584 * clear ->lock_depth so that schedule() doesnt
4585 * auto-release the semaphore:
4586 */
4587 saved_lock_depth = task->lock_depth;
4588 task->lock_depth = -1;
4589 schedule();
4590 task->lock_depth = saved_lock_depth;
4591 sub_preempt_count(PREEMPT_ACTIVE);
4592
4593 /*
4594 * Check again in case we missed a preemption opportunity
4595 * between schedule and now.
4596 */
4597 barrier();
4598 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4599}
4600EXPORT_SYMBOL(preempt_schedule);
4601
4602/*
4603 * this is the entry point to schedule() from kernel preemption
4604 * off of irq context.
4605 * Note, that this is called and return with irqs disabled. This will
4606 * protect us against recursive calling from irq.
4607 */
4608asmlinkage void __sched preempt_schedule_irq(void)
4609{
4610 struct thread_info *ti = current_thread_info();
4611 struct task_struct *task = current;
4612 int saved_lock_depth;
4613
4614 /* Catch callers which need to be fixed */
4615 BUG_ON(ti->preempt_count || !irqs_disabled());
4616
4617 do {
4618 add_preempt_count(PREEMPT_ACTIVE);
4619
4620 /*
4621 * We keep the big kernel semaphore locked, but we
4622 * clear ->lock_depth so that schedule() doesnt
4623 * auto-release the semaphore:
4624 */
4625 saved_lock_depth = task->lock_depth;
4626 task->lock_depth = -1;
4627 local_irq_enable();
4628 schedule();
4629 local_irq_disable();
4630 task->lock_depth = saved_lock_depth;
4631 sub_preempt_count(PREEMPT_ACTIVE);
4632
4633 /*
4634 * Check again in case we missed a preemption opportunity
4635 * between schedule and now.
4636 */
4637 barrier();
4638 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4639}
4640
4641#endif /* CONFIG_PREEMPT */
4642
4643int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4644 void *key)
4645{
4646 return try_to_wake_up(curr->private, mode, sync);
4647}
4648EXPORT_SYMBOL(default_wake_function);
4649
4650/*
4651 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4652 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4653 * number) then we wake all the non-exclusive tasks and one exclusive task.
4654 *
4655 * There are circumstances in which we can try to wake a task which has already
4656 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4657 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4658 */
4659static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4660 int nr_exclusive, int sync, void *key)
4661{
4662 wait_queue_t *curr, *next;
4663
4664 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4665 unsigned flags = curr->flags;
4666
4667 if (curr->func(curr, mode, sync, key) &&
4668 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4669 break;
4670 }
4671}
4672
4673/**
4674 * __wake_up - wake up threads blocked on a waitqueue.
4675 * @q: the waitqueue
4676 * @mode: which threads
4677 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4678 * @key: is directly passed to the wakeup function
4679 */
4680void __wake_up(wait_queue_head_t *q, unsigned int mode,
4681 int nr_exclusive, void *key)
4682{
4683 unsigned long flags;
4684
4685 spin_lock_irqsave(&q->lock, flags);
4686 __wake_up_common(q, mode, nr_exclusive, 0, key);
4687 spin_unlock_irqrestore(&q->lock, flags);
4688}
4689EXPORT_SYMBOL(__wake_up);
4690
4691/*
4692 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4693 */
4694void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4695{
4696 __wake_up_common(q, mode, 1, 0, NULL);
4697}
4698
4699/**
4700 * __wake_up_sync - wake up threads blocked on a waitqueue.
4701 * @q: the waitqueue
4702 * @mode: which threads
4703 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4704 *
4705 * The sync wakeup differs that the waker knows that it will schedule
4706 * away soon, so while the target thread will be woken up, it will not
4707 * be migrated to another CPU - ie. the two threads are 'synchronized'
4708 * with each other. This can prevent needless bouncing between CPUs.
4709 *
4710 * On UP it can prevent extra preemption.
4711 */
4712void
4713__wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4714{
4715 unsigned long flags;
4716 int sync = 1;
4717
4718 if (unlikely(!q))
4719 return;
4720
4721 if (unlikely(!nr_exclusive))
4722 sync = 0;
4723
4724 spin_lock_irqsave(&q->lock, flags);
4725 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4726 spin_unlock_irqrestore(&q->lock, flags);
4727}
4728EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4729
4730void complete(struct completion *x)
4731{
4732 unsigned long flags;
4733
4734 spin_lock_irqsave(&x->wait.lock, flags);
4735 x->done++;
4736 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4737 spin_unlock_irqrestore(&x->wait.lock, flags);
4738}
4739EXPORT_SYMBOL(complete);
4740
4741void complete_all(struct completion *x)
4742{
4743 unsigned long flags;
4744
4745 spin_lock_irqsave(&x->wait.lock, flags);
4746 x->done += UINT_MAX/2;
4747 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4748 spin_unlock_irqrestore(&x->wait.lock, flags);
4749}
4750EXPORT_SYMBOL(complete_all);
4751
4752static inline long __sched
4753do_wait_for_common(struct completion *x, long timeout, int state)
4754{
4755 if (!x->done) {
4756 DECLARE_WAITQUEUE(wait, current);
4757
4758 wait.flags |= WQ_FLAG_EXCLUSIVE;
4759 __add_wait_queue_tail(&x->wait, &wait);
4760 do {
4761 if ((state == TASK_INTERRUPTIBLE &&
4762 signal_pending(current)) ||
4763 (state == TASK_KILLABLE &&
4764 fatal_signal_pending(current))) {
4765 __remove_wait_queue(&x->wait, &wait);
4766 return -ERESTARTSYS;
4767 }
4768 __set_current_state(state);
4769 spin_unlock_irq(&x->wait.lock);
4770 timeout = schedule_timeout(timeout);
4771 spin_lock_irq(&x->wait.lock);
4772 if (!timeout) {
4773 __remove_wait_queue(&x->wait, &wait);
4774 return timeout;
4775 }
4776 } while (!x->done);
4777 __remove_wait_queue(&x->wait, &wait);
4778 }
4779 x->done--;
4780 return timeout;
4781}
4782
4783static long __sched
4784wait_for_common(struct completion *x, long timeout, int state)
4785{
4786 might_sleep();
4787
4788 spin_lock_irq(&x->wait.lock);
4789 timeout = do_wait_for_common(x, timeout, state);
4790 spin_unlock_irq(&x->wait.lock);
4791 return timeout;
4792}
4793
4794void __sched wait_for_completion(struct completion *x)
4795{
4796 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4797}
4798EXPORT_SYMBOL(wait_for_completion);
4799
4800unsigned long __sched
4801wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4802{
4803 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4804}
4805EXPORT_SYMBOL(wait_for_completion_timeout);
4806
4807int __sched wait_for_completion_interruptible(struct completion *x)
4808{
4809 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4810 if (t == -ERESTARTSYS)
4811 return t;
4812 return 0;
4813}
4814EXPORT_SYMBOL(wait_for_completion_interruptible);
4815
4816unsigned long __sched
4817wait_for_completion_interruptible_timeout(struct completion *x,
4818 unsigned long timeout)
4819{
4820 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4821}
4822EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4823
4824int __sched wait_for_completion_killable(struct completion *x)
4825{
4826 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4827 if (t == -ERESTARTSYS)
4828 return t;
4829 return 0;
4830}
4831EXPORT_SYMBOL(wait_for_completion_killable);
4832
4833static long __sched
4834sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4835{
4836 unsigned long flags;
4837 wait_queue_t wait;
4838
4839 init_waitqueue_entry(&wait, current);
4840
4841 __set_current_state(state);
4842
4843 spin_lock_irqsave(&q->lock, flags);
4844 __add_wait_queue(q, &wait);
4845 spin_unlock(&q->lock);
4846 timeout = schedule_timeout(timeout);
4847 spin_lock_irq(&q->lock);
4848 __remove_wait_queue(q, &wait);
4849 spin_unlock_irqrestore(&q->lock, flags);
4850
4851 return timeout;
4852}
4853
4854void __sched interruptible_sleep_on(wait_queue_head_t *q)
4855{
4856 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4857}
4858EXPORT_SYMBOL(interruptible_sleep_on);
4859
4860long __sched
4861interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4862{
4863 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4864}
4865EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4866
4867void __sched sleep_on(wait_queue_head_t *q)
4868{
4869 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4870}
4871EXPORT_SYMBOL(sleep_on);
4872
4873long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4874{
4875 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4876}
4877EXPORT_SYMBOL(sleep_on_timeout);
4878
4879#ifdef CONFIG_RT_MUTEXES
4880
4881/*
4882 * rt_mutex_setprio - set the current priority of a task
4883 * @p: task
4884 * @prio: prio value (kernel-internal form)
4885 *
4886 * This function changes the 'effective' priority of a task. It does
4887 * not touch ->normal_prio like __setscheduler().
4888 *
4889 * Used by the rt_mutex code to implement priority inheritance logic.
4890 */
4891void rt_mutex_setprio(struct task_struct *p, int prio)
4892{
4893 unsigned long flags;
4894 int oldprio, on_rq, running;
4895 struct rq *rq;
4896 const struct sched_class *prev_class = p->sched_class;
4897
4898 BUG_ON(prio < 0 || prio > MAX_PRIO);
4899
4900 rq = task_rq_lock(p, &flags);
4901 update_rq_clock(rq);
4902
4903 oldprio = p->prio;
4904 on_rq = p->se.on_rq;
4905 running = task_current(rq, p);
4906 if (on_rq)
4907 dequeue_task(rq, p, 0);
4908 if (running)
4909 p->sched_class->put_prev_task(rq, p);
4910
4911 if (rt_prio(prio))
4912 p->sched_class = &rt_sched_class;
4913 else
4914 p->sched_class = &fair_sched_class;
4915
4916 p->prio = prio;
4917
4918 if (running)
4919 p->sched_class->set_curr_task(rq);
4920 if (on_rq) {
4921 enqueue_task(rq, p, 0);
4922
4923 check_class_changed(rq, p, prev_class, oldprio, running);
4924 }
4925 task_rq_unlock(rq, &flags);
4926}
4927
4928#endif
4929
4930void set_user_nice(struct task_struct *p, long nice)
4931{
4932 int old_prio, delta, on_rq;
4933 unsigned long flags;
4934 struct rq *rq;
4935
4936 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4937 return;
4938 /*
4939 * We have to be careful, if called from sys_setpriority(),
4940 * the task might be in the middle of scheduling on another CPU.
4941 */
4942 rq = task_rq_lock(p, &flags);
4943 update_rq_clock(rq);
4944 /*
4945 * The RT priorities are set via sched_setscheduler(), but we still
4946 * allow the 'normal' nice value to be set - but as expected
4947 * it wont have any effect on scheduling until the task is
4948 * SCHED_FIFO/SCHED_RR:
4949 */
4950 if (task_has_rt_policy(p)) {
4951 p->static_prio = NICE_TO_PRIO(nice);
4952 goto out_unlock;
4953 }
4954 on_rq = p->se.on_rq;
4955 if (on_rq)
4956 dequeue_task(rq, p, 0);
4957
4958 p->static_prio = NICE_TO_PRIO(nice);
4959 set_load_weight(p);
4960 old_prio = p->prio;
4961 p->prio = effective_prio(p);
4962 delta = p->prio - old_prio;
4963
4964 if (on_rq) {
4965 enqueue_task(rq, p, 0);
4966 /*
4967 * If the task increased its priority or is running and
4968 * lowered its priority, then reschedule its CPU:
4969 */
4970 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4971 resched_task(rq->curr);
4972 }
4973out_unlock:
4974 task_rq_unlock(rq, &flags);
4975}
4976EXPORT_SYMBOL(set_user_nice);
4977
4978/*
4979 * can_nice - check if a task can reduce its nice value
4980 * @p: task
4981 * @nice: nice value
4982 */
4983int can_nice(const struct task_struct *p, const int nice)
4984{
4985 /* convert nice value [19,-20] to rlimit style value [1,40] */
4986 int nice_rlim = 20 - nice;
4987
4988 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4989 capable(CAP_SYS_NICE));
4990}
4991
4992#ifdef __ARCH_WANT_SYS_NICE
4993
4994/*
4995 * sys_nice - change the priority of the current process.
4996 * @increment: priority increment
4997 *
4998 * sys_setpriority is a more generic, but much slower function that
4999 * does similar things.
5000 */
5001asmlinkage long sys_nice(int increment)
5002{
5003 long nice, retval;
5004
5005 /*
5006 * Setpriority might change our priority at the same moment.
5007 * We don't have to worry. Conceptually one call occurs first
5008 * and we have a single winner.
5009 */
5010 if (increment < -40)
5011 increment = -40;
5012 if (increment > 40)
5013 increment = 40;
5014
5015 nice = PRIO_TO_NICE(current->static_prio) + increment;
5016 if (nice < -20)
5017 nice = -20;
5018 if (nice > 19)
5019 nice = 19;
5020
5021 if (increment < 0 && !can_nice(current, nice))
5022 return -EPERM;
5023
5024 retval = security_task_setnice(current, nice);
5025 if (retval)
5026 return retval;
5027
5028 set_user_nice(current, nice);
5029 return 0;
5030}
5031
5032#endif
5033
5034/**
5035 * task_prio - return the priority value of a given task.
5036 * @p: the task in question.
5037 *
5038 * This is the priority value as seen by users in /proc.
5039 * RT tasks are offset by -200. Normal tasks are centered
5040 * around 0, value goes from -16 to +15.
5041 */
5042int task_prio(const struct task_struct *p)
5043{
5044 return p->prio - MAX_RT_PRIO;
5045}
5046
5047/**
5048 * task_nice - return the nice value of a given task.
5049 * @p: the task in question.
5050 */
5051int task_nice(const struct task_struct *p)
5052{
5053 return TASK_NICE(p);
5054}
5055EXPORT_SYMBOL(task_nice);
5056
5057/**
5058 * idle_cpu - is a given cpu idle currently?
5059 * @cpu: the processor in question.
5060 */
5061int idle_cpu(int cpu)
5062{
5063 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5064}
5065
5066/**
5067 * idle_task - return the idle task for a given cpu.
5068 * @cpu: the processor in question.
5069 */
5070struct task_struct *idle_task(int cpu)
5071{
5072 return cpu_rq(cpu)->idle;
5073}
5074
5075/**
5076 * find_process_by_pid - find a process with a matching PID value.
5077 * @pid: the pid in question.
5078 */
5079static struct task_struct *find_process_by_pid(pid_t pid)
5080{
5081 return pid ? find_task_by_vpid(pid) : current;
5082}
5083
5084/* Actually do priority change: must hold rq lock. */
5085static void
5086__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5087{
5088 BUG_ON(p->se.on_rq);
5089
5090 p->policy = policy;
5091 switch (p->policy) {
5092 case SCHED_NORMAL:
5093 case SCHED_BATCH:
5094 case SCHED_IDLE:
5095 p->sched_class = &fair_sched_class;
5096 break;
5097 case SCHED_FIFO:
5098 case SCHED_RR:
5099 p->sched_class = &rt_sched_class;
5100 break;
5101 }
5102
5103 p->rt_priority = prio;
5104 p->normal_prio = normal_prio(p);
5105 /* we are holding p->pi_lock already */
5106 p->prio = rt_mutex_getprio(p);
5107 set_load_weight(p);
5108}
5109
5110/**
5111 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5112 * @p: the task in question.
5113 * @policy: new policy.
5114 * @param: structure containing the new RT priority.
5115 *
5116 * NOTE that the task may be already dead.
5117 */
5118int sched_setscheduler(struct task_struct *p, int policy,
5119 struct sched_param *param)
5120{
5121 int retval, oldprio, oldpolicy = -1, on_rq, running;
5122 unsigned long flags;
5123 const struct sched_class *prev_class = p->sched_class;
5124 struct rq *rq;
5125
5126 /* may grab non-irq protected spin_locks */
5127 BUG_ON(in_interrupt());
5128recheck:
5129 /* double check policy once rq lock held */
5130 if (policy < 0)
5131 policy = oldpolicy = p->policy;
5132 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5133 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5134 policy != SCHED_IDLE)
5135 return -EINVAL;
5136 /*
5137 * Valid priorities for SCHED_FIFO and SCHED_RR are
5138 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5139 * SCHED_BATCH and SCHED_IDLE is 0.
5140 */
5141 if (param->sched_priority < 0 ||
5142 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5143 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5144 return -EINVAL;
5145 if (rt_policy(policy) != (param->sched_priority != 0))
5146 return -EINVAL;
5147
5148 /*
5149 * Allow unprivileged RT tasks to decrease priority:
5150 */
5151 if (!capable(CAP_SYS_NICE)) {
5152 if (rt_policy(policy)) {
5153 unsigned long rlim_rtprio;
5154
5155 if (!lock_task_sighand(p, &flags))
5156 return -ESRCH;
5157 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5158 unlock_task_sighand(p, &flags);
5159
5160 /* can't set/change the rt policy */
5161 if (policy != p->policy && !rlim_rtprio)
5162 return -EPERM;
5163
5164 /* can't increase priority */
5165 if (param->sched_priority > p->rt_priority &&
5166 param->sched_priority > rlim_rtprio)
5167 return -EPERM;
5168 }
5169 /*
5170 * Like positive nice levels, dont allow tasks to
5171 * move out of SCHED_IDLE either:
5172 */
5173 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5174 return -EPERM;
5175
5176 /* can't change other user's priorities */
5177 if ((current->euid != p->euid) &&
5178 (current->euid != p->uid))
5179 return -EPERM;
5180 }
5181
5182#ifdef CONFIG_RT_GROUP_SCHED
5183 /*
5184 * Do not allow realtime tasks into groups that have no runtime
5185 * assigned.
5186 */
5187 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5188 return -EPERM;
5189#endif
5190
5191 retval = security_task_setscheduler(p, policy, param);
5192 if (retval)
5193 return retval;
5194 /*
5195 * make sure no PI-waiters arrive (or leave) while we are
5196 * changing the priority of the task:
5197 */
5198 spin_lock_irqsave(&p->pi_lock, flags);
5199 /*
5200 * To be able to change p->policy safely, the apropriate
5201 * runqueue lock must be held.
5202 */
5203 rq = __task_rq_lock(p);
5204 /* recheck policy now with rq lock held */
5205 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5206 policy = oldpolicy = -1;
5207 __task_rq_unlock(rq);
5208 spin_unlock_irqrestore(&p->pi_lock, flags);
5209 goto recheck;
5210 }
5211 update_rq_clock(rq);
5212 on_rq = p->se.on_rq;
5213 running = task_current(rq, p);
5214 if (on_rq)
5215 deactivate_task(rq, p, 0);
5216 if (running)
5217 p->sched_class->put_prev_task(rq, p);
5218
5219 oldprio = p->prio;
5220 __setscheduler(rq, p, policy, param->sched_priority);
5221
5222 if (running)
5223 p->sched_class->set_curr_task(rq);
5224 if (on_rq) {
5225 activate_task(rq, p, 0);
5226
5227 check_class_changed(rq, p, prev_class, oldprio, running);
5228 }
5229 __task_rq_unlock(rq);
5230 spin_unlock_irqrestore(&p->pi_lock, flags);
5231
5232 rt_mutex_adjust_pi(p);
5233
5234 return 0;
5235}
5236EXPORT_SYMBOL_GPL(sched_setscheduler);
5237
5238static int
5239do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5240{
5241 struct sched_param lparam;
5242 struct task_struct *p;
5243 int retval;
5244
5245 if (!param || pid < 0)
5246 return -EINVAL;
5247 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5248 return -EFAULT;
5249
5250 rcu_read_lock();
5251 retval = -ESRCH;
5252 p = find_process_by_pid(pid);
5253 if (p != NULL)
5254 retval = sched_setscheduler(p, policy, &lparam);
5255 rcu_read_unlock();
5256
5257 return retval;
5258}
5259
5260/**
5261 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5262 * @pid: the pid in question.
5263 * @policy: new policy.
5264 * @param: structure containing the new RT priority.
5265 */
5266asmlinkage long
5267sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5268{
5269 /* negative values for policy are not valid */
5270 if (policy < 0)
5271 return -EINVAL;
5272
5273 return do_sched_setscheduler(pid, policy, param);
5274}
5275
5276/**
5277 * sys_sched_setparam - set/change the RT priority of a thread
5278 * @pid: the pid in question.
5279 * @param: structure containing the new RT priority.
5280 */
5281asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5282{
5283 return do_sched_setscheduler(pid, -1, param);
5284}
5285
5286/**
5287 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5288 * @pid: the pid in question.
5289 */
5290asmlinkage long sys_sched_getscheduler(pid_t pid)
5291{
5292 struct task_struct *p;
5293 int retval;
5294
5295 if (pid < 0)
5296 return -EINVAL;
5297
5298 retval = -ESRCH;
5299 read_lock(&tasklist_lock);
5300 p = find_process_by_pid(pid);
5301 if (p) {
5302 retval = security_task_getscheduler(p);
5303 if (!retval)
5304 retval = p->policy;
5305 }
5306 read_unlock(&tasklist_lock);
5307 return retval;
5308}
5309
5310/**
5311 * sys_sched_getscheduler - get the RT priority of a thread
5312 * @pid: the pid in question.
5313 * @param: structure containing the RT priority.
5314 */
5315asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5316{
5317 struct sched_param lp;
5318 struct task_struct *p;
5319 int retval;
5320
5321 if (!param || pid < 0)
5322 return -EINVAL;
5323
5324 read_lock(&tasklist_lock);
5325 p = find_process_by_pid(pid);
5326 retval = -ESRCH;
5327 if (!p)
5328 goto out_unlock;
5329
5330 retval = security_task_getscheduler(p);
5331 if (retval)
5332 goto out_unlock;
5333
5334 lp.sched_priority = p->rt_priority;
5335 read_unlock(&tasklist_lock);
5336
5337 /*
5338 * This one might sleep, we cannot do it with a spinlock held ...
5339 */
5340 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5341
5342 return retval;
5343
5344out_unlock:
5345 read_unlock(&tasklist_lock);
5346 return retval;
5347}
5348
5349long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5350{
5351 cpumask_t cpus_allowed;
5352 cpumask_t new_mask = *in_mask;
5353 struct task_struct *p;
5354 int retval;
5355
5356 get_online_cpus();
5357 read_lock(&tasklist_lock);
5358
5359 p = find_process_by_pid(pid);
5360 if (!p) {
5361 read_unlock(&tasklist_lock);
5362 put_online_cpus();
5363 return -ESRCH;
5364 }
5365
5366 /*
5367 * It is not safe to call set_cpus_allowed with the
5368 * tasklist_lock held. We will bump the task_struct's
5369 * usage count and then drop tasklist_lock.
5370 */
5371 get_task_struct(p);
5372 read_unlock(&tasklist_lock);
5373
5374 retval = -EPERM;
5375 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5376 !capable(CAP_SYS_NICE))
5377 goto out_unlock;
5378
5379 retval = security_task_setscheduler(p, 0, NULL);
5380 if (retval)
5381 goto out_unlock;
5382
5383 cpuset_cpus_allowed(p, &cpus_allowed);
5384 cpus_and(new_mask, new_mask, cpus_allowed);
5385 again:
5386 retval = set_cpus_allowed_ptr(p, &new_mask);
5387
5388 if (!retval) {
5389 cpuset_cpus_allowed(p, &cpus_allowed);
5390 if (!cpus_subset(new_mask, cpus_allowed)) {
5391 /*
5392 * We must have raced with a concurrent cpuset
5393 * update. Just reset the cpus_allowed to the
5394 * cpuset's cpus_allowed
5395 */
5396 new_mask = cpus_allowed;
5397 goto again;
5398 }
5399 }
5400out_unlock:
5401 put_task_struct(p);
5402 put_online_cpus();
5403 return retval;
5404}
5405
5406static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5407 cpumask_t *new_mask)
5408{
5409 if (len < sizeof(cpumask_t)) {
5410 memset(new_mask, 0, sizeof(cpumask_t));
5411 } else if (len > sizeof(cpumask_t)) {
5412 len = sizeof(cpumask_t);
5413 }
5414 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5415}
5416
5417/**
5418 * sys_sched_setaffinity - set the cpu affinity of a process
5419 * @pid: pid of the process
5420 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5421 * @user_mask_ptr: user-space pointer to the new cpu mask
5422 */
5423asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5424 unsigned long __user *user_mask_ptr)
5425{
5426 cpumask_t new_mask;
5427 int retval;
5428
5429 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5430 if (retval)
5431 return retval;
5432
5433 return sched_setaffinity(pid, &new_mask);
5434}
5435
5436/*
5437 * Represents all cpu's present in the system
5438 * In systems capable of hotplug, this map could dynamically grow
5439 * as new cpu's are detected in the system via any platform specific
5440 * method, such as ACPI for e.g.
5441 */
5442
5443cpumask_t cpu_present_map __read_mostly;
5444EXPORT_SYMBOL(cpu_present_map);
5445
5446#ifndef CONFIG_SMP
5447cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5448EXPORT_SYMBOL(cpu_online_map);
5449
5450cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5451EXPORT_SYMBOL(cpu_possible_map);
5452#endif
5453
5454long sched_getaffinity(pid_t pid, cpumask_t *mask)
5455{
5456 struct task_struct *p;
5457 int retval;
5458
5459 get_online_cpus();
5460 read_lock(&tasklist_lock);
5461
5462 retval = -ESRCH;
5463 p = find_process_by_pid(pid);
5464 if (!p)
5465 goto out_unlock;
5466
5467 retval = security_task_getscheduler(p);
5468 if (retval)
5469 goto out_unlock;
5470
5471 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5472
5473out_unlock:
5474 read_unlock(&tasklist_lock);
5475 put_online_cpus();
5476
5477 return retval;
5478}
5479
5480/**
5481 * sys_sched_getaffinity - get the cpu affinity of a process
5482 * @pid: pid of the process
5483 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5484 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5485 */
5486asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5487 unsigned long __user *user_mask_ptr)
5488{
5489 int ret;
5490 cpumask_t mask;
5491
5492 if (len < sizeof(cpumask_t))
5493 return -EINVAL;
5494
5495 ret = sched_getaffinity(pid, &mask);
5496 if (ret < 0)
5497 return ret;
5498
5499 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5500 return -EFAULT;
5501
5502 return sizeof(cpumask_t);
5503}
5504
5505/**
5506 * sys_sched_yield - yield the current processor to other threads.
5507 *
5508 * This function yields the current CPU to other tasks. If there are no
5509 * other threads running on this CPU then this function will return.
5510 */
5511asmlinkage long sys_sched_yield(void)
5512{
5513 struct rq *rq = this_rq_lock();
5514
5515 schedstat_inc(rq, yld_count);
5516 current->sched_class->yield_task(rq);
5517
5518 /*
5519 * Since we are going to call schedule() anyway, there's
5520 * no need to preempt or enable interrupts:
5521 */
5522 __release(rq->lock);
5523 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5524 _raw_spin_unlock(&rq->lock);
5525 preempt_enable_no_resched();
5526
5527 schedule();
5528
5529 return 0;
5530}
5531
5532static void __cond_resched(void)
5533{
5534#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5535 __might_sleep(__FILE__, __LINE__);
5536#endif
5537 /*
5538 * The BKS might be reacquired before we have dropped
5539 * PREEMPT_ACTIVE, which could trigger a second
5540 * cond_resched() call.
5541 */
5542 do {
5543 add_preempt_count(PREEMPT_ACTIVE);
5544 schedule();
5545 sub_preempt_count(PREEMPT_ACTIVE);
5546 } while (need_resched());
5547}
5548
5549#if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5550int __sched _cond_resched(void)
5551{
5552 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5553 system_state == SYSTEM_RUNNING) {
5554 __cond_resched();
5555 return 1;
5556 }
5557 return 0;
5558}
5559EXPORT_SYMBOL(_cond_resched);
5560#endif
5561
5562/*
5563 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5564 * call schedule, and on return reacquire the lock.
5565 *
5566 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5567 * operations here to prevent schedule() from being called twice (once via
5568 * spin_unlock(), once by hand).
5569 */
5570int cond_resched_lock(spinlock_t *lock)
5571{
5572 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5573 int ret = 0;
5574
5575 if (spin_needbreak(lock) || resched) {
5576 spin_unlock(lock);
5577 if (resched && need_resched())
5578 __cond_resched();
5579 else
5580 cpu_relax();
5581 ret = 1;
5582 spin_lock(lock);
5583 }
5584 return ret;
5585}
5586EXPORT_SYMBOL(cond_resched_lock);
5587
5588int __sched cond_resched_softirq(void)
5589{
5590 BUG_ON(!in_softirq());
5591
5592 if (need_resched() && system_state == SYSTEM_RUNNING) {
5593 local_bh_enable();
5594 __cond_resched();
5595 local_bh_disable();
5596 return 1;
5597 }
5598 return 0;
5599}
5600EXPORT_SYMBOL(cond_resched_softirq);
5601
5602/**
5603 * yield - yield the current processor to other threads.
5604 *
5605 * This is a shortcut for kernel-space yielding - it marks the
5606 * thread runnable and calls sys_sched_yield().
5607 */
5608void __sched yield(void)
5609{
5610 set_current_state(TASK_RUNNING);
5611 sys_sched_yield();
5612}
5613EXPORT_SYMBOL(yield);
5614
5615/*
5616 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5617 * that process accounting knows that this is a task in IO wait state.
5618 *
5619 * But don't do that if it is a deliberate, throttling IO wait (this task
5620 * has set its backing_dev_info: the queue against which it should throttle)
5621 */
5622void __sched io_schedule(void)
5623{
5624 struct rq *rq = &__raw_get_cpu_var(runqueues);
5625
5626 delayacct_blkio_start();
5627 atomic_inc(&rq->nr_iowait);
5628 schedule();
5629 atomic_dec(&rq->nr_iowait);
5630 delayacct_blkio_end();
5631}
5632EXPORT_SYMBOL(io_schedule);
5633
5634long __sched io_schedule_timeout(long timeout)
5635{
5636 struct rq *rq = &__raw_get_cpu_var(runqueues);
5637 long ret;
5638
5639 delayacct_blkio_start();
5640 atomic_inc(&rq->nr_iowait);
5641 ret = schedule_timeout(timeout);
5642 atomic_dec(&rq->nr_iowait);
5643 delayacct_blkio_end();
5644 return ret;
5645}
5646
5647/**
5648 * sys_sched_get_priority_max - return maximum RT priority.
5649 * @policy: scheduling class.
5650 *
5651 * this syscall returns the maximum rt_priority that can be used
5652 * by a given scheduling class.
5653 */
5654asmlinkage long sys_sched_get_priority_max(int policy)
5655{
5656 int ret = -EINVAL;
5657
5658 switch (policy) {
5659 case SCHED_FIFO:
5660 case SCHED_RR:
5661 ret = MAX_USER_RT_PRIO-1;
5662 break;
5663 case SCHED_NORMAL:
5664 case SCHED_BATCH:
5665 case SCHED_IDLE:
5666 ret = 0;
5667 break;
5668 }
5669 return ret;
5670}
5671
5672/**
5673 * sys_sched_get_priority_min - return minimum RT priority.
5674 * @policy: scheduling class.
5675 *
5676 * this syscall returns the minimum rt_priority that can be used
5677 * by a given scheduling class.
5678 */
5679asmlinkage long sys_sched_get_priority_min(int policy)
5680{
5681 int ret = -EINVAL;
5682
5683 switch (policy) {
5684 case SCHED_FIFO:
5685 case SCHED_RR:
5686 ret = 1;
5687 break;
5688 case SCHED_NORMAL:
5689 case SCHED_BATCH:
5690 case SCHED_IDLE:
5691 ret = 0;
5692 }
5693 return ret;
5694}
5695
5696/**
5697 * sys_sched_rr_get_interval - return the default timeslice of a process.
5698 * @pid: pid of the process.
5699 * @interval: userspace pointer to the timeslice value.
5700 *
5701 * this syscall writes the default timeslice value of a given process
5702 * into the user-space timespec buffer. A value of '0' means infinity.
5703 */
5704asmlinkage
5705long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5706{
5707 struct task_struct *p;
5708 unsigned int time_slice;
5709 int retval;
5710 struct timespec t;
5711
5712 if (pid < 0)
5713 return -EINVAL;
5714
5715 retval = -ESRCH;
5716 read_lock(&tasklist_lock);
5717 p = find_process_by_pid(pid);
5718 if (!p)
5719 goto out_unlock;
5720
5721 retval = security_task_getscheduler(p);
5722 if (retval)
5723 goto out_unlock;
5724
5725 /*
5726 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5727 * tasks that are on an otherwise idle runqueue:
5728 */
5729 time_slice = 0;
5730 if (p->policy == SCHED_RR) {
5731 time_slice = DEF_TIMESLICE;
5732 } else if (p->policy != SCHED_FIFO) {
5733 struct sched_entity *se = &p->se;
5734 unsigned long flags;
5735 struct rq *rq;
5736
5737 rq = task_rq_lock(p, &flags);
5738 if (rq->cfs.load.weight)
5739 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5740 task_rq_unlock(rq, &flags);
5741 }
5742 read_unlock(&tasklist_lock);
5743 jiffies_to_timespec(time_slice, &t);
5744 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5745 return retval;
5746
5747out_unlock:
5748 read_unlock(&tasklist_lock);
5749 return retval;
5750}
5751
5752static const char stat_nam[] = "RSDTtZX";
5753
5754void sched_show_task(struct task_struct *p)
5755{
5756 unsigned long free = 0;
5757 unsigned state;
5758
5759 state = p->state ? __ffs(p->state) + 1 : 0;
5760 printk(KERN_INFO "%-13.13s %c", p->comm,
5761 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5762#if BITS_PER_LONG == 32
5763 if (state == TASK_RUNNING)
5764 printk(KERN_CONT " running ");
5765 else
5766 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5767#else
5768 if (state == TASK_RUNNING)
5769 printk(KERN_CONT " running task ");
5770 else
5771 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5772#endif
5773#ifdef CONFIG_DEBUG_STACK_USAGE
5774 {
5775 unsigned long *n = end_of_stack(p);
5776 while (!*n)
5777 n++;
5778 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5779 }
5780#endif
5781 printk(KERN_CONT "%5lu %5d %6d\n", free,
5782 task_pid_nr(p), task_pid_nr(p->real_parent));
5783
5784 show_stack(p, NULL);
5785}
5786
5787void show_state_filter(unsigned long state_filter)
5788{
5789 struct task_struct *g, *p;
5790
5791#if BITS_PER_LONG == 32
5792 printk(KERN_INFO
5793 " task PC stack pid father\n");
5794#else
5795 printk(KERN_INFO
5796 " task PC stack pid father\n");
5797#endif
5798 read_lock(&tasklist_lock);
5799 do_each_thread(g, p) {
5800 /*
5801 * reset the NMI-timeout, listing all files on a slow
5802 * console might take alot of time:
5803 */
5804 touch_nmi_watchdog();
5805 if (!state_filter || (p->state & state_filter))
5806 sched_show_task(p);
5807 } while_each_thread(g, p);
5808
5809 touch_all_softlockup_watchdogs();
5810
5811#ifdef CONFIG_SCHED_DEBUG
5812 sysrq_sched_debug_show();
5813#endif
5814 read_unlock(&tasklist_lock);
5815 /*
5816 * Only show locks if all tasks are dumped:
5817 */
5818 if (state_filter == -1)
5819 debug_show_all_locks();
5820}
5821
5822void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5823{
5824 idle->sched_class = &idle_sched_class;
5825}
5826
5827/**
5828 * init_idle - set up an idle thread for a given CPU
5829 * @idle: task in question
5830 * @cpu: cpu the idle task belongs to
5831 *
5832 * NOTE: this function does not set the idle thread's NEED_RESCHED
5833 * flag, to make booting more robust.
5834 */
5835void __cpuinit init_idle(struct task_struct *idle, int cpu)
5836{
5837 struct rq *rq = cpu_rq(cpu);
5838 unsigned long flags;
5839
5840 __sched_fork(idle);
5841 idle->se.exec_start = sched_clock();
5842
5843 idle->prio = idle->normal_prio = MAX_PRIO;
5844 idle->cpus_allowed = cpumask_of_cpu(cpu);
5845 __set_task_cpu(idle, cpu);
5846
5847 spin_lock_irqsave(&rq->lock, flags);
5848 rq->curr = rq->idle = idle;
5849#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5850 idle->oncpu = 1;
5851#endif
5852 spin_unlock_irqrestore(&rq->lock, flags);
5853
5854 /* Set the preempt count _outside_ the spinlocks! */
5855 task_thread_info(idle)->preempt_count = 0;
5856
5857 /*
5858 * The idle tasks have their own, simple scheduling class:
5859 */
5860 idle->sched_class = &idle_sched_class;
5861}
5862
5863/*
5864 * In a system that switches off the HZ timer nohz_cpu_mask
5865 * indicates which cpus entered this state. This is used
5866 * in the rcu update to wait only for active cpus. For system
5867 * which do not switch off the HZ timer nohz_cpu_mask should
5868 * always be CPU_MASK_NONE.
5869 */
5870cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5871
5872/*
5873 * Increase the granularity value when there are more CPUs,
5874 * because with more CPUs the 'effective latency' as visible
5875 * to users decreases. But the relationship is not linear,
5876 * so pick a second-best guess by going with the log2 of the
5877 * number of CPUs.
5878 *
5879 * This idea comes from the SD scheduler of Con Kolivas:
5880 */
5881static inline void sched_init_granularity(void)
5882{
5883 unsigned int factor = 1 + ilog2(num_online_cpus());
5884 const unsigned long limit = 200000000;
5885
5886 sysctl_sched_min_granularity *= factor;
5887 if (sysctl_sched_min_granularity > limit)
5888 sysctl_sched_min_granularity = limit;
5889
5890 sysctl_sched_latency *= factor;
5891 if (sysctl_sched_latency > limit)
5892 sysctl_sched_latency = limit;
5893
5894 sysctl_sched_wakeup_granularity *= factor;
5895}
5896
5897#ifdef CONFIG_SMP
5898/*
5899 * This is how migration works:
5900 *
5901 * 1) we queue a struct migration_req structure in the source CPU's
5902 * runqueue and wake up that CPU's migration thread.
5903 * 2) we down() the locked semaphore => thread blocks.
5904 * 3) migration thread wakes up (implicitly it forces the migrated
5905 * thread off the CPU)
5906 * 4) it gets the migration request and checks whether the migrated
5907 * task is still in the wrong runqueue.
5908 * 5) if it's in the wrong runqueue then the migration thread removes
5909 * it and puts it into the right queue.
5910 * 6) migration thread up()s the semaphore.
5911 * 7) we wake up and the migration is done.
5912 */
5913
5914/*
5915 * Change a given task's CPU affinity. Migrate the thread to a
5916 * proper CPU and schedule it away if the CPU it's executing on
5917 * is removed from the allowed bitmask.
5918 *
5919 * NOTE: the caller must have a valid reference to the task, the
5920 * task must not exit() & deallocate itself prematurely. The
5921 * call is not atomic; no spinlocks may be held.
5922 */
5923int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5924{
5925 struct migration_req req;
5926 unsigned long flags;
5927 struct rq *rq;
5928 int ret = 0;
5929
5930 rq = task_rq_lock(p, &flags);
5931 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5932 ret = -EINVAL;
5933 goto out;
5934 }
5935
5936 if (p->sched_class->set_cpus_allowed)
5937 p->sched_class->set_cpus_allowed(p, new_mask);
5938 else {
5939 p->cpus_allowed = *new_mask;
5940 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5941 }
5942
5943 /* Can the task run on the task's current CPU? If so, we're done */
5944 if (cpu_isset(task_cpu(p), *new_mask))
5945 goto out;
5946
5947 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5948 /* Need help from migration thread: drop lock and wait. */
5949 task_rq_unlock(rq, &flags);
5950 wake_up_process(rq->migration_thread);
5951 wait_for_completion(&req.done);
5952 tlb_migrate_finish(p->mm);
5953 return 0;
5954 }
5955out:
5956 task_rq_unlock(rq, &flags);
5957
5958 return ret;
5959}
5960EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5961
5962/*
5963 * Move (not current) task off this cpu, onto dest cpu. We're doing
5964 * this because either it can't run here any more (set_cpus_allowed()
5965 * away from this CPU, or CPU going down), or because we're
5966 * attempting to rebalance this task on exec (sched_exec).
5967 *
5968 * So we race with normal scheduler movements, but that's OK, as long
5969 * as the task is no longer on this CPU.
5970 *
5971 * Returns non-zero if task was successfully migrated.
5972 */
5973static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5974{
5975 struct rq *rq_dest, *rq_src;
5976 int ret = 0, on_rq;
5977
5978 if (unlikely(cpu_is_offline(dest_cpu)))
5979 return ret;
5980
5981 rq_src = cpu_rq(src_cpu);
5982 rq_dest = cpu_rq(dest_cpu);
5983
5984 double_rq_lock(rq_src, rq_dest);
5985 /* Already moved. */
5986 if (task_cpu(p) != src_cpu)
5987 goto out;
5988 /* Affinity changed (again). */
5989 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5990 goto out;
5991
5992 on_rq = p->se.on_rq;
5993 if (on_rq)
5994 deactivate_task(rq_src, p, 0);
5995
5996 set_task_cpu(p, dest_cpu);
5997 if (on_rq) {
5998 activate_task(rq_dest, p, 0);
5999 check_preempt_curr(rq_dest, p);
6000 }
6001 ret = 1;
6002out:
6003 double_rq_unlock(rq_src, rq_dest);
6004 return ret;
6005}
6006
6007/*
6008 * migration_thread - this is a highprio system thread that performs
6009 * thread migration by bumping thread off CPU then 'pushing' onto
6010 * another runqueue.
6011 */
6012static int migration_thread(void *data)
6013{
6014 int cpu = (long)data;
6015 struct rq *rq;
6016
6017 rq = cpu_rq(cpu);
6018 BUG_ON(rq->migration_thread != current);
6019
6020 set_current_state(TASK_INTERRUPTIBLE);
6021 while (!kthread_should_stop()) {
6022 struct migration_req *req;
6023 struct list_head *head;
6024
6025 spin_lock_irq(&rq->lock);
6026
6027 if (cpu_is_offline(cpu)) {
6028 spin_unlock_irq(&rq->lock);
6029 goto wait_to_die;
6030 }
6031
6032 if (rq->active_balance) {
6033 active_load_balance(rq, cpu);
6034 rq->active_balance = 0;
6035 }
6036
6037 head = &rq->migration_queue;
6038
6039 if (list_empty(head)) {
6040 spin_unlock_irq(&rq->lock);
6041 schedule();
6042 set_current_state(TASK_INTERRUPTIBLE);
6043 continue;
6044 }
6045 req = list_entry(head->next, struct migration_req, list);
6046 list_del_init(head->next);
6047
6048 spin_unlock(&rq->lock);
6049 __migrate_task(req->task, cpu, req->dest_cpu);
6050 local_irq_enable();
6051
6052 complete(&req->done);
6053 }
6054 __set_current_state(TASK_RUNNING);
6055 return 0;
6056
6057wait_to_die:
6058 /* Wait for kthread_stop */
6059 set_current_state(TASK_INTERRUPTIBLE);
6060 while (!kthread_should_stop()) {
6061 schedule();
6062 set_current_state(TASK_INTERRUPTIBLE);
6063 }
6064 __set_current_state(TASK_RUNNING);
6065 return 0;
6066}
6067
6068#ifdef CONFIG_HOTPLUG_CPU
6069
6070static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6071{
6072 int ret;
6073
6074 local_irq_disable();
6075 ret = __migrate_task(p, src_cpu, dest_cpu);
6076 local_irq_enable();
6077 return ret;
6078}
6079
6080/*
6081 * Figure out where task on dead CPU should go, use force if necessary.
6082 * NOTE: interrupts should be disabled by the caller
6083 */
6084static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6085{
6086 unsigned long flags;
6087 cpumask_t mask;
6088 struct rq *rq;
6089 int dest_cpu;
6090
6091 do {
6092 /* On same node? */
6093 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6094 cpus_and(mask, mask, p->cpus_allowed);
6095 dest_cpu = any_online_cpu(mask);
6096
6097 /* On any allowed CPU? */
6098 if (dest_cpu >= nr_cpu_ids)
6099 dest_cpu = any_online_cpu(p->cpus_allowed);
6100
6101 /* No more Mr. Nice Guy. */
6102 if (dest_cpu >= nr_cpu_ids) {
6103 cpumask_t cpus_allowed;
6104
6105 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6106 /*
6107 * Try to stay on the same cpuset, where the
6108 * current cpuset may be a subset of all cpus.
6109 * The cpuset_cpus_allowed_locked() variant of
6110 * cpuset_cpus_allowed() will not block. It must be
6111 * called within calls to cpuset_lock/cpuset_unlock.
6112 */
6113 rq = task_rq_lock(p, &flags);
6114 p->cpus_allowed = cpus_allowed;
6115 dest_cpu = any_online_cpu(p->cpus_allowed);
6116 task_rq_unlock(rq, &flags);
6117
6118 /*
6119 * Don't tell them about moving exiting tasks or
6120 * kernel threads (both mm NULL), since they never
6121 * leave kernel.
6122 */
6123 if (p->mm && printk_ratelimit()) {
6124 printk(KERN_INFO "process %d (%s) no "
6125 "longer affine to cpu%d\n",
6126 task_pid_nr(p), p->comm, dead_cpu);
6127 }
6128 }
6129 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6130}
6131
6132/*
6133 * While a dead CPU has no uninterruptible tasks queued at this point,
6134 * it might still have a nonzero ->nr_uninterruptible counter, because
6135 * for performance reasons the counter is not stricly tracking tasks to
6136 * their home CPUs. So we just add the counter to another CPU's counter,
6137 * to keep the global sum constant after CPU-down:
6138 */
6139static void migrate_nr_uninterruptible(struct rq *rq_src)
6140{
6141 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6142 unsigned long flags;
6143
6144 local_irq_save(flags);
6145 double_rq_lock(rq_src, rq_dest);
6146 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6147 rq_src->nr_uninterruptible = 0;
6148 double_rq_unlock(rq_src, rq_dest);
6149 local_irq_restore(flags);
6150}
6151
6152/* Run through task list and migrate tasks from the dead cpu. */
6153static void migrate_live_tasks(int src_cpu)
6154{
6155 struct task_struct *p, *t;
6156
6157 read_lock(&tasklist_lock);
6158
6159 do_each_thread(t, p) {
6160 if (p == current)
6161 continue;
6162
6163 if (task_cpu(p) == src_cpu)
6164 move_task_off_dead_cpu(src_cpu, p);
6165 } while_each_thread(t, p);
6166
6167 read_unlock(&tasklist_lock);
6168}
6169
6170/*
6171 * Schedules idle task to be the next runnable task on current CPU.
6172 * It does so by boosting its priority to highest possible.
6173 * Used by CPU offline code.
6174 */
6175void sched_idle_next(void)
6176{
6177 int this_cpu = smp_processor_id();
6178 struct rq *rq = cpu_rq(this_cpu);
6179 struct task_struct *p = rq->idle;
6180 unsigned long flags;
6181
6182 /* cpu has to be offline */
6183 BUG_ON(cpu_online(this_cpu));
6184
6185 /*
6186 * Strictly not necessary since rest of the CPUs are stopped by now
6187 * and interrupts disabled on the current cpu.
6188 */
6189 spin_lock_irqsave(&rq->lock, flags);
6190
6191 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6192
6193 update_rq_clock(rq);
6194 activate_task(rq, p, 0);
6195
6196 spin_unlock_irqrestore(&rq->lock, flags);
6197}
6198
6199/*
6200 * Ensures that the idle task is using init_mm right before its cpu goes
6201 * offline.
6202 */
6203void idle_task_exit(void)
6204{
6205 struct mm_struct *mm = current->active_mm;
6206
6207 BUG_ON(cpu_online(smp_processor_id()));
6208
6209 if (mm != &init_mm)
6210 switch_mm(mm, &init_mm, current);
6211 mmdrop(mm);
6212}
6213
6214/* called under rq->lock with disabled interrupts */
6215static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6216{
6217 struct rq *rq = cpu_rq(dead_cpu);
6218
6219 /* Must be exiting, otherwise would be on tasklist. */
6220 BUG_ON(!p->exit_state);
6221
6222 /* Cannot have done final schedule yet: would have vanished. */
6223 BUG_ON(p->state == TASK_DEAD);
6224
6225 get_task_struct(p);
6226
6227 /*
6228 * Drop lock around migration; if someone else moves it,
6229 * that's OK. No task can be added to this CPU, so iteration is
6230 * fine.
6231 */
6232 spin_unlock_irq(&rq->lock);
6233 move_task_off_dead_cpu(dead_cpu, p);
6234 spin_lock_irq(&rq->lock);
6235
6236 put_task_struct(p);
6237}
6238
6239/* release_task() removes task from tasklist, so we won't find dead tasks. */
6240static void migrate_dead_tasks(unsigned int dead_cpu)
6241{
6242 struct rq *rq = cpu_rq(dead_cpu);
6243 struct task_struct *next;
6244
6245 for ( ; ; ) {
6246 if (!rq->nr_running)
6247 break;
6248 update_rq_clock(rq);
6249 next = pick_next_task(rq, rq->curr);
6250 if (!next)
6251 break;
6252 migrate_dead(dead_cpu, next);
6253
6254 }
6255}
6256#endif /* CONFIG_HOTPLUG_CPU */
6257
6258#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6259
6260static struct ctl_table sd_ctl_dir[] = {
6261 {
6262 .procname = "sched_domain",
6263 .mode = 0555,
6264 },
6265 {0, },
6266};
6267
6268static struct ctl_table sd_ctl_root[] = {
6269 {
6270 .ctl_name = CTL_KERN,
6271 .procname = "kernel",
6272 .mode = 0555,
6273 .child = sd_ctl_dir,
6274 },
6275 {0, },
6276};
6277
6278static struct ctl_table *sd_alloc_ctl_entry(int n)
6279{
6280 struct ctl_table *entry =
6281 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6282
6283 return entry;
6284}
6285
6286static void sd_free_ctl_entry(struct ctl_table **tablep)
6287{
6288 struct ctl_table *entry;
6289
6290 /*
6291 * In the intermediate directories, both the child directory and
6292 * procname are dynamically allocated and could fail but the mode
6293 * will always be set. In the lowest directory the names are
6294 * static strings and all have proc handlers.
6295 */
6296 for (entry = *tablep; entry->mode; entry++) {
6297 if (entry->child)
6298 sd_free_ctl_entry(&entry->child);
6299 if (entry->proc_handler == NULL)
6300 kfree(entry->procname);
6301 }
6302
6303 kfree(*tablep);
6304 *tablep = NULL;
6305}
6306
6307static void
6308set_table_entry(struct ctl_table *entry,
6309 const char *procname, void *data, int maxlen,
6310 mode_t mode, proc_handler *proc_handler)
6311{
6312 entry->procname = procname;
6313 entry->data = data;
6314 entry->maxlen = maxlen;
6315 entry->mode = mode;
6316 entry->proc_handler = proc_handler;
6317}
6318
6319static struct ctl_table *
6320sd_alloc_ctl_domain_table(struct sched_domain *sd)
6321{
6322 struct ctl_table *table = sd_alloc_ctl_entry(12);
6323
6324 if (table == NULL)
6325 return NULL;
6326
6327 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6328 sizeof(long), 0644, proc_doulongvec_minmax);
6329 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6330 sizeof(long), 0644, proc_doulongvec_minmax);
6331 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6332 sizeof(int), 0644, proc_dointvec_minmax);
6333 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6334 sizeof(int), 0644, proc_dointvec_minmax);
6335 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6336 sizeof(int), 0644, proc_dointvec_minmax);
6337 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6338 sizeof(int), 0644, proc_dointvec_minmax);
6339 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6340 sizeof(int), 0644, proc_dointvec_minmax);
6341 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6342 sizeof(int), 0644, proc_dointvec_minmax);
6343 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6344 sizeof(int), 0644, proc_dointvec_minmax);
6345 set_table_entry(&table[9], "cache_nice_tries",
6346 &sd->cache_nice_tries,
6347 sizeof(int), 0644, proc_dointvec_minmax);
6348 set_table_entry(&table[10], "flags", &sd->flags,
6349 sizeof(int), 0644, proc_dointvec_minmax);
6350 /* &table[11] is terminator */
6351
6352 return table;
6353}
6354
6355static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6356{
6357 struct ctl_table *entry, *table;
6358 struct sched_domain *sd;
6359 int domain_num = 0, i;
6360 char buf[32];
6361
6362 for_each_domain(cpu, sd)
6363 domain_num++;
6364 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6365 if (table == NULL)
6366 return NULL;
6367
6368 i = 0;
6369 for_each_domain(cpu, sd) {
6370 snprintf(buf, 32, "domain%d", i);
6371 entry->procname = kstrdup(buf, GFP_KERNEL);
6372 entry->mode = 0555;
6373 entry->child = sd_alloc_ctl_domain_table(sd);
6374 entry++;
6375 i++;
6376 }
6377 return table;
6378}
6379
6380static struct ctl_table_header *sd_sysctl_header;
6381static void register_sched_domain_sysctl(void)
6382{
6383 int i, cpu_num = num_online_cpus();
6384 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6385 char buf[32];
6386
6387 WARN_ON(sd_ctl_dir[0].child);
6388 sd_ctl_dir[0].child = entry;
6389
6390 if (entry == NULL)
6391 return;
6392
6393 for_each_online_cpu(i) {
6394 snprintf(buf, 32, "cpu%d", i);
6395 entry->procname = kstrdup(buf, GFP_KERNEL);
6396 entry->mode = 0555;
6397 entry->child = sd_alloc_ctl_cpu_table(i);
6398 entry++;
6399 }
6400
6401 WARN_ON(sd_sysctl_header);
6402 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6403}
6404
6405/* may be called multiple times per register */
6406static void unregister_sched_domain_sysctl(void)
6407{
6408 if (sd_sysctl_header)
6409 unregister_sysctl_table(sd_sysctl_header);
6410 sd_sysctl_header = NULL;
6411 if (sd_ctl_dir[0].child)
6412 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6413}
6414#else
6415static void register_sched_domain_sysctl(void)
6416{
6417}
6418static void unregister_sched_domain_sysctl(void)
6419{
6420}
6421#endif
6422
6423/*
6424 * migration_call - callback that gets triggered when a CPU is added.
6425 * Here we can start up the necessary migration thread for the new CPU.
6426 */
6427static int __cpuinit
6428migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6429{
6430 struct task_struct *p;
6431 int cpu = (long)hcpu;
6432 unsigned long flags;
6433 struct rq *rq;
6434
6435 switch (action) {
6436
6437 case CPU_UP_PREPARE:
6438 case CPU_UP_PREPARE_FROZEN:
6439 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6440 if (IS_ERR(p))
6441 return NOTIFY_BAD;
6442 kthread_bind(p, cpu);
6443 /* Must be high prio: stop_machine expects to yield to it. */
6444 rq = task_rq_lock(p, &flags);
6445 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6446 task_rq_unlock(rq, &flags);
6447 cpu_rq(cpu)->migration_thread = p;
6448 break;
6449
6450 case CPU_ONLINE:
6451 case CPU_ONLINE_FROZEN:
6452 /* Strictly unnecessary, as first user will wake it. */
6453 wake_up_process(cpu_rq(cpu)->migration_thread);
6454
6455 /* Update our root-domain */
6456 rq = cpu_rq(cpu);
6457 spin_lock_irqsave(&rq->lock, flags);
6458 if (rq->rd) {
6459 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6460 cpu_set(cpu, rq->rd->online);
6461 }
6462 spin_unlock_irqrestore(&rq->lock, flags);
6463 break;
6464
6465#ifdef CONFIG_HOTPLUG_CPU
6466 case CPU_UP_CANCELED:
6467 case CPU_UP_CANCELED_FROZEN:
6468 if (!cpu_rq(cpu)->migration_thread)
6469 break;
6470 /* Unbind it from offline cpu so it can run. Fall thru. */
6471 kthread_bind(cpu_rq(cpu)->migration_thread,
6472 any_online_cpu(cpu_online_map));
6473 kthread_stop(cpu_rq(cpu)->migration_thread);
6474 cpu_rq(cpu)->migration_thread = NULL;
6475 break;
6476
6477 case CPU_DEAD:
6478 case CPU_DEAD_FROZEN:
6479 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6480 migrate_live_tasks(cpu);
6481 rq = cpu_rq(cpu);
6482 kthread_stop(rq->migration_thread);
6483 rq->migration_thread = NULL;
6484 /* Idle task back to normal (off runqueue, low prio) */
6485 spin_lock_irq(&rq->lock);
6486 update_rq_clock(rq);
6487 deactivate_task(rq, rq->idle, 0);
6488 rq->idle->static_prio = MAX_PRIO;
6489 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6490 rq->idle->sched_class = &idle_sched_class;
6491 migrate_dead_tasks(cpu);
6492 spin_unlock_irq(&rq->lock);
6493 cpuset_unlock();
6494 migrate_nr_uninterruptible(rq);
6495 BUG_ON(rq->nr_running != 0);
6496
6497 /*
6498 * No need to migrate the tasks: it was best-effort if
6499 * they didn't take sched_hotcpu_mutex. Just wake up
6500 * the requestors.
6501 */
6502 spin_lock_irq(&rq->lock);
6503 while (!list_empty(&rq->migration_queue)) {
6504 struct migration_req *req;
6505
6506 req = list_entry(rq->migration_queue.next,
6507 struct migration_req, list);
6508 list_del_init(&req->list);
6509 complete(&req->done);
6510 }
6511 spin_unlock_irq(&rq->lock);
6512 break;
6513
6514 case CPU_DYING:
6515 case CPU_DYING_FROZEN:
6516 /* Update our root-domain */
6517 rq = cpu_rq(cpu);
6518 spin_lock_irqsave(&rq->lock, flags);
6519 if (rq->rd) {
6520 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6521 cpu_clear(cpu, rq->rd->online);
6522 }
6523 spin_unlock_irqrestore(&rq->lock, flags);
6524 break;
6525#endif
6526 }
6527 return NOTIFY_OK;
6528}
6529
6530/* Register at highest priority so that task migration (migrate_all_tasks)
6531 * happens before everything else.
6532 */
6533static struct notifier_block __cpuinitdata migration_notifier = {
6534 .notifier_call = migration_call,
6535 .priority = 10
6536};
6537
6538void __init migration_init(void)
6539{
6540 void *cpu = (void *)(long)smp_processor_id();
6541 int err;
6542
6543 /* Start one for the boot CPU: */
6544 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6545 BUG_ON(err == NOTIFY_BAD);
6546 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6547 register_cpu_notifier(&migration_notifier);
6548}
6549#endif
6550
6551#ifdef CONFIG_SMP
6552
6553#ifdef CONFIG_SCHED_DEBUG
6554
6555static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6556 cpumask_t *groupmask)
6557{
6558 struct sched_group *group = sd->groups;
6559 char str[256];
6560
6561 cpulist_scnprintf(str, sizeof(str), sd->span);
6562 cpus_clear(*groupmask);
6563
6564 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6565
6566 if (!(sd->flags & SD_LOAD_BALANCE)) {
6567 printk("does not load-balance\n");
6568 if (sd->parent)
6569 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6570 " has parent");
6571 return -1;
6572 }
6573
6574 printk(KERN_CONT "span %s\n", str);
6575
6576 if (!cpu_isset(cpu, sd->span)) {
6577 printk(KERN_ERR "ERROR: domain->span does not contain "
6578 "CPU%d\n", cpu);
6579 }
6580 if (!cpu_isset(cpu, group->cpumask)) {
6581 printk(KERN_ERR "ERROR: domain->groups does not contain"
6582 " CPU%d\n", cpu);
6583 }
6584
6585 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6586 do {
6587 if (!group) {
6588 printk("\n");
6589 printk(KERN_ERR "ERROR: group is NULL\n");
6590 break;
6591 }
6592
6593 if (!group->__cpu_power) {
6594 printk(KERN_CONT "\n");
6595 printk(KERN_ERR "ERROR: domain->cpu_power not "
6596 "set\n");
6597 break;
6598 }
6599
6600 if (!cpus_weight(group->cpumask)) {
6601 printk(KERN_CONT "\n");
6602 printk(KERN_ERR "ERROR: empty group\n");
6603 break;
6604 }
6605
6606 if (cpus_intersects(*groupmask, group->cpumask)) {
6607 printk(KERN_CONT "\n");
6608 printk(KERN_ERR "ERROR: repeated CPUs\n");
6609 break;
6610 }
6611
6612 cpus_or(*groupmask, *groupmask, group->cpumask);
6613
6614 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6615 printk(KERN_CONT " %s", str);
6616
6617 group = group->next;
6618 } while (group != sd->groups);
6619 printk(KERN_CONT "\n");
6620
6621 if (!cpus_equal(sd->span, *groupmask))
6622 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6623
6624 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6625 printk(KERN_ERR "ERROR: parent span is not a superset "
6626 "of domain->span\n");
6627 return 0;
6628}
6629
6630static void sched_domain_debug(struct sched_domain *sd, int cpu)
6631{
6632 cpumask_t *groupmask;
6633 int level = 0;
6634
6635 if (!sd) {
6636 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6637 return;
6638 }
6639
6640 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6641
6642 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6643 if (!groupmask) {
6644 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6645 return;
6646 }
6647
6648 for (;;) {
6649 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6650 break;
6651 level++;
6652 sd = sd->parent;
6653 if (!sd)
6654 break;
6655 }
6656 kfree(groupmask);
6657}
6658#else
6659# define sched_domain_debug(sd, cpu) do { } while (0)
6660#endif
6661
6662static int sd_degenerate(struct sched_domain *sd)
6663{
6664 if (cpus_weight(sd->span) == 1)
6665 return 1;
6666
6667 /* Following flags need at least 2 groups */
6668 if (sd->flags & (SD_LOAD_BALANCE |
6669 SD_BALANCE_NEWIDLE |
6670 SD_BALANCE_FORK |
6671 SD_BALANCE_EXEC |
6672 SD_SHARE_CPUPOWER |
6673 SD_SHARE_PKG_RESOURCES)) {
6674 if (sd->groups != sd->groups->next)
6675 return 0;
6676 }
6677
6678 /* Following flags don't use groups */
6679 if (sd->flags & (SD_WAKE_IDLE |
6680 SD_WAKE_AFFINE |
6681 SD_WAKE_BALANCE))
6682 return 0;
6683
6684 return 1;
6685}
6686
6687static int
6688sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6689{
6690 unsigned long cflags = sd->flags, pflags = parent->flags;
6691
6692 if (sd_degenerate(parent))
6693 return 1;
6694
6695 if (!cpus_equal(sd->span, parent->span))
6696 return 0;
6697
6698 /* Does parent contain flags not in child? */
6699 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6700 if (cflags & SD_WAKE_AFFINE)
6701 pflags &= ~SD_WAKE_BALANCE;
6702 /* Flags needing groups don't count if only 1 group in parent */
6703 if (parent->groups == parent->groups->next) {
6704 pflags &= ~(SD_LOAD_BALANCE |
6705 SD_BALANCE_NEWIDLE |
6706 SD_BALANCE_FORK |
6707 SD_BALANCE_EXEC |
6708 SD_SHARE_CPUPOWER |
6709 SD_SHARE_PKG_RESOURCES);
6710 }
6711 if (~cflags & pflags)
6712 return 0;
6713
6714 return 1;
6715}
6716
6717static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6718{
6719 unsigned long flags;
6720 const struct sched_class *class;
6721
6722 spin_lock_irqsave(&rq->lock, flags);
6723
6724 if (rq->rd) {
6725 struct root_domain *old_rd = rq->rd;
6726
6727 for (class = sched_class_highest; class; class = class->next) {
6728 if (class->leave_domain)
6729 class->leave_domain(rq);
6730 }
6731
6732 cpu_clear(rq->cpu, old_rd->span);
6733 cpu_clear(rq->cpu, old_rd->online);
6734
6735 if (atomic_dec_and_test(&old_rd->refcount))
6736 kfree(old_rd);
6737 }
6738
6739 atomic_inc(&rd->refcount);
6740 rq->rd = rd;
6741
6742 cpu_set(rq->cpu, rd->span);
6743 if (cpu_isset(rq->cpu, cpu_online_map))
6744 cpu_set(rq->cpu, rd->online);
6745
6746 for (class = sched_class_highest; class; class = class->next) {
6747 if (class->join_domain)
6748 class->join_domain(rq);
6749 }
6750
6751 spin_unlock_irqrestore(&rq->lock, flags);
6752}
6753
6754static void init_rootdomain(struct root_domain *rd)
6755{
6756 memset(rd, 0, sizeof(*rd));
6757
6758 cpus_clear(rd->span);
6759 cpus_clear(rd->online);
6760}
6761
6762static void init_defrootdomain(void)
6763{
6764 init_rootdomain(&def_root_domain);
6765 atomic_set(&def_root_domain.refcount, 1);
6766}
6767
6768static struct root_domain *alloc_rootdomain(void)
6769{
6770 struct root_domain *rd;
6771
6772 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6773 if (!rd)
6774 return NULL;
6775
6776 init_rootdomain(rd);
6777
6778 return rd;
6779}
6780
6781/*
6782 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6783 * hold the hotplug lock.
6784 */
6785static void
6786cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6787{
6788 struct rq *rq = cpu_rq(cpu);
6789 struct sched_domain *tmp;
6790
6791 /* Remove the sched domains which do not contribute to scheduling. */
6792 for (tmp = sd; tmp; tmp = tmp->parent) {
6793 struct sched_domain *parent = tmp->parent;
6794 if (!parent)
6795 break;
6796 if (sd_parent_degenerate(tmp, parent)) {
6797 tmp->parent = parent->parent;
6798 if (parent->parent)
6799 parent->parent->child = tmp;
6800 }
6801 }
6802
6803 if (sd && sd_degenerate(sd)) {
6804 sd = sd->parent;
6805 if (sd)
6806 sd->child = NULL;
6807 }
6808
6809 sched_domain_debug(sd, cpu);
6810
6811 rq_attach_root(rq, rd);
6812 rcu_assign_pointer(rq->sd, sd);
6813}
6814
6815/* cpus with isolated domains */
6816static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6817
6818/* Setup the mask of cpus configured for isolated domains */
6819static int __init isolated_cpu_setup(char *str)
6820{
6821 int ints[NR_CPUS], i;
6822
6823 str = get_options(str, ARRAY_SIZE(ints), ints);
6824 cpus_clear(cpu_isolated_map);
6825 for (i = 1; i <= ints[0]; i++)
6826 if (ints[i] < NR_CPUS)
6827 cpu_set(ints[i], cpu_isolated_map);
6828 return 1;
6829}
6830
6831__setup("isolcpus=", isolated_cpu_setup);
6832
6833/*
6834 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6835 * to a function which identifies what group(along with sched group) a CPU
6836 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6837 * (due to the fact that we keep track of groups covered with a cpumask_t).
6838 *
6839 * init_sched_build_groups will build a circular linked list of the groups
6840 * covered by the given span, and will set each group's ->cpumask correctly,
6841 * and ->cpu_power to 0.
6842 */
6843static void
6844init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6845 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6846 struct sched_group **sg,
6847 cpumask_t *tmpmask),
6848 cpumask_t *covered, cpumask_t *tmpmask)
6849{
6850 struct sched_group *first = NULL, *last = NULL;
6851 int i;
6852
6853 cpus_clear(*covered);
6854
6855 for_each_cpu_mask(i, *span) {
6856 struct sched_group *sg;
6857 int group = group_fn(i, cpu_map, &sg, tmpmask);
6858 int j;
6859
6860 if (cpu_isset(i, *covered))
6861 continue;
6862
6863 cpus_clear(sg->cpumask);
6864 sg->__cpu_power = 0;
6865
6866 for_each_cpu_mask(j, *span) {
6867 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6868 continue;
6869
6870 cpu_set(j, *covered);
6871 cpu_set(j, sg->cpumask);
6872 }
6873 if (!first)
6874 first = sg;
6875 if (last)
6876 last->next = sg;
6877 last = sg;
6878 }
6879 last->next = first;
6880}
6881
6882#define SD_NODES_PER_DOMAIN 16
6883
6884#ifdef CONFIG_NUMA
6885
6886/**
6887 * find_next_best_node - find the next node to include in a sched_domain
6888 * @node: node whose sched_domain we're building
6889 * @used_nodes: nodes already in the sched_domain
6890 *
6891 * Find the next node to include in a given scheduling domain. Simply
6892 * finds the closest node not already in the @used_nodes map.
6893 *
6894 * Should use nodemask_t.
6895 */
6896static int find_next_best_node(int node, nodemask_t *used_nodes)
6897{
6898 int i, n, val, min_val, best_node = 0;
6899
6900 min_val = INT_MAX;
6901
6902 for (i = 0; i < MAX_NUMNODES; i++) {
6903 /* Start at @node */
6904 n = (node + i) % MAX_NUMNODES;
6905
6906 if (!nr_cpus_node(n))
6907 continue;
6908
6909 /* Skip already used nodes */
6910 if (node_isset(n, *used_nodes))
6911 continue;
6912
6913 /* Simple min distance search */
6914 val = node_distance(node, n);
6915
6916 if (val < min_val) {
6917 min_val = val;
6918 best_node = n;
6919 }
6920 }
6921
6922 node_set(best_node, *used_nodes);
6923 return best_node;
6924}
6925
6926/**
6927 * sched_domain_node_span - get a cpumask for a node's sched_domain
6928 * @node: node whose cpumask we're constructing
6929 *
6930 * Given a node, construct a good cpumask for its sched_domain to span. It
6931 * should be one that prevents unnecessary balancing, but also spreads tasks
6932 * out optimally.
6933 */
6934static void sched_domain_node_span(int node, cpumask_t *span)
6935{
6936 nodemask_t used_nodes;
6937 node_to_cpumask_ptr(nodemask, node);
6938 int i;
6939
6940 cpus_clear(*span);
6941 nodes_clear(used_nodes);
6942
6943 cpus_or(*span, *span, *nodemask);
6944 node_set(node, used_nodes);
6945
6946 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6947 int next_node = find_next_best_node(node, &used_nodes);
6948
6949 node_to_cpumask_ptr_next(nodemask, next_node);
6950 cpus_or(*span, *span, *nodemask);
6951 }
6952}
6953#endif
6954
6955int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6956
6957/*
6958 * SMT sched-domains:
6959 */
6960#ifdef CONFIG_SCHED_SMT
6961static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6962static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6963
6964static int
6965cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6966 cpumask_t *unused)
6967{
6968 if (sg)
6969 *sg = &per_cpu(sched_group_cpus, cpu);
6970 return cpu;
6971}
6972#endif
6973
6974/*
6975 * multi-core sched-domains:
6976 */
6977#ifdef CONFIG_SCHED_MC
6978static DEFINE_PER_CPU(struct sched_domain, core_domains);
6979static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6980#endif
6981
6982#if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6983static int
6984cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6985 cpumask_t *mask)
6986{
6987 int group;
6988
6989 *mask = per_cpu(cpu_sibling_map, cpu);
6990 cpus_and(*mask, *mask, *cpu_map);
6991 group = first_cpu(*mask);
6992 if (sg)
6993 *sg = &per_cpu(sched_group_core, group);
6994 return group;
6995}
6996#elif defined(CONFIG_SCHED_MC)
6997static int
6998cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6999 cpumask_t *unused)
7000{
7001 if (sg)
7002 *sg = &per_cpu(sched_group_core, cpu);
7003 return cpu;
7004}
7005#endif
7006
7007static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7008static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7009
7010static int
7011cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7012 cpumask_t *mask)
7013{
7014 int group;
7015#ifdef CONFIG_SCHED_MC
7016 *mask = cpu_coregroup_map(cpu);
7017 cpus_and(*mask, *mask, *cpu_map);
7018 group = first_cpu(*mask);
7019#elif defined(CONFIG_SCHED_SMT)
7020 *mask = per_cpu(cpu_sibling_map, cpu);
7021 cpus_and(*mask, *mask, *cpu_map);
7022 group = first_cpu(*mask);
7023#else
7024 group = cpu;
7025#endif
7026 if (sg)
7027 *sg = &per_cpu(sched_group_phys, group);
7028 return group;
7029}
7030
7031#ifdef CONFIG_NUMA
7032/*
7033 * The init_sched_build_groups can't handle what we want to do with node
7034 * groups, so roll our own. Now each node has its own list of groups which
7035 * gets dynamically allocated.
7036 */
7037static DEFINE_PER_CPU(struct sched_domain, node_domains);
7038static struct sched_group ***sched_group_nodes_bycpu;
7039
7040static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7041static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7042
7043static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7044 struct sched_group **sg, cpumask_t *nodemask)
7045{
7046 int group;
7047
7048 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7049 cpus_and(*nodemask, *nodemask, *cpu_map);
7050 group = first_cpu(*nodemask);
7051
7052 if (sg)
7053 *sg = &per_cpu(sched_group_allnodes, group);
7054 return group;
7055}
7056
7057static void init_numa_sched_groups_power(struct sched_group *group_head)
7058{
7059 struct sched_group *sg = group_head;
7060 int j;
7061
7062 if (!sg)
7063 return;
7064 do {
7065 for_each_cpu_mask(j, sg->cpumask) {
7066 struct sched_domain *sd;
7067
7068 sd = &per_cpu(phys_domains, j);
7069 if (j != first_cpu(sd->groups->cpumask)) {
7070 /*
7071 * Only add "power" once for each
7072 * physical package.
7073 */
7074 continue;
7075 }
7076
7077 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7078 }
7079 sg = sg->next;
7080 } while (sg != group_head);
7081}
7082#endif
7083
7084#ifdef CONFIG_NUMA
7085/* Free memory allocated for various sched_group structures */
7086static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7087{
7088 int cpu, i;
7089
7090 for_each_cpu_mask(cpu, *cpu_map) {
7091 struct sched_group **sched_group_nodes
7092 = sched_group_nodes_bycpu[cpu];
7093
7094 if (!sched_group_nodes)
7095 continue;
7096
7097 for (i = 0; i < MAX_NUMNODES; i++) {
7098 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7099
7100 *nodemask = node_to_cpumask(i);
7101 cpus_and(*nodemask, *nodemask, *cpu_map);
7102 if (cpus_empty(*nodemask))
7103 continue;
7104
7105 if (sg == NULL)
7106 continue;
7107 sg = sg->next;
7108next_sg:
7109 oldsg = sg;
7110 sg = sg->next;
7111 kfree(oldsg);
7112 if (oldsg != sched_group_nodes[i])
7113 goto next_sg;
7114 }
7115 kfree(sched_group_nodes);
7116 sched_group_nodes_bycpu[cpu] = NULL;
7117 }
7118}
7119#else
7120static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7121{
7122}
7123#endif
7124
7125/*
7126 * Initialize sched groups cpu_power.
7127 *
7128 * cpu_power indicates the capacity of sched group, which is used while
7129 * distributing the load between different sched groups in a sched domain.
7130 * Typically cpu_power for all the groups in a sched domain will be same unless
7131 * there are asymmetries in the topology. If there are asymmetries, group
7132 * having more cpu_power will pickup more load compared to the group having
7133 * less cpu_power.
7134 *
7135 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7136 * the maximum number of tasks a group can handle in the presence of other idle
7137 * or lightly loaded groups in the same sched domain.
7138 */
7139static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7140{
7141 struct sched_domain *child;
7142 struct sched_group *group;
7143
7144 WARN_ON(!sd || !sd->groups);
7145
7146 if (cpu != first_cpu(sd->groups->cpumask))
7147 return;
7148
7149 child = sd->child;
7150
7151 sd->groups->__cpu_power = 0;
7152
7153 /*
7154 * For perf policy, if the groups in child domain share resources
7155 * (for example cores sharing some portions of the cache hierarchy
7156 * or SMT), then set this domain groups cpu_power such that each group
7157 * can handle only one task, when there are other idle groups in the
7158 * same sched domain.
7159 */
7160 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7161 (child->flags &
7162 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7163 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7164 return;
7165 }
7166
7167 /*
7168 * add cpu_power of each child group to this groups cpu_power
7169 */
7170 group = child->groups;
7171 do {
7172 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7173 group = group->next;
7174 } while (group != child->groups);
7175}
7176
7177/*
7178 * Initializers for schedule domains
7179 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7180 */
7181
7182#define SD_INIT(sd, type) sd_init_##type(sd)
7183#define SD_INIT_FUNC(type) \
7184static noinline void sd_init_##type(struct sched_domain *sd) \
7185{ \
7186 memset(sd, 0, sizeof(*sd)); \
7187 *sd = SD_##type##_INIT; \
7188 sd->level = SD_LV_##type; \
7189}
7190
7191SD_INIT_FUNC(CPU)
7192#ifdef CONFIG_NUMA
7193 SD_INIT_FUNC(ALLNODES)
7194 SD_INIT_FUNC(NODE)
7195#endif
7196#ifdef CONFIG_SCHED_SMT
7197 SD_INIT_FUNC(SIBLING)
7198#endif
7199#ifdef CONFIG_SCHED_MC
7200 SD_INIT_FUNC(MC)
7201#endif
7202
7203/*
7204 * To minimize stack usage kmalloc room for cpumasks and share the
7205 * space as the usage in build_sched_domains() dictates. Used only
7206 * if the amount of space is significant.
7207 */
7208struct allmasks {
7209 cpumask_t tmpmask; /* make this one first */
7210 union {
7211 cpumask_t nodemask;
7212 cpumask_t this_sibling_map;
7213 cpumask_t this_core_map;
7214 };
7215 cpumask_t send_covered;
7216
7217#ifdef CONFIG_NUMA
7218 cpumask_t domainspan;
7219 cpumask_t covered;
7220 cpumask_t notcovered;
7221#endif
7222};
7223
7224#if NR_CPUS > 128
7225#define SCHED_CPUMASK_ALLOC 1
7226#define SCHED_CPUMASK_FREE(v) kfree(v)
7227#define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7228#else
7229#define SCHED_CPUMASK_ALLOC 0
7230#define SCHED_CPUMASK_FREE(v)
7231#define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7232#endif
7233
7234#define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7235 ((unsigned long)(a) + offsetof(struct allmasks, v))
7236
7237static int default_relax_domain_level = -1;
7238
7239static int __init setup_relax_domain_level(char *str)
7240{
7241 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7242 return 1;
7243}
7244__setup("relax_domain_level=", setup_relax_domain_level);
7245
7246static void set_domain_attribute(struct sched_domain *sd,
7247 struct sched_domain_attr *attr)
7248{
7249 int request;
7250
7251 if (!attr || attr->relax_domain_level < 0) {
7252 if (default_relax_domain_level < 0)
7253 return;
7254 else
7255 request = default_relax_domain_level;
7256 } else
7257 request = attr->relax_domain_level;
7258 if (request < sd->level) {
7259 /* turn off idle balance on this domain */
7260 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7261 } else {
7262 /* turn on idle balance on this domain */
7263 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7264 }
7265}
7266
7267/*
7268 * Build sched domains for a given set of cpus and attach the sched domains
7269 * to the individual cpus
7270 */
7271static int __build_sched_domains(const cpumask_t *cpu_map,
7272 struct sched_domain_attr *attr)
7273{
7274 int i;
7275 struct root_domain *rd;
7276 SCHED_CPUMASK_DECLARE(allmasks);
7277 cpumask_t *tmpmask;
7278#ifdef CONFIG_NUMA
7279 struct sched_group **sched_group_nodes = NULL;
7280 int sd_allnodes = 0;
7281
7282 /*
7283 * Allocate the per-node list of sched groups
7284 */
7285 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7286 GFP_KERNEL);
7287 if (!sched_group_nodes) {
7288 printk(KERN_WARNING "Can not alloc sched group node list\n");
7289 return -ENOMEM;
7290 }
7291#endif
7292
7293 rd = alloc_rootdomain();
7294 if (!rd) {
7295 printk(KERN_WARNING "Cannot alloc root domain\n");
7296#ifdef CONFIG_NUMA
7297 kfree(sched_group_nodes);
7298#endif
7299 return -ENOMEM;
7300 }
7301
7302#if SCHED_CPUMASK_ALLOC
7303 /* get space for all scratch cpumask variables */
7304 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7305 if (!allmasks) {
7306 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7307 kfree(rd);
7308#ifdef CONFIG_NUMA
7309 kfree(sched_group_nodes);
7310#endif
7311 return -ENOMEM;
7312 }
7313#endif
7314 tmpmask = (cpumask_t *)allmasks;
7315
7316
7317#ifdef CONFIG_NUMA
7318 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7319#endif
7320
7321 /*
7322 * Set up domains for cpus specified by the cpu_map.
7323 */
7324 for_each_cpu_mask(i, *cpu_map) {
7325 struct sched_domain *sd = NULL, *p;
7326 SCHED_CPUMASK_VAR(nodemask, allmasks);
7327
7328 *nodemask = node_to_cpumask(cpu_to_node(i));
7329 cpus_and(*nodemask, *nodemask, *cpu_map);
7330
7331#ifdef CONFIG_NUMA
7332 if (cpus_weight(*cpu_map) >
7333 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7334 sd = &per_cpu(allnodes_domains, i);
7335 SD_INIT(sd, ALLNODES);
7336 set_domain_attribute(sd, attr);
7337 sd->span = *cpu_map;
7338 sd->first_cpu = first_cpu(sd->span);
7339 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7340 p = sd;
7341 sd_allnodes = 1;
7342 } else
7343 p = NULL;
7344
7345 sd = &per_cpu(node_domains, i);
7346 SD_INIT(sd, NODE);
7347 set_domain_attribute(sd, attr);
7348 sched_domain_node_span(cpu_to_node(i), &sd->span);
7349 sd->first_cpu = first_cpu(sd->span);
7350 sd->parent = p;
7351 if (p)
7352 p->child = sd;
7353 cpus_and(sd->span, sd->span, *cpu_map);
7354#endif
7355
7356 p = sd;
7357 sd = &per_cpu(phys_domains, i);
7358 SD_INIT(sd, CPU);
7359 set_domain_attribute(sd, attr);
7360 sd->span = *nodemask;
7361 sd->first_cpu = first_cpu(sd->span);
7362 sd->parent = p;
7363 if (p)
7364 p->child = sd;
7365 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7366
7367#ifdef CONFIG_SCHED_MC
7368 p = sd;
7369 sd = &per_cpu(core_domains, i);
7370 SD_INIT(sd, MC);
7371 set_domain_attribute(sd, attr);
7372 sd->span = cpu_coregroup_map(i);
7373 sd->first_cpu = first_cpu(sd->span);
7374 cpus_and(sd->span, sd->span, *cpu_map);
7375 sd->parent = p;
7376 p->child = sd;
7377 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7378#endif
7379
7380#ifdef CONFIG_SCHED_SMT
7381 p = sd;
7382 sd = &per_cpu(cpu_domains, i);
7383 SD_INIT(sd, SIBLING);
7384 set_domain_attribute(sd, attr);
7385 sd->span = per_cpu(cpu_sibling_map, i);
7386 sd->first_cpu = first_cpu(sd->span);
7387 cpus_and(sd->span, sd->span, *cpu_map);
7388 sd->parent = p;
7389 p->child = sd;
7390 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7391#endif
7392 }
7393
7394#ifdef CONFIG_SCHED_SMT
7395 /* Set up CPU (sibling) groups */
7396 for_each_cpu_mask(i, *cpu_map) {
7397 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7398 SCHED_CPUMASK_VAR(send_covered, allmasks);
7399
7400 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7401 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7402 if (i != first_cpu(*this_sibling_map))
7403 continue;
7404
7405 init_sched_build_groups(this_sibling_map, cpu_map,
7406 &cpu_to_cpu_group,
7407 send_covered, tmpmask);
7408 }
7409#endif
7410
7411#ifdef CONFIG_SCHED_MC
7412 /* Set up multi-core groups */
7413 for_each_cpu_mask(i, *cpu_map) {
7414 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7415 SCHED_CPUMASK_VAR(send_covered, allmasks);
7416
7417 *this_core_map = cpu_coregroup_map(i);
7418 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7419 if (i != first_cpu(*this_core_map))
7420 continue;
7421
7422 init_sched_build_groups(this_core_map, cpu_map,
7423 &cpu_to_core_group,
7424 send_covered, tmpmask);
7425 }
7426#endif
7427
7428 /* Set up physical groups */
7429 for (i = 0; i < MAX_NUMNODES; i++) {
7430 SCHED_CPUMASK_VAR(nodemask, allmasks);
7431 SCHED_CPUMASK_VAR(send_covered, allmasks);
7432
7433 *nodemask = node_to_cpumask(i);
7434 cpus_and(*nodemask, *nodemask, *cpu_map);
7435 if (cpus_empty(*nodemask))
7436 continue;
7437
7438 init_sched_build_groups(nodemask, cpu_map,
7439 &cpu_to_phys_group,
7440 send_covered, tmpmask);
7441 }
7442
7443#ifdef CONFIG_NUMA
7444 /* Set up node groups */
7445 if (sd_allnodes) {
7446 SCHED_CPUMASK_VAR(send_covered, allmasks);
7447
7448 init_sched_build_groups(cpu_map, cpu_map,
7449 &cpu_to_allnodes_group,
7450 send_covered, tmpmask);
7451 }
7452
7453 for (i = 0; i < MAX_NUMNODES; i++) {
7454 /* Set up node groups */
7455 struct sched_group *sg, *prev;
7456 SCHED_CPUMASK_VAR(nodemask, allmasks);
7457 SCHED_CPUMASK_VAR(domainspan, allmasks);
7458 SCHED_CPUMASK_VAR(covered, allmasks);
7459 int j;
7460
7461 *nodemask = node_to_cpumask(i);
7462 cpus_clear(*covered);
7463
7464 cpus_and(*nodemask, *nodemask, *cpu_map);
7465 if (cpus_empty(*nodemask)) {
7466 sched_group_nodes[i] = NULL;
7467 continue;
7468 }
7469
7470 sched_domain_node_span(i, domainspan);
7471 cpus_and(*domainspan, *domainspan, *cpu_map);
7472
7473 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7474 if (!sg) {
7475 printk(KERN_WARNING "Can not alloc domain group for "
7476 "node %d\n", i);
7477 goto error;
7478 }
7479 sched_group_nodes[i] = sg;
7480 for_each_cpu_mask(j, *nodemask) {
7481 struct sched_domain *sd;
7482
7483 sd = &per_cpu(node_domains, j);
7484 sd->groups = sg;
7485 }
7486 sg->__cpu_power = 0;
7487 sg->cpumask = *nodemask;
7488 sg->next = sg;
7489 cpus_or(*covered, *covered, *nodemask);
7490 prev = sg;
7491
7492 for (j = 0; j < MAX_NUMNODES; j++) {
7493 SCHED_CPUMASK_VAR(notcovered, allmasks);
7494 int n = (i + j) % MAX_NUMNODES;
7495 node_to_cpumask_ptr(pnodemask, n);
7496
7497 cpus_complement(*notcovered, *covered);
7498 cpus_and(*tmpmask, *notcovered, *cpu_map);
7499 cpus_and(*tmpmask, *tmpmask, *domainspan);
7500 if (cpus_empty(*tmpmask))
7501 break;
7502
7503 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7504 if (cpus_empty(*tmpmask))
7505 continue;
7506
7507 sg = kmalloc_node(sizeof(struct sched_group),
7508 GFP_KERNEL, i);
7509 if (!sg) {
7510 printk(KERN_WARNING
7511 "Can not alloc domain group for node %d\n", j);
7512 goto error;
7513 }
7514 sg->__cpu_power = 0;
7515 sg->cpumask = *tmpmask;
7516 sg->next = prev->next;
7517 cpus_or(*covered, *covered, *tmpmask);
7518 prev->next = sg;
7519 prev = sg;
7520 }
7521 }
7522#endif
7523
7524 /* Calculate CPU power for physical packages and nodes */
7525#ifdef CONFIG_SCHED_SMT
7526 for_each_cpu_mask(i, *cpu_map) {
7527 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7528
7529 init_sched_groups_power(i, sd);
7530 }
7531#endif
7532#ifdef CONFIG_SCHED_MC
7533 for_each_cpu_mask(i, *cpu_map) {
7534 struct sched_domain *sd = &per_cpu(core_domains, i);
7535
7536 init_sched_groups_power(i, sd);
7537 }
7538#endif
7539
7540 for_each_cpu_mask(i, *cpu_map) {
7541 struct sched_domain *sd = &per_cpu(phys_domains, i);
7542
7543 init_sched_groups_power(i, sd);
7544 }
7545
7546#ifdef CONFIG_NUMA
7547 for (i = 0; i < MAX_NUMNODES; i++)
7548 init_numa_sched_groups_power(sched_group_nodes[i]);
7549
7550 if (sd_allnodes) {
7551 struct sched_group *sg;
7552
7553 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7554 tmpmask);
7555 init_numa_sched_groups_power(sg);
7556 }
7557#endif
7558
7559 /* Attach the domains */
7560 for_each_cpu_mask(i, *cpu_map) {
7561 struct sched_domain *sd;
7562#ifdef CONFIG_SCHED_SMT
7563 sd = &per_cpu(cpu_domains, i);
7564#elif defined(CONFIG_SCHED_MC)
7565 sd = &per_cpu(core_domains, i);
7566#else
7567 sd = &per_cpu(phys_domains, i);
7568#endif
7569 cpu_attach_domain(sd, rd, i);
7570 }
7571
7572 SCHED_CPUMASK_FREE((void *)allmasks);
7573 return 0;
7574
7575#ifdef CONFIG_NUMA
7576error:
7577 free_sched_groups(cpu_map, tmpmask);
7578 SCHED_CPUMASK_FREE((void *)allmasks);
7579 return -ENOMEM;
7580#endif
7581}
7582
7583static int build_sched_domains(const cpumask_t *cpu_map)
7584{
7585 return __build_sched_domains(cpu_map, NULL);
7586}
7587
7588static cpumask_t *doms_cur; /* current sched domains */
7589static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7590static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7591 in 'doms_cur' */
7592
7593/*
7594 * Special case: If a kmalloc of a doms_cur partition (array of
7595 * cpumask_t) fails, then fallback to a single sched domain,
7596 * as determined by the single cpumask_t fallback_doms.
7597 */
7598static cpumask_t fallback_doms;
7599
7600void __attribute__((weak)) arch_update_cpu_topology(void)
7601{
7602}
7603
7604/*
7605 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7606 * For now this just excludes isolated cpus, but could be used to
7607 * exclude other special cases in the future.
7608 */
7609static int arch_init_sched_domains(const cpumask_t *cpu_map)
7610{
7611 int err;
7612
7613 arch_update_cpu_topology();
7614 ndoms_cur = 1;
7615 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7616 if (!doms_cur)
7617 doms_cur = &fallback_doms;
7618 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7619 dattr_cur = NULL;
7620 err = build_sched_domains(doms_cur);
7621 register_sched_domain_sysctl();
7622
7623 return err;
7624}
7625
7626static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7627 cpumask_t *tmpmask)
7628{
7629 free_sched_groups(cpu_map, tmpmask);
7630}
7631
7632/*
7633 * Detach sched domains from a group of cpus specified in cpu_map
7634 * These cpus will now be attached to the NULL domain
7635 */
7636static void detach_destroy_domains(const cpumask_t *cpu_map)
7637{
7638 cpumask_t tmpmask;
7639 int i;
7640
7641 unregister_sched_domain_sysctl();
7642
7643 for_each_cpu_mask(i, *cpu_map)
7644 cpu_attach_domain(NULL, &def_root_domain, i);
7645 synchronize_sched();
7646 arch_destroy_sched_domains(cpu_map, &tmpmask);
7647}
7648
7649/* handle null as "default" */
7650static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7651 struct sched_domain_attr *new, int idx_new)
7652{
7653 struct sched_domain_attr tmp;
7654
7655 /* fast path */
7656 if (!new && !cur)
7657 return 1;
7658
7659 tmp = SD_ATTR_INIT;
7660 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7661 new ? (new + idx_new) : &tmp,
7662 sizeof(struct sched_domain_attr));
7663}
7664
7665/*
7666 * Partition sched domains as specified by the 'ndoms_new'
7667 * cpumasks in the array doms_new[] of cpumasks. This compares
7668 * doms_new[] to the current sched domain partitioning, doms_cur[].
7669 * It destroys each deleted domain and builds each new domain.
7670 *
7671 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7672 * The masks don't intersect (don't overlap.) We should setup one
7673 * sched domain for each mask. CPUs not in any of the cpumasks will
7674 * not be load balanced. If the same cpumask appears both in the
7675 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7676 * it as it is.
7677 *
7678 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7679 * ownership of it and will kfree it when done with it. If the caller
7680 * failed the kmalloc call, then it can pass in doms_new == NULL,
7681 * and partition_sched_domains() will fallback to the single partition
7682 * 'fallback_doms'.
7683 *
7684 * Call with hotplug lock held
7685 */
7686void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7687 struct sched_domain_attr *dattr_new)
7688{
7689 int i, j;
7690
7691 lock_doms_cur();
7692
7693 /* always unregister in case we don't destroy any domains */
7694 unregister_sched_domain_sysctl();
7695
7696 if (doms_new == NULL) {
7697 ndoms_new = 1;
7698 doms_new = &fallback_doms;
7699 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7700 dattr_new = NULL;
7701 }
7702
7703 /* Destroy deleted domains */
7704 for (i = 0; i < ndoms_cur; i++) {
7705 for (j = 0; j < ndoms_new; j++) {
7706 if (cpus_equal(doms_cur[i], doms_new[j])
7707 && dattrs_equal(dattr_cur, i, dattr_new, j))
7708 goto match1;
7709 }
7710 /* no match - a current sched domain not in new doms_new[] */
7711 detach_destroy_domains(doms_cur + i);
7712match1:
7713 ;
7714 }
7715
7716 /* Build new domains */
7717 for (i = 0; i < ndoms_new; i++) {
7718 for (j = 0; j < ndoms_cur; j++) {
7719 if (cpus_equal(doms_new[i], doms_cur[j])
7720 && dattrs_equal(dattr_new, i, dattr_cur, j))
7721 goto match2;
7722 }
7723 /* no match - add a new doms_new */
7724 __build_sched_domains(doms_new + i,
7725 dattr_new ? dattr_new + i : NULL);
7726match2:
7727 ;
7728 }
7729
7730 /* Remember the new sched domains */
7731 if (doms_cur != &fallback_doms)
7732 kfree(doms_cur);
7733 kfree(dattr_cur); /* kfree(NULL) is safe */
7734 doms_cur = doms_new;
7735 dattr_cur = dattr_new;
7736 ndoms_cur = ndoms_new;
7737
7738 register_sched_domain_sysctl();
7739
7740 unlock_doms_cur();
7741}
7742
7743#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7744int arch_reinit_sched_domains(void)
7745{
7746 int err;
7747
7748 get_online_cpus();
7749 detach_destroy_domains(&cpu_online_map);
7750 err = arch_init_sched_domains(&cpu_online_map);
7751 put_online_cpus();
7752
7753 return err;
7754}
7755
7756static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7757{
7758 int ret;
7759
7760 if (buf[0] != '0' && buf[0] != '1')
7761 return -EINVAL;
7762
7763 if (smt)
7764 sched_smt_power_savings = (buf[0] == '1');
7765 else
7766 sched_mc_power_savings = (buf[0] == '1');
7767
7768 ret = arch_reinit_sched_domains();
7769
7770 return ret ? ret : count;
7771}
7772
7773#ifdef CONFIG_SCHED_MC
7774static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7775{
7776 return sprintf(page, "%u\n", sched_mc_power_savings);
7777}
7778static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7779 const char *buf, size_t count)
7780{
7781 return sched_power_savings_store(buf, count, 0);
7782}
7783static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7784 sched_mc_power_savings_store);
7785#endif
7786
7787#ifdef CONFIG_SCHED_SMT
7788static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7789{
7790 return sprintf(page, "%u\n", sched_smt_power_savings);
7791}
7792static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7793 const char *buf, size_t count)
7794{
7795 return sched_power_savings_store(buf, count, 1);
7796}
7797static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7798 sched_smt_power_savings_store);
7799#endif
7800
7801int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7802{
7803 int err = 0;
7804
7805#ifdef CONFIG_SCHED_SMT
7806 if (smt_capable())
7807 err = sysfs_create_file(&cls->kset.kobj,
7808 &attr_sched_smt_power_savings.attr);
7809#endif
7810#ifdef CONFIG_SCHED_MC
7811 if (!err && mc_capable())
7812 err = sysfs_create_file(&cls->kset.kobj,
7813 &attr_sched_mc_power_savings.attr);
7814#endif
7815 return err;
7816}
7817#endif
7818
7819/*
7820 * Force a reinitialization of the sched domains hierarchy. The domains
7821 * and groups cannot be updated in place without racing with the balancing
7822 * code, so we temporarily attach all running cpus to the NULL domain
7823 * which will prevent rebalancing while the sched domains are recalculated.
7824 */
7825static int update_sched_domains(struct notifier_block *nfb,
7826 unsigned long action, void *hcpu)
7827{
7828 switch (action) {
7829 case CPU_UP_PREPARE:
7830 case CPU_UP_PREPARE_FROZEN:
7831 case CPU_DOWN_PREPARE:
7832 case CPU_DOWN_PREPARE_FROZEN:
7833 detach_destroy_domains(&cpu_online_map);
7834 return NOTIFY_OK;
7835
7836 case CPU_UP_CANCELED:
7837 case CPU_UP_CANCELED_FROZEN:
7838 case CPU_DOWN_FAILED:
7839 case CPU_DOWN_FAILED_FROZEN:
7840 case CPU_ONLINE:
7841 case CPU_ONLINE_FROZEN:
7842 case CPU_DEAD:
7843 case CPU_DEAD_FROZEN:
7844 /*
7845 * Fall through and re-initialise the domains.
7846 */
7847 break;
7848 default:
7849 return NOTIFY_DONE;
7850 }
7851
7852 /* The hotplug lock is already held by cpu_up/cpu_down */
7853 arch_init_sched_domains(&cpu_online_map);
7854
7855 return NOTIFY_OK;
7856}
7857
7858void __init sched_init_smp(void)
7859{
7860 cpumask_t non_isolated_cpus;
7861
7862#if defined(CONFIG_NUMA)
7863 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7864 GFP_KERNEL);
7865 BUG_ON(sched_group_nodes_bycpu == NULL);
7866#endif
7867 get_online_cpus();
7868 arch_init_sched_domains(&cpu_online_map);
7869 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7870 if (cpus_empty(non_isolated_cpus))
7871 cpu_set(smp_processor_id(), non_isolated_cpus);
7872 put_online_cpus();
7873 /* XXX: Theoretical race here - CPU may be hotplugged now */
7874 hotcpu_notifier(update_sched_domains, 0);
7875
7876 /* Move init over to a non-isolated CPU */
7877 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7878 BUG();
7879 sched_init_granularity();
7880}
7881#else
7882void __init sched_init_smp(void)
7883{
7884#if defined(CONFIG_NUMA)
7885 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7886 GFP_KERNEL);
7887 BUG_ON(sched_group_nodes_bycpu == NULL);
7888#endif
7889 sched_init_granularity();
7890}
7891#endif /* CONFIG_SMP */
7892
7893int in_sched_functions(unsigned long addr)
7894{
7895 return in_lock_functions(addr) ||
7896 (addr >= (unsigned long)__sched_text_start
7897 && addr < (unsigned long)__sched_text_end);
7898}
7899
7900static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7901{
7902 cfs_rq->tasks_timeline = RB_ROOT;
7903 INIT_LIST_HEAD(&cfs_rq->tasks);
7904#ifdef CONFIG_FAIR_GROUP_SCHED
7905 cfs_rq->rq = rq;
7906#endif
7907 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7908}
7909
7910static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7911{
7912 struct rt_prio_array *array;
7913 int i;
7914
7915 array = &rt_rq->active;
7916 for (i = 0; i < MAX_RT_PRIO; i++) {
7917 INIT_LIST_HEAD(array->queue + i);
7918 __clear_bit(i, array->bitmap);
7919 }
7920 /* delimiter for bitsearch: */
7921 __set_bit(MAX_RT_PRIO, array->bitmap);
7922
7923#if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7924 rt_rq->highest_prio = MAX_RT_PRIO;
7925#endif
7926#ifdef CONFIG_SMP
7927 rt_rq->rt_nr_migratory = 0;
7928 rt_rq->overloaded = 0;
7929#endif
7930
7931 rt_rq->rt_time = 0;
7932 rt_rq->rt_throttled = 0;
7933 rt_rq->rt_runtime = 0;
7934 spin_lock_init(&rt_rq->rt_runtime_lock);
7935
7936#ifdef CONFIG_RT_GROUP_SCHED
7937 rt_rq->rt_nr_boosted = 0;
7938 rt_rq->rq = rq;
7939#endif
7940}
7941
7942#ifdef CONFIG_FAIR_GROUP_SCHED
7943static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7944 struct sched_entity *se, int cpu, int add,
7945 struct sched_entity *parent)
7946{
7947 struct rq *rq = cpu_rq(cpu);
7948 tg->cfs_rq[cpu] = cfs_rq;
7949 init_cfs_rq(cfs_rq, rq);
7950 cfs_rq->tg = tg;
7951 if (add)
7952 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7953
7954 tg->se[cpu] = se;
7955 /* se could be NULL for init_task_group */
7956 if (!se)
7957 return;
7958
7959 if (!parent)
7960 se->cfs_rq = &rq->cfs;
7961 else
7962 se->cfs_rq = parent->my_q;
7963
7964 se->my_q = cfs_rq;
7965 se->load.weight = tg->shares;
7966 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7967 se->parent = parent;
7968}
7969#endif
7970
7971#ifdef CONFIG_RT_GROUP_SCHED
7972static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7973 struct sched_rt_entity *rt_se, int cpu, int add,
7974 struct sched_rt_entity *parent)
7975{
7976 struct rq *rq = cpu_rq(cpu);
7977
7978 tg->rt_rq[cpu] = rt_rq;
7979 init_rt_rq(rt_rq, rq);
7980 rt_rq->tg = tg;
7981 rt_rq->rt_se = rt_se;
7982 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7983 if (add)
7984 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7985
7986 tg->rt_se[cpu] = rt_se;
7987 if (!rt_se)
7988 return;
7989
7990 if (!parent)
7991 rt_se->rt_rq = &rq->rt;
7992 else
7993 rt_se->rt_rq = parent->my_q;
7994
7995 rt_se->rt_rq = &rq->rt;
7996 rt_se->my_q = rt_rq;
7997 rt_se->parent = parent;
7998 INIT_LIST_HEAD(&rt_se->run_list);
7999}
8000#endif
8001
8002void __init sched_init(void)
8003{
8004 int i, j;
8005 unsigned long alloc_size = 0, ptr;
8006
8007#ifdef CONFIG_FAIR_GROUP_SCHED
8008 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8009#endif
8010#ifdef CONFIG_RT_GROUP_SCHED
8011 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8012#endif
8013#ifdef CONFIG_USER_SCHED
8014 alloc_size *= 2;
8015#endif
8016 /*
8017 * As sched_init() is called before page_alloc is setup,
8018 * we use alloc_bootmem().
8019 */
8020 if (alloc_size) {
8021 ptr = (unsigned long)alloc_bootmem_low(alloc_size);
8022
8023#ifdef CONFIG_FAIR_GROUP_SCHED
8024 init_task_group.se = (struct sched_entity **)ptr;
8025 ptr += nr_cpu_ids * sizeof(void **);
8026
8027 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8028 ptr += nr_cpu_ids * sizeof(void **);
8029
8030#ifdef CONFIG_USER_SCHED
8031 root_task_group.se = (struct sched_entity **)ptr;
8032 ptr += nr_cpu_ids * sizeof(void **);
8033
8034 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8035 ptr += nr_cpu_ids * sizeof(void **);
8036#endif
8037#endif
8038#ifdef CONFIG_RT_GROUP_SCHED
8039 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8040 ptr += nr_cpu_ids * sizeof(void **);
8041
8042 init_task_group.rt_rq = (struct rt_rq **)ptr;
8043 ptr += nr_cpu_ids * sizeof(void **);
8044
8045#ifdef CONFIG_USER_SCHED
8046 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8047 ptr += nr_cpu_ids * sizeof(void **);
8048
8049 root_task_group.rt_rq = (struct rt_rq **)ptr;
8050 ptr += nr_cpu_ids * sizeof(void **);
8051#endif
8052#endif
8053 }
8054
8055#ifdef CONFIG_SMP
8056 init_aggregate();
8057 init_defrootdomain();
8058#endif
8059
8060 init_rt_bandwidth(&def_rt_bandwidth,
8061 global_rt_period(), global_rt_runtime());
8062
8063#ifdef CONFIG_RT_GROUP_SCHED
8064 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8065 global_rt_period(), global_rt_runtime());
8066#ifdef CONFIG_USER_SCHED
8067 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8068 global_rt_period(), RUNTIME_INF);
8069#endif
8070#endif
8071
8072#ifdef CONFIG_GROUP_SCHED
8073 list_add(&init_task_group.list, &task_groups);
8074 INIT_LIST_HEAD(&init_task_group.children);
8075
8076#ifdef CONFIG_USER_SCHED
8077 INIT_LIST_HEAD(&root_task_group.children);
8078 init_task_group.parent = &root_task_group;
8079 list_add(&init_task_group.siblings, &root_task_group.children);
8080#endif
8081#endif
8082
8083 for_each_possible_cpu(i) {
8084 struct rq *rq;
8085
8086 rq = cpu_rq(i);
8087 spin_lock_init(&rq->lock);
8088 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8089 rq->nr_running = 0;
8090 rq->clock = 1;
8091 update_last_tick_seen(rq);
8092 init_cfs_rq(&rq->cfs, rq);
8093 init_rt_rq(&rq->rt, rq);
8094#ifdef CONFIG_FAIR_GROUP_SCHED
8095 init_task_group.shares = init_task_group_load;
8096 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8097#ifdef CONFIG_CGROUP_SCHED
8098 /*
8099 * How much cpu bandwidth does init_task_group get?
8100 *
8101 * In case of task-groups formed thr' the cgroup filesystem, it
8102 * gets 100% of the cpu resources in the system. This overall
8103 * system cpu resource is divided among the tasks of
8104 * init_task_group and its child task-groups in a fair manner,
8105 * based on each entity's (task or task-group's) weight
8106 * (se->load.weight).
8107 *
8108 * In other words, if init_task_group has 10 tasks of weight
8109 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8110 * then A0's share of the cpu resource is:
8111 *
8112 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8113 *
8114 * We achieve this by letting init_task_group's tasks sit
8115 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8116 */
8117 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8118#elif defined CONFIG_USER_SCHED
8119 root_task_group.shares = NICE_0_LOAD;
8120 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8121 /*
8122 * In case of task-groups formed thr' the user id of tasks,
8123 * init_task_group represents tasks belonging to root user.
8124 * Hence it forms a sibling of all subsequent groups formed.
8125 * In this case, init_task_group gets only a fraction of overall
8126 * system cpu resource, based on the weight assigned to root
8127 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8128 * by letting tasks of init_task_group sit in a separate cfs_rq
8129 * (init_cfs_rq) and having one entity represent this group of
8130 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8131 */
8132 init_tg_cfs_entry(&init_task_group,
8133 &per_cpu(init_cfs_rq, i),
8134 &per_cpu(init_sched_entity, i), i, 1,
8135 root_task_group.se[i]);
8136
8137#endif
8138#endif /* CONFIG_FAIR_GROUP_SCHED */
8139
8140 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8141#ifdef CONFIG_RT_GROUP_SCHED
8142 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8143#ifdef CONFIG_CGROUP_SCHED
8144 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8145#elif defined CONFIG_USER_SCHED
8146 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8147 init_tg_rt_entry(&init_task_group,
8148 &per_cpu(init_rt_rq, i),
8149 &per_cpu(init_sched_rt_entity, i), i, 1,
8150 root_task_group.rt_se[i]);
8151#endif
8152#endif
8153
8154 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8155 rq->cpu_load[j] = 0;
8156#ifdef CONFIG_SMP
8157 rq->sd = NULL;
8158 rq->rd = NULL;
8159 rq->active_balance = 0;
8160 rq->next_balance = jiffies;
8161 rq->push_cpu = 0;
8162 rq->cpu = i;
8163 rq->migration_thread = NULL;
8164 INIT_LIST_HEAD(&rq->migration_queue);
8165 rq_attach_root(rq, &def_root_domain);
8166#endif
8167 init_rq_hrtick(rq);
8168 atomic_set(&rq->nr_iowait, 0);
8169 }
8170
8171 set_load_weight(&init_task);
8172
8173#ifdef CONFIG_PREEMPT_NOTIFIERS
8174 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8175#endif
8176
8177#ifdef CONFIG_SMP
8178 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8179#endif
8180
8181#ifdef CONFIG_RT_MUTEXES
8182 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8183#endif
8184
8185 /*
8186 * The boot idle thread does lazy MMU switching as well:
8187 */
8188 atomic_inc(&init_mm.mm_count);
8189 enter_lazy_tlb(&init_mm, current);
8190
8191 /*
8192 * Make us the idle thread. Technically, schedule() should not be
8193 * called from this thread, however somewhere below it might be,
8194 * but because we are the idle thread, we just pick up running again
8195 * when this runqueue becomes "idle".
8196 */
8197 init_idle(current, smp_processor_id());
8198 /*
8199 * During early bootup we pretend to be a normal task:
8200 */
8201 current->sched_class = &fair_sched_class;
8202
8203 scheduler_running = 1;
8204}
8205
8206#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8207void __might_sleep(char *file, int line)
8208{
8209#ifdef in_atomic
8210 static unsigned long prev_jiffy; /* ratelimiting */
8211
8212 if ((in_atomic() || irqs_disabled()) &&
8213 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8214 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8215 return;
8216 prev_jiffy = jiffies;
8217 printk(KERN_ERR "BUG: sleeping function called from invalid"
8218 " context at %s:%d\n", file, line);
8219 printk("in_atomic():%d, irqs_disabled():%d\n",
8220 in_atomic(), irqs_disabled());
8221 debug_show_held_locks(current);
8222 if (irqs_disabled())
8223 print_irqtrace_events(current);
8224 dump_stack();
8225 }
8226#endif
8227}
8228EXPORT_SYMBOL(__might_sleep);
8229#endif
8230
8231#ifdef CONFIG_MAGIC_SYSRQ
8232static void normalize_task(struct rq *rq, struct task_struct *p)
8233{
8234 int on_rq;
8235 update_rq_clock(rq);
8236 on_rq = p->se.on_rq;
8237 if (on_rq)
8238 deactivate_task(rq, p, 0);
8239 __setscheduler(rq, p, SCHED_NORMAL, 0);
8240 if (on_rq) {
8241 activate_task(rq, p, 0);
8242 resched_task(rq->curr);
8243 }
8244}
8245
8246void normalize_rt_tasks(void)
8247{
8248 struct task_struct *g, *p;
8249 unsigned long flags;
8250 struct rq *rq;
8251
8252 read_lock_irqsave(&tasklist_lock, flags);
8253 do_each_thread(g, p) {
8254 /*
8255 * Only normalize user tasks:
8256 */
8257 if (!p->mm)
8258 continue;
8259
8260 p->se.exec_start = 0;
8261#ifdef CONFIG_SCHEDSTATS
8262 p->se.wait_start = 0;
8263 p->se.sleep_start = 0;
8264 p->se.block_start = 0;
8265#endif
8266 task_rq(p)->clock = 0;
8267
8268 if (!rt_task(p)) {
8269 /*
8270 * Renice negative nice level userspace
8271 * tasks back to 0:
8272 */
8273 if (TASK_NICE(p) < 0 && p->mm)
8274 set_user_nice(p, 0);
8275 continue;
8276 }
8277
8278 spin_lock(&p->pi_lock);
8279 rq = __task_rq_lock(p);
8280
8281 normalize_task(rq, p);
8282
8283 __task_rq_unlock(rq);
8284 spin_unlock(&p->pi_lock);
8285 } while_each_thread(g, p);
8286
8287 read_unlock_irqrestore(&tasklist_lock, flags);
8288}
8289
8290#endif /* CONFIG_MAGIC_SYSRQ */
8291
8292#ifdef CONFIG_IA64
8293/*
8294 * These functions are only useful for the IA64 MCA handling.
8295 *
8296 * They can only be called when the whole system has been
8297 * stopped - every CPU needs to be quiescent, and no scheduling
8298 * activity can take place. Using them for anything else would
8299 * be a serious bug, and as a result, they aren't even visible
8300 * under any other configuration.
8301 */
8302
8303/**
8304 * curr_task - return the current task for a given cpu.
8305 * @cpu: the processor in question.
8306 *
8307 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8308 */
8309struct task_struct *curr_task(int cpu)
8310{
8311 return cpu_curr(cpu);
8312}
8313
8314/**
8315 * set_curr_task - set the current task for a given cpu.
8316 * @cpu: the processor in question.
8317 * @p: the task pointer to set.
8318 *
8319 * Description: This function must only be used when non-maskable interrupts
8320 * are serviced on a separate stack. It allows the architecture to switch the
8321 * notion of the current task on a cpu in a non-blocking manner. This function
8322 * must be called with all CPU's synchronized, and interrupts disabled, the
8323 * and caller must save the original value of the current task (see
8324 * curr_task() above) and restore that value before reenabling interrupts and
8325 * re-starting the system.
8326 *
8327 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8328 */
8329void set_curr_task(int cpu, struct task_struct *p)
8330{
8331 cpu_curr(cpu) = p;
8332}
8333
8334#endif
8335
8336#ifdef CONFIG_FAIR_GROUP_SCHED
8337static void free_fair_sched_group(struct task_group *tg)
8338{
8339 int i;
8340
8341 for_each_possible_cpu(i) {
8342 if (tg->cfs_rq)
8343 kfree(tg->cfs_rq[i]);
8344 if (tg->se)
8345 kfree(tg->se[i]);
8346 }
8347
8348 kfree(tg->cfs_rq);
8349 kfree(tg->se);
8350}
8351
8352static
8353int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8354{
8355 struct cfs_rq *cfs_rq;
8356 struct sched_entity *se, *parent_se;
8357 struct rq *rq;
8358 int i;
8359
8360 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8361 if (!tg->cfs_rq)
8362 goto err;
8363 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8364 if (!tg->se)
8365 goto err;
8366
8367 tg->shares = NICE_0_LOAD;
8368
8369 for_each_possible_cpu(i) {
8370 rq = cpu_rq(i);
8371
8372 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8373 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8374 if (!cfs_rq)
8375 goto err;
8376
8377 se = kmalloc_node(sizeof(struct sched_entity),
8378 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8379 if (!se)
8380 goto err;
8381
8382 parent_se = parent ? parent->se[i] : NULL;
8383 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8384 }
8385
8386 return 1;
8387
8388 err:
8389 return 0;
8390}
8391
8392static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8393{
8394 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8395 &cpu_rq(cpu)->leaf_cfs_rq_list);
8396}
8397
8398static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8399{
8400 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8401}
8402#else
8403static inline void free_fair_sched_group(struct task_group *tg)
8404{
8405}
8406
8407static inline
8408int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8409{
8410 return 1;
8411}
8412
8413static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8414{
8415}
8416
8417static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8418{
8419}
8420#endif
8421
8422#ifdef CONFIG_RT_GROUP_SCHED
8423static void free_rt_sched_group(struct task_group *tg)
8424{
8425 int i;
8426
8427 destroy_rt_bandwidth(&tg->rt_bandwidth);
8428
8429 for_each_possible_cpu(i) {
8430 if (tg->rt_rq)
8431 kfree(tg->rt_rq[i]);
8432 if (tg->rt_se)
8433 kfree(tg->rt_se[i]);
8434 }
8435
8436 kfree(tg->rt_rq);
8437 kfree(tg->rt_se);
8438}
8439
8440static
8441int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8442{
8443 struct rt_rq *rt_rq;
8444 struct sched_rt_entity *rt_se, *parent_se;
8445 struct rq *rq;
8446 int i;
8447
8448 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8449 if (!tg->rt_rq)
8450 goto err;
8451 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8452 if (!tg->rt_se)
8453 goto err;
8454
8455 init_rt_bandwidth(&tg->rt_bandwidth,
8456 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8457
8458 for_each_possible_cpu(i) {
8459 rq = cpu_rq(i);
8460
8461 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8462 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8463 if (!rt_rq)
8464 goto err;
8465
8466 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8467 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8468 if (!rt_se)
8469 goto err;
8470
8471 parent_se = parent ? parent->rt_se[i] : NULL;
8472 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8473 }
8474
8475 return 1;
8476
8477 err:
8478 return 0;
8479}
8480
8481static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8482{
8483 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8484 &cpu_rq(cpu)->leaf_rt_rq_list);
8485}
8486
8487static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8488{
8489 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8490}
8491#else
8492static inline void free_rt_sched_group(struct task_group *tg)
8493{
8494}
8495
8496static inline
8497int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8498{
8499 return 1;
8500}
8501
8502static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8503{
8504}
8505
8506static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8507{
8508}
8509#endif
8510
8511#ifdef CONFIG_GROUP_SCHED
8512static void free_sched_group(struct task_group *tg)
8513{
8514 free_fair_sched_group(tg);
8515 free_rt_sched_group(tg);
8516 kfree(tg);
8517}
8518
8519/* allocate runqueue etc for a new task group */
8520struct task_group *sched_create_group(struct task_group *parent)
8521{
8522 struct task_group *tg;
8523 unsigned long flags;
8524 int i;
8525
8526 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8527 if (!tg)
8528 return ERR_PTR(-ENOMEM);
8529
8530 if (!alloc_fair_sched_group(tg, parent))
8531 goto err;
8532
8533 if (!alloc_rt_sched_group(tg, parent))
8534 goto err;
8535
8536 spin_lock_irqsave(&task_group_lock, flags);
8537 for_each_possible_cpu(i) {
8538 register_fair_sched_group(tg, i);
8539 register_rt_sched_group(tg, i);
8540 }
8541 list_add_rcu(&tg->list, &task_groups);
8542
8543 WARN_ON(!parent); /* root should already exist */
8544
8545 tg->parent = parent;
8546 list_add_rcu(&tg->siblings, &parent->children);
8547 INIT_LIST_HEAD(&tg->children);
8548 spin_unlock_irqrestore(&task_group_lock, flags);
8549
8550 return tg;
8551
8552err:
8553 free_sched_group(tg);
8554 return ERR_PTR(-ENOMEM);
8555}
8556
8557/* rcu callback to free various structures associated with a task group */
8558static void free_sched_group_rcu(struct rcu_head *rhp)
8559{
8560 /* now it should be safe to free those cfs_rqs */
8561 free_sched_group(container_of(rhp, struct task_group, rcu));
8562}
8563
8564/* Destroy runqueue etc associated with a task group */
8565void sched_destroy_group(struct task_group *tg)
8566{
8567 unsigned long flags;
8568 int i;
8569
8570 spin_lock_irqsave(&task_group_lock, flags);
8571 for_each_possible_cpu(i) {
8572 unregister_fair_sched_group(tg, i);
8573 unregister_rt_sched_group(tg, i);
8574 }
8575 list_del_rcu(&tg->list);
8576 list_del_rcu(&tg->siblings);
8577 spin_unlock_irqrestore(&task_group_lock, flags);
8578
8579 /* wait for possible concurrent references to cfs_rqs complete */
8580 call_rcu(&tg->rcu, free_sched_group_rcu);
8581}
8582
8583/* change task's runqueue when it moves between groups.
8584 * The caller of this function should have put the task in its new group
8585 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8586 * reflect its new group.
8587 */
8588void sched_move_task(struct task_struct *tsk)
8589{
8590 int on_rq, running;
8591 unsigned long flags;
8592 struct rq *rq;
8593
8594 rq = task_rq_lock(tsk, &flags);
8595
8596 update_rq_clock(rq);
8597
8598 running = task_current(rq, tsk);
8599 on_rq = tsk->se.on_rq;
8600
8601 if (on_rq)
8602 dequeue_task(rq, tsk, 0);
8603 if (unlikely(running))
8604 tsk->sched_class->put_prev_task(rq, tsk);
8605
8606 set_task_rq(tsk, task_cpu(tsk));
8607
8608#ifdef CONFIG_FAIR_GROUP_SCHED
8609 if (tsk->sched_class->moved_group)
8610 tsk->sched_class->moved_group(tsk);
8611#endif
8612
8613 if (unlikely(running))
8614 tsk->sched_class->set_curr_task(rq);
8615 if (on_rq)
8616 enqueue_task(rq, tsk, 0);
8617
8618 task_rq_unlock(rq, &flags);
8619}
8620#endif
8621
8622#ifdef CONFIG_FAIR_GROUP_SCHED
8623static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8624{
8625 struct cfs_rq *cfs_rq = se->cfs_rq;
8626 int on_rq;
8627
8628 on_rq = se->on_rq;
8629 if (on_rq)
8630 dequeue_entity(cfs_rq, se, 0);
8631
8632 se->load.weight = shares;
8633 se->load.inv_weight = div64_64((1ULL<<32), shares);
8634
8635 if (on_rq)
8636 enqueue_entity(cfs_rq, se, 0);
8637}
8638
8639static void set_se_shares(struct sched_entity *se, unsigned long shares)
8640{
8641 struct cfs_rq *cfs_rq = se->cfs_rq;
8642 struct rq *rq = cfs_rq->rq;
8643 unsigned long flags;
8644
8645 spin_lock_irqsave(&rq->lock, flags);
8646 __set_se_shares(se, shares);
8647 spin_unlock_irqrestore(&rq->lock, flags);
8648}
8649
8650static DEFINE_MUTEX(shares_mutex);
8651
8652int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8653{
8654 int i;
8655 unsigned long flags;
8656
8657 /*
8658 * We can't change the weight of the root cgroup.
8659 */
8660 if (!tg->se[0])
8661 return -EINVAL;
8662
8663 /*
8664 * A weight of 0 or 1 can cause arithmetics problems.
8665 * (The default weight is 1024 - so there's no practical
8666 * limitation from this.)
8667 */
8668 if (shares < MIN_SHARES)
8669 shares = MIN_SHARES;
8670
8671 mutex_lock(&shares_mutex);
8672 if (tg->shares == shares)
8673 goto done;
8674
8675 spin_lock_irqsave(&task_group_lock, flags);
8676 for_each_possible_cpu(i)
8677 unregister_fair_sched_group(tg, i);
8678 list_del_rcu(&tg->siblings);
8679 spin_unlock_irqrestore(&task_group_lock, flags);
8680
8681 /* wait for any ongoing reference to this group to finish */
8682 synchronize_sched();
8683
8684 /*
8685 * Now we are free to modify the group's share on each cpu
8686 * w/o tripping rebalance_share or load_balance_fair.
8687 */
8688 tg->shares = shares;
8689 for_each_possible_cpu(i) {
8690 /*
8691 * force a rebalance
8692 */
8693 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8694 set_se_shares(tg->se[i], shares/nr_cpu_ids);
8695 }
8696
8697 /*
8698 * Enable load balance activity on this group, by inserting it back on
8699 * each cpu's rq->leaf_cfs_rq_list.
8700 */
8701 spin_lock_irqsave(&task_group_lock, flags);
8702 for_each_possible_cpu(i)
8703 register_fair_sched_group(tg, i);
8704 list_add_rcu(&tg->siblings, &tg->parent->children);
8705 spin_unlock_irqrestore(&task_group_lock, flags);
8706done:
8707 mutex_unlock(&shares_mutex);
8708 return 0;
8709}
8710
8711unsigned long sched_group_shares(struct task_group *tg)
8712{
8713 return tg->shares;
8714}
8715#endif
8716
8717#ifdef CONFIG_RT_GROUP_SCHED
8718/*
8719 * Ensure that the real time constraints are schedulable.
8720 */
8721static DEFINE_MUTEX(rt_constraints_mutex);
8722
8723static unsigned long to_ratio(u64 period, u64 runtime)
8724{
8725 if (runtime == RUNTIME_INF)
8726 return 1ULL << 16;
8727
8728 return div64_64(runtime << 16, period);
8729}
8730
8731#ifdef CONFIG_CGROUP_SCHED
8732static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8733{
8734 struct task_group *tgi, *parent = tg->parent;
8735 unsigned long total = 0;
8736
8737 if (!parent) {
8738 if (global_rt_period() < period)
8739 return 0;
8740
8741 return to_ratio(period, runtime) <
8742 to_ratio(global_rt_period(), global_rt_runtime());
8743 }
8744
8745 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8746 return 0;
8747
8748 rcu_read_lock();
8749 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8750 if (tgi == tg)
8751 continue;
8752
8753 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8754 tgi->rt_bandwidth.rt_runtime);
8755 }
8756 rcu_read_unlock();
8757
8758 return total + to_ratio(period, runtime) <
8759 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8760 parent->rt_bandwidth.rt_runtime);
8761}
8762#elif defined CONFIG_USER_SCHED
8763static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8764{
8765 struct task_group *tgi;
8766 unsigned long total = 0;
8767 unsigned long global_ratio =
8768 to_ratio(global_rt_period(), global_rt_runtime());
8769
8770 rcu_read_lock();
8771 list_for_each_entry_rcu(tgi, &task_groups, list) {
8772 if (tgi == tg)
8773 continue;
8774
8775 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8776 tgi->rt_bandwidth.rt_runtime);
8777 }
8778 rcu_read_unlock();
8779
8780 return total + to_ratio(period, runtime) < global_ratio;
8781}
8782#endif
8783
8784/* Must be called with tasklist_lock held */
8785static inline int tg_has_rt_tasks(struct task_group *tg)
8786{
8787 struct task_struct *g, *p;
8788 do_each_thread(g, p) {
8789 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8790 return 1;
8791 } while_each_thread(g, p);
8792 return 0;
8793}
8794
8795static int tg_set_bandwidth(struct task_group *tg,
8796 u64 rt_period, u64 rt_runtime)
8797{
8798 int i, err = 0;
8799
8800 mutex_lock(&rt_constraints_mutex);
8801 read_lock(&tasklist_lock);
8802 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8803 err = -EBUSY;
8804 goto unlock;
8805 }
8806 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8807 err = -EINVAL;
8808 goto unlock;
8809 }
8810
8811 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8812 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8813 tg->rt_bandwidth.rt_runtime = rt_runtime;
8814
8815 for_each_possible_cpu(i) {
8816 struct rt_rq *rt_rq = tg->rt_rq[i];
8817
8818 spin_lock(&rt_rq->rt_runtime_lock);
8819 rt_rq->rt_runtime = rt_runtime;
8820 spin_unlock(&rt_rq->rt_runtime_lock);
8821 }
8822 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8823 unlock:
8824 read_unlock(&tasklist_lock);
8825 mutex_unlock(&rt_constraints_mutex);
8826
8827 return err;
8828}
8829
8830int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8831{
8832 u64 rt_runtime, rt_period;
8833
8834 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8835 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8836 if (rt_runtime_us < 0)
8837 rt_runtime = RUNTIME_INF;
8838
8839 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8840}
8841
8842long sched_group_rt_runtime(struct task_group *tg)
8843{
8844 u64 rt_runtime_us;
8845
8846 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8847 return -1;
8848
8849 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8850 do_div(rt_runtime_us, NSEC_PER_USEC);
8851 return rt_runtime_us;
8852}
8853
8854int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8855{
8856 u64 rt_runtime, rt_period;
8857
8858 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8859 rt_runtime = tg->rt_bandwidth.rt_runtime;
8860
8861 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8862}
8863
8864long sched_group_rt_period(struct task_group *tg)
8865{
8866 u64 rt_period_us;
8867
8868 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8869 do_div(rt_period_us, NSEC_PER_USEC);
8870 return rt_period_us;
8871}
8872
8873static int sched_rt_global_constraints(void)
8874{
8875 int ret = 0;
8876
8877 mutex_lock(&rt_constraints_mutex);
8878 if (!__rt_schedulable(NULL, 1, 0))
8879 ret = -EINVAL;
8880 mutex_unlock(&rt_constraints_mutex);
8881
8882 return ret;
8883}
8884#else
8885static int sched_rt_global_constraints(void)
8886{
8887 unsigned long flags;
8888 int i;
8889
8890 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8891 for_each_possible_cpu(i) {
8892 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8893
8894 spin_lock(&rt_rq->rt_runtime_lock);
8895 rt_rq->rt_runtime = global_rt_runtime();
8896 spin_unlock(&rt_rq->rt_runtime_lock);
8897 }
8898 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8899
8900 return 0;
8901}
8902#endif
8903
8904int sched_rt_handler(struct ctl_table *table, int write,
8905 struct file *filp, void __user *buffer, size_t *lenp,
8906 loff_t *ppos)
8907{
8908 int ret;
8909 int old_period, old_runtime;
8910 static DEFINE_MUTEX(mutex);
8911
8912 mutex_lock(&mutex);
8913 old_period = sysctl_sched_rt_period;
8914 old_runtime = sysctl_sched_rt_runtime;
8915
8916 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8917
8918 if (!ret && write) {
8919 ret = sched_rt_global_constraints();
8920 if (ret) {
8921 sysctl_sched_rt_period = old_period;
8922 sysctl_sched_rt_runtime = old_runtime;
8923 } else {
8924 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8925 def_rt_bandwidth.rt_period =
8926 ns_to_ktime(global_rt_period());
8927 }
8928 }
8929 mutex_unlock(&mutex);
8930
8931 return ret;
8932}
8933
8934#ifdef CONFIG_CGROUP_SCHED
8935
8936/* return corresponding task_group object of a cgroup */
8937static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8938{
8939 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8940 struct task_group, css);
8941}
8942
8943static struct cgroup_subsys_state *
8944cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8945{
8946 struct task_group *tg, *parent;
8947
8948 if (!cgrp->parent) {
8949 /* This is early initialization for the top cgroup */
8950 init_task_group.css.cgroup = cgrp;
8951 return &init_task_group.css;
8952 }
8953
8954 parent = cgroup_tg(cgrp->parent);
8955 tg = sched_create_group(parent);
8956 if (IS_ERR(tg))
8957 return ERR_PTR(-ENOMEM);
8958
8959 /* Bind the cgroup to task_group object we just created */
8960 tg->css.cgroup = cgrp;
8961
8962 return &tg->css;
8963}
8964
8965static void
8966cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8967{
8968 struct task_group *tg = cgroup_tg(cgrp);
8969
8970 sched_destroy_group(tg);
8971}
8972
8973static int
8974cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8975 struct task_struct *tsk)
8976{
8977#ifdef CONFIG_RT_GROUP_SCHED
8978 /* Don't accept realtime tasks when there is no way for them to run */
8979 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
8980 return -EINVAL;
8981#else
8982 /* We don't support RT-tasks being in separate groups */
8983 if (tsk->sched_class != &fair_sched_class)
8984 return -EINVAL;
8985#endif
8986
8987 return 0;
8988}
8989
8990static void
8991cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8992 struct cgroup *old_cont, struct task_struct *tsk)
8993{
8994 sched_move_task(tsk);
8995}
8996
8997#ifdef CONFIG_FAIR_GROUP_SCHED
8998static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8999 u64 shareval)
9000{
9001 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9002}
9003
9004static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
9005{
9006 struct task_group *tg = cgroup_tg(cgrp);
9007
9008 return (u64) tg->shares;
9009}
9010#endif
9011
9012#ifdef CONFIG_RT_GROUP_SCHED
9013static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9014 struct file *file,
9015 const char __user *userbuf,
9016 size_t nbytes, loff_t *unused_ppos)
9017{
9018 char buffer[64];
9019 int retval = 0;
9020 s64 val;
9021 char *end;
9022
9023 if (!nbytes)
9024 return -EINVAL;
9025 if (nbytes >= sizeof(buffer))
9026 return -E2BIG;
9027 if (copy_from_user(buffer, userbuf, nbytes))
9028 return -EFAULT;
9029
9030 buffer[nbytes] = 0; /* nul-terminate */
9031
9032 /* strip newline if necessary */
9033 if (nbytes && (buffer[nbytes-1] == '\n'))
9034 buffer[nbytes-1] = 0;
9035 val = simple_strtoll(buffer, &end, 0);
9036 if (*end)
9037 return -EINVAL;
9038
9039 /* Pass to subsystem */
9040 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9041 if (!retval)
9042 retval = nbytes;
9043 return retval;
9044}
9045
9046static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
9047 struct file *file,
9048 char __user *buf, size_t nbytes,
9049 loff_t *ppos)
9050{
9051 char tmp[64];
9052 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
9053 int len = sprintf(tmp, "%ld\n", val);
9054
9055 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
9056}
9057
9058static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9059 u64 rt_period_us)
9060{
9061 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9062}
9063
9064static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9065{
9066 return sched_group_rt_period(cgroup_tg(cgrp));
9067}
9068#endif
9069
9070static struct cftype cpu_files[] = {
9071#ifdef CONFIG_FAIR_GROUP_SCHED
9072 {
9073 .name = "shares",
9074 .read_uint = cpu_shares_read_uint,
9075 .write_uint = cpu_shares_write_uint,
9076 },
9077#endif
9078#ifdef CONFIG_RT_GROUP_SCHED
9079 {
9080 .name = "rt_runtime_us",
9081 .read = cpu_rt_runtime_read,
9082 .write = cpu_rt_runtime_write,
9083 },
9084 {
9085 .name = "rt_period_us",
9086 .read_uint = cpu_rt_period_read_uint,
9087 .write_uint = cpu_rt_period_write_uint,
9088 },
9089#endif
9090};
9091
9092static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9093{
9094 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9095}
9096
9097struct cgroup_subsys cpu_cgroup_subsys = {
9098 .name = "cpu",
9099 .create = cpu_cgroup_create,
9100 .destroy = cpu_cgroup_destroy,
9101 .can_attach = cpu_cgroup_can_attach,
9102 .attach = cpu_cgroup_attach,
9103 .populate = cpu_cgroup_populate,
9104 .subsys_id = cpu_cgroup_subsys_id,
9105 .early_init = 1,
9106};
9107
9108#endif /* CONFIG_CGROUP_SCHED */
9109
9110#ifdef CONFIG_CGROUP_CPUACCT
9111
9112/*
9113 * CPU accounting code for task groups.
9114 *
9115 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9116 * (balbir@in.ibm.com).
9117 */
9118
9119/* track cpu usage of a group of tasks */
9120struct cpuacct {
9121 struct cgroup_subsys_state css;
9122 /* cpuusage holds pointer to a u64-type object on every cpu */
9123 u64 *cpuusage;
9124};
9125
9126struct cgroup_subsys cpuacct_subsys;
9127
9128/* return cpu accounting group corresponding to this container */
9129static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9130{
9131 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9132 struct cpuacct, css);
9133}
9134
9135/* return cpu accounting group to which this task belongs */
9136static inline struct cpuacct *task_ca(struct task_struct *tsk)
9137{
9138 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9139 struct cpuacct, css);
9140}
9141
9142/* create a new cpu accounting group */
9143static struct cgroup_subsys_state *cpuacct_create(
9144 struct cgroup_subsys *ss, struct cgroup *cgrp)
9145{
9146 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9147
9148 if (!ca)
9149 return ERR_PTR(-ENOMEM);
9150
9151 ca->cpuusage = alloc_percpu(u64);
9152 if (!ca->cpuusage) {
9153 kfree(ca);
9154 return ERR_PTR(-ENOMEM);
9155 }
9156
9157 return &ca->css;
9158}
9159
9160/* destroy an existing cpu accounting group */
9161static void
9162cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9163{
9164 struct cpuacct *ca = cgroup_ca(cgrp);
9165
9166 free_percpu(ca->cpuusage);
9167 kfree(ca);
9168}
9169
9170/* return total cpu usage (in nanoseconds) of a group */
9171static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9172{
9173 struct cpuacct *ca = cgroup_ca(cgrp);
9174 u64 totalcpuusage = 0;
9175 int i;
9176
9177 for_each_possible_cpu(i) {
9178 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9179
9180 /*
9181 * Take rq->lock to make 64-bit addition safe on 32-bit
9182 * platforms.
9183 */
9184 spin_lock_irq(&cpu_rq(i)->lock);
9185 totalcpuusage += *cpuusage;
9186 spin_unlock_irq(&cpu_rq(i)->lock);
9187 }
9188
9189 return totalcpuusage;
9190}
9191
9192static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9193 u64 reset)
9194{
9195 struct cpuacct *ca = cgroup_ca(cgrp);
9196 int err = 0;
9197 int i;
9198
9199 if (reset) {
9200 err = -EINVAL;
9201 goto out;
9202 }
9203
9204 for_each_possible_cpu(i) {
9205 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9206
9207 spin_lock_irq(&cpu_rq(i)->lock);
9208 *cpuusage = 0;
9209 spin_unlock_irq(&cpu_rq(i)->lock);
9210 }
9211out:
9212 return err;
9213}
9214
9215static struct cftype files[] = {
9216 {
9217 .name = "usage",
9218 .read_uint = cpuusage_read,
9219 .write_uint = cpuusage_write,
9220 },
9221};
9222
9223static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9224{
9225 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9226}
9227
9228/*
9229 * charge this task's execution time to its accounting group.
9230 *
9231 * called with rq->lock held.
9232 */
9233static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9234{
9235 struct cpuacct *ca;
9236
9237 if (!cpuacct_subsys.active)
9238 return;
9239
9240 ca = task_ca(tsk);
9241 if (ca) {
9242 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9243
9244 *cpuusage += cputime;
9245 }
9246}
9247
9248struct cgroup_subsys cpuacct_subsys = {
9249 .name = "cpuacct",
9250 .create = cpuacct_create,
9251 .destroy = cpuacct_destroy,
9252 .populate = cpuacct_populate,
9253 .subsys_id = cpuacct_subsys_id,
9254};
9255#endif /* CONFIG_CGROUP_CPUACCT */