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