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