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