f33608e9e1a2fee343d41321537733e557dd4661
[deliverable/linux.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 */
26
27 #include <linux/mm.h>
28 #include <linux/module.h>
29 #include <linux/nmi.h>
30 #include <linux/init.h>
31 #include <linux/uaccess.h>
32 #include <linux/highmem.h>
33 #include <linux/smp_lock.h>
34 #include <asm/mmu_context.h>
35 #include <linux/interrupt.h>
36 #include <linux/capability.h>
37 #include <linux/completion.h>
38 #include <linux/kernel_stat.h>
39 #include <linux/debug_locks.h>
40 #include <linux/security.h>
41 #include <linux/notifier.h>
42 #include <linux/profile.h>
43 #include <linux/freezer.h>
44 #include <linux/vmalloc.h>
45 #include <linux/blkdev.h>
46 #include <linux/delay.h>
47 #include <linux/smp.h>
48 #include <linux/threads.h>
49 #include <linux/timer.h>
50 #include <linux/rcupdate.h>
51 #include <linux/cpu.h>
52 #include <linux/cpuset.h>
53 #include <linux/percpu.h>
54 #include <linux/kthread.h>
55 #include <linux/seq_file.h>
56 #include <linux/sysctl.h>
57 #include <linux/syscalls.h>
58 #include <linux/times.h>
59 #include <linux/tsacct_kern.h>
60 #include <linux/kprobes.h>
61 #include <linux/delayacct.h>
62 #include <linux/reciprocal_div.h>
63 #include <linux/unistd.h>
64 #include <linux/pagemap.h>
65
66 #include <asm/tlb.h>
67
68 /*
69 * Scheduler clock - returns current time in nanosec units.
70 * This is default implementation.
71 * Architectures and sub-architectures can override this.
72 */
73 unsigned long long __attribute__((weak)) sched_clock(void)
74 {
75 return (unsigned long long)jiffies * (1000000000 / HZ);
76 }
77
78 /*
79 * Convert user-nice values [ -20 ... 0 ... 19 ]
80 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
81 * and back.
82 */
83 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
84 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
85 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
86
87 /*
88 * 'User priority' is the nice value converted to something we
89 * can work with better when scaling various scheduler parameters,
90 * it's a [ 0 ... 39 ] range.
91 */
92 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
93 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
94 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
95
96 /*
97 * Some helpers for converting nanosecond timing to jiffy resolution
98 */
99 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
100 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
101
102 #define NICE_0_LOAD SCHED_LOAD_SCALE
103 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
104
105 /*
106 * These are the 'tuning knobs' of the scheduler:
107 *
108 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
109 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
110 * Timeslices get refilled after they expire.
111 */
112 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
113 #define DEF_TIMESLICE (100 * HZ / 1000)
114
115 #ifdef CONFIG_SMP
116 /*
117 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
118 * Since cpu_power is a 'constant', we can use a reciprocal divide.
119 */
120 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
121 {
122 return reciprocal_divide(load, sg->reciprocal_cpu_power);
123 }
124
125 /*
126 * Each time a sched group cpu_power is changed,
127 * we must compute its reciprocal value
128 */
129 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
130 {
131 sg->__cpu_power += val;
132 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
133 }
134 #endif
135
136 #define SCALE_PRIO(x, prio) \
137 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
138
139 /*
140 * static_prio_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
141 * to time slice values: [800ms ... 100ms ... 5ms]
142 */
143 static unsigned int static_prio_timeslice(int static_prio)
144 {
145 if (static_prio == NICE_TO_PRIO(19))
146 return 1;
147
148 if (static_prio < NICE_TO_PRIO(0))
149 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
150 else
151 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
152 }
153
154 static inline int rt_policy(int policy)
155 {
156 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
157 return 1;
158 return 0;
159 }
160
161 static inline int task_has_rt_policy(struct task_struct *p)
162 {
163 return rt_policy(p->policy);
164 }
165
166 /*
167 * This is the priority-queue data structure of the RT scheduling class:
168 */
169 struct rt_prio_array {
170 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
171 struct list_head queue[MAX_RT_PRIO];
172 };
173
174 #ifdef CONFIG_FAIR_GROUP_SCHED
175
176 struct cfs_rq;
177
178 /* task group related information */
179 struct task_grp {
180 /* schedulable entities of this group on each cpu */
181 struct sched_entity **se;
182 /* runqueue "owned" by this group on each cpu */
183 struct cfs_rq **cfs_rq;
184 unsigned long shares;
185 };
186
187 /* Default task group's sched entity on each cpu */
188 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
189 /* Default task group's cfs_rq on each cpu */
190 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
191
192 static struct sched_entity *init_sched_entity_p[NR_CPUS];
193 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
194
195 /* Default task group.
196 * Every task in system belong to this group at bootup.
197 */
198 struct task_grp init_task_grp = {
199 .se = init_sched_entity_p,
200 .cfs_rq = init_cfs_rq_p,
201 };
202
203 #ifdef CONFIG_FAIR_USER_SCHED
204 #define INIT_TASK_GRP_LOAD 2*NICE_0_LOAD
205 #else
206 #define INIT_TASK_GRP_LOAD NICE_0_LOAD
207 #endif
208
209 static int init_task_grp_load = INIT_TASK_GRP_LOAD;
210
211 /* return group to which a task belongs */
212 static inline struct task_grp *task_grp(struct task_struct *p)
213 {
214 struct task_grp *tg;
215
216 #ifdef CONFIG_FAIR_USER_SCHED
217 tg = p->user->tg;
218 #else
219 tg = &init_task_grp;
220 #endif
221
222 return tg;
223 }
224
225 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
226 static inline void set_task_cfs_rq(struct task_struct *p)
227 {
228 p->se.cfs_rq = task_grp(p)->cfs_rq[task_cpu(p)];
229 p->se.parent = task_grp(p)->se[task_cpu(p)];
230 }
231
232 #else
233
234 static inline void set_task_cfs_rq(struct task_struct *p) { }
235
236 #endif /* CONFIG_FAIR_GROUP_SCHED */
237
238 /* CFS-related fields in a runqueue */
239 struct cfs_rq {
240 struct load_weight load;
241 unsigned long nr_running;
242
243 u64 exec_clock;
244 u64 min_vruntime;
245
246 struct rb_root tasks_timeline;
247 struct rb_node *rb_leftmost;
248 struct rb_node *rb_load_balance_curr;
249 /* 'curr' points to currently running entity on this cfs_rq.
250 * It is set to NULL otherwise (i.e when none are currently running).
251 */
252 struct sched_entity *curr;
253 #ifdef CONFIG_FAIR_GROUP_SCHED
254 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
255
256 /* leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
257 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
258 * (like users, containers etc.)
259 *
260 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
261 * list is used during load balance.
262 */
263 struct list_head leaf_cfs_rq_list; /* Better name : task_cfs_rq_list? */
264 struct task_grp *tg; /* group that "owns" this runqueue */
265 struct rcu_head rcu;
266 #endif
267 };
268
269 /* Real-Time classes' related field in a runqueue: */
270 struct rt_rq {
271 struct rt_prio_array active;
272 int rt_load_balance_idx;
273 struct list_head *rt_load_balance_head, *rt_load_balance_curr;
274 };
275
276 /*
277 * This is the main, per-CPU runqueue data structure.
278 *
279 * Locking rule: those places that want to lock multiple runqueues
280 * (such as the load balancing or the thread migration code), lock
281 * acquire operations must be ordered by ascending &runqueue.
282 */
283 struct rq {
284 spinlock_t lock; /* runqueue lock */
285
286 /*
287 * nr_running and cpu_load should be in the same cacheline because
288 * remote CPUs use both these fields when doing load calculation.
289 */
290 unsigned long nr_running;
291 #define CPU_LOAD_IDX_MAX 5
292 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
293 unsigned char idle_at_tick;
294 #ifdef CONFIG_NO_HZ
295 unsigned char in_nohz_recently;
296 #endif
297 struct load_weight load; /* capture load from *all* tasks on this cpu */
298 unsigned long nr_load_updates;
299 u64 nr_switches;
300
301 struct cfs_rq cfs;
302 #ifdef CONFIG_FAIR_GROUP_SCHED
303 struct list_head leaf_cfs_rq_list; /* list of leaf cfs_rq on this cpu */
304 #endif
305 struct rt_rq rt;
306
307 /*
308 * This is part of a global counter where only the total sum
309 * over all CPUs matters. A task can increase this counter on
310 * one CPU and if it got migrated afterwards it may decrease
311 * it on another CPU. Always updated under the runqueue lock:
312 */
313 unsigned long nr_uninterruptible;
314
315 struct task_struct *curr, *idle;
316 unsigned long next_balance;
317 struct mm_struct *prev_mm;
318
319 u64 clock, prev_clock_raw;
320 s64 clock_max_delta;
321
322 unsigned int clock_warps, clock_overflows;
323 u64 idle_clock;
324 unsigned int clock_deep_idle_events;
325 u64 tick_timestamp;
326
327 atomic_t nr_iowait;
328
329 #ifdef CONFIG_SMP
330 struct sched_domain *sd;
331
332 /* For active balancing */
333 int active_balance;
334 int push_cpu;
335 int cpu; /* cpu of this runqueue */
336
337 struct task_struct *migration_thread;
338 struct list_head migration_queue;
339 #endif
340
341 #ifdef CONFIG_SCHEDSTATS
342 /* latency stats */
343 struct sched_info rq_sched_info;
344
345 /* sys_sched_yield() stats */
346 unsigned long yld_exp_empty;
347 unsigned long yld_act_empty;
348 unsigned long yld_both_empty;
349 unsigned long yld_cnt;
350
351 /* schedule() stats */
352 unsigned long sched_switch;
353 unsigned long sched_cnt;
354 unsigned long sched_goidle;
355
356 /* try_to_wake_up() stats */
357 unsigned long ttwu_cnt;
358 unsigned long ttwu_local;
359 #endif
360 struct lock_class_key rq_lock_key;
361 };
362
363 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
364 static DEFINE_MUTEX(sched_hotcpu_mutex);
365
366 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
367 {
368 rq->curr->sched_class->check_preempt_curr(rq, p);
369 }
370
371 static inline int cpu_of(struct rq *rq)
372 {
373 #ifdef CONFIG_SMP
374 return rq->cpu;
375 #else
376 return 0;
377 #endif
378 }
379
380 /*
381 * Update the per-runqueue clock, as finegrained as the platform can give
382 * us, but without assuming monotonicity, etc.:
383 */
384 static void __update_rq_clock(struct rq *rq)
385 {
386 u64 prev_raw = rq->prev_clock_raw;
387 u64 now = sched_clock();
388 s64 delta = now - prev_raw;
389 u64 clock = rq->clock;
390
391 #ifdef CONFIG_SCHED_DEBUG
392 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
393 #endif
394 /*
395 * Protect against sched_clock() occasionally going backwards:
396 */
397 if (unlikely(delta < 0)) {
398 clock++;
399 rq->clock_warps++;
400 } else {
401 /*
402 * Catch too large forward jumps too:
403 */
404 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
405 if (clock < rq->tick_timestamp + TICK_NSEC)
406 clock = rq->tick_timestamp + TICK_NSEC;
407 else
408 clock++;
409 rq->clock_overflows++;
410 } else {
411 if (unlikely(delta > rq->clock_max_delta))
412 rq->clock_max_delta = delta;
413 clock += delta;
414 }
415 }
416
417 rq->prev_clock_raw = now;
418 rq->clock = clock;
419 }
420
421 static void update_rq_clock(struct rq *rq)
422 {
423 if (likely(smp_processor_id() == cpu_of(rq)))
424 __update_rq_clock(rq);
425 }
426
427 /*
428 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
429 * See detach_destroy_domains: synchronize_sched for details.
430 *
431 * The domain tree of any CPU may only be accessed from within
432 * preempt-disabled sections.
433 */
434 #define for_each_domain(cpu, __sd) \
435 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
436
437 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
438 #define this_rq() (&__get_cpu_var(runqueues))
439 #define task_rq(p) cpu_rq(task_cpu(p))
440 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
441
442 /*
443 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
444 */
445 #ifdef CONFIG_SCHED_DEBUG
446 # define const_debug __read_mostly
447 #else
448 # define const_debug static const
449 #endif
450
451 /*
452 * Debugging: various feature bits
453 */
454 enum {
455 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
456 SCHED_FEAT_START_DEBIT = 2,
457 SCHED_FEAT_USE_TREE_AVG = 4,
458 SCHED_FEAT_APPROX_AVG = 8,
459 };
460
461 const_debug unsigned int sysctl_sched_features =
462 SCHED_FEAT_NEW_FAIR_SLEEPERS *1 |
463 SCHED_FEAT_START_DEBIT *1 |
464 SCHED_FEAT_USE_TREE_AVG *0 |
465 SCHED_FEAT_APPROX_AVG *0;
466
467 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
468
469 /*
470 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
471 * clock constructed from sched_clock():
472 */
473 unsigned long long cpu_clock(int cpu)
474 {
475 unsigned long long now;
476 unsigned long flags;
477 struct rq *rq;
478
479 local_irq_save(flags);
480 rq = cpu_rq(cpu);
481 update_rq_clock(rq);
482 now = rq->clock;
483 local_irq_restore(flags);
484
485 return now;
486 }
487
488 #ifndef prepare_arch_switch
489 # define prepare_arch_switch(next) do { } while (0)
490 #endif
491 #ifndef finish_arch_switch
492 # define finish_arch_switch(prev) do { } while (0)
493 #endif
494
495 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
496 static inline int task_running(struct rq *rq, struct task_struct *p)
497 {
498 return rq->curr == p;
499 }
500
501 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
502 {
503 }
504
505 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
506 {
507 #ifdef CONFIG_DEBUG_SPINLOCK
508 /* this is a valid case when another task releases the spinlock */
509 rq->lock.owner = current;
510 #endif
511 /*
512 * If we are tracking spinlock dependencies then we have to
513 * fix up the runqueue lock - which gets 'carried over' from
514 * prev into current:
515 */
516 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
517
518 spin_unlock_irq(&rq->lock);
519 }
520
521 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
522 static inline int task_running(struct rq *rq, struct task_struct *p)
523 {
524 #ifdef CONFIG_SMP
525 return p->oncpu;
526 #else
527 return rq->curr == p;
528 #endif
529 }
530
531 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
532 {
533 #ifdef CONFIG_SMP
534 /*
535 * We can optimise this out completely for !SMP, because the
536 * SMP rebalancing from interrupt is the only thing that cares
537 * here.
538 */
539 next->oncpu = 1;
540 #endif
541 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
542 spin_unlock_irq(&rq->lock);
543 #else
544 spin_unlock(&rq->lock);
545 #endif
546 }
547
548 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
549 {
550 #ifdef CONFIG_SMP
551 /*
552 * After ->oncpu is cleared, the task can be moved to a different CPU.
553 * We must ensure this doesn't happen until the switch is completely
554 * finished.
555 */
556 smp_wmb();
557 prev->oncpu = 0;
558 #endif
559 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
560 local_irq_enable();
561 #endif
562 }
563 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
564
565 /*
566 * __task_rq_lock - lock the runqueue a given task resides on.
567 * Must be called interrupts disabled.
568 */
569 static inline struct rq *__task_rq_lock(struct task_struct *p)
570 __acquires(rq->lock)
571 {
572 struct rq *rq;
573
574 repeat_lock_task:
575 rq = task_rq(p);
576 spin_lock(&rq->lock);
577 if (unlikely(rq != task_rq(p))) {
578 spin_unlock(&rq->lock);
579 goto repeat_lock_task;
580 }
581 return rq;
582 }
583
584 /*
585 * task_rq_lock - lock the runqueue a given task resides on and disable
586 * interrupts. Note the ordering: we can safely lookup the task_rq without
587 * explicitly disabling preemption.
588 */
589 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
590 __acquires(rq->lock)
591 {
592 struct rq *rq;
593
594 repeat_lock_task:
595 local_irq_save(*flags);
596 rq = task_rq(p);
597 spin_lock(&rq->lock);
598 if (unlikely(rq != task_rq(p))) {
599 spin_unlock_irqrestore(&rq->lock, *flags);
600 goto repeat_lock_task;
601 }
602 return rq;
603 }
604
605 static inline void __task_rq_unlock(struct rq *rq)
606 __releases(rq->lock)
607 {
608 spin_unlock(&rq->lock);
609 }
610
611 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
612 __releases(rq->lock)
613 {
614 spin_unlock_irqrestore(&rq->lock, *flags);
615 }
616
617 /*
618 * this_rq_lock - lock this runqueue and disable interrupts.
619 */
620 static inline struct rq *this_rq_lock(void)
621 __acquires(rq->lock)
622 {
623 struct rq *rq;
624
625 local_irq_disable();
626 rq = this_rq();
627 spin_lock(&rq->lock);
628
629 return rq;
630 }
631
632 /*
633 * We are going deep-idle (irqs are disabled):
634 */
635 void sched_clock_idle_sleep_event(void)
636 {
637 struct rq *rq = cpu_rq(smp_processor_id());
638
639 spin_lock(&rq->lock);
640 __update_rq_clock(rq);
641 spin_unlock(&rq->lock);
642 rq->clock_deep_idle_events++;
643 }
644 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
645
646 /*
647 * We just idled delta nanoseconds (called with irqs disabled):
648 */
649 void sched_clock_idle_wakeup_event(u64 delta_ns)
650 {
651 struct rq *rq = cpu_rq(smp_processor_id());
652 u64 now = sched_clock();
653
654 rq->idle_clock += delta_ns;
655 /*
656 * Override the previous timestamp and ignore all
657 * sched_clock() deltas that occured while we idled,
658 * and use the PM-provided delta_ns to advance the
659 * rq clock:
660 */
661 spin_lock(&rq->lock);
662 rq->prev_clock_raw = now;
663 rq->clock += delta_ns;
664 spin_unlock(&rq->lock);
665 }
666 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
667
668 /*
669 * resched_task - mark a task 'to be rescheduled now'.
670 *
671 * On UP this means the setting of the need_resched flag, on SMP it
672 * might also involve a cross-CPU call to trigger the scheduler on
673 * the target CPU.
674 */
675 #ifdef CONFIG_SMP
676
677 #ifndef tsk_is_polling
678 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
679 #endif
680
681 static void resched_task(struct task_struct *p)
682 {
683 int cpu;
684
685 assert_spin_locked(&task_rq(p)->lock);
686
687 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
688 return;
689
690 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
691
692 cpu = task_cpu(p);
693 if (cpu == smp_processor_id())
694 return;
695
696 /* NEED_RESCHED must be visible before we test polling */
697 smp_mb();
698 if (!tsk_is_polling(p))
699 smp_send_reschedule(cpu);
700 }
701
702 static void resched_cpu(int cpu)
703 {
704 struct rq *rq = cpu_rq(cpu);
705 unsigned long flags;
706
707 if (!spin_trylock_irqsave(&rq->lock, flags))
708 return;
709 resched_task(cpu_curr(cpu));
710 spin_unlock_irqrestore(&rq->lock, flags);
711 }
712 #else
713 static inline void resched_task(struct task_struct *p)
714 {
715 assert_spin_locked(&task_rq(p)->lock);
716 set_tsk_need_resched(p);
717 }
718 #endif
719
720 #if BITS_PER_LONG == 32
721 # define WMULT_CONST (~0UL)
722 #else
723 # define WMULT_CONST (1UL << 32)
724 #endif
725
726 #define WMULT_SHIFT 32
727
728 /*
729 * Shift right and round:
730 */
731 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
732
733 static unsigned long
734 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
735 struct load_weight *lw)
736 {
737 u64 tmp;
738
739 if (unlikely(!lw->inv_weight))
740 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
741
742 tmp = (u64)delta_exec * weight;
743 /*
744 * Check whether we'd overflow the 64-bit multiplication:
745 */
746 if (unlikely(tmp > WMULT_CONST))
747 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
748 WMULT_SHIFT/2);
749 else
750 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
751
752 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
753 }
754
755 static inline unsigned long
756 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
757 {
758 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
759 }
760
761 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
762 {
763 lw->weight += inc;
764 }
765
766 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
767 {
768 lw->weight -= dec;
769 }
770
771 /*
772 * To aid in avoiding the subversion of "niceness" due to uneven distribution
773 * of tasks with abnormal "nice" values across CPUs the contribution that
774 * each task makes to its run queue's load is weighted according to its
775 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
776 * scaled version of the new time slice allocation that they receive on time
777 * slice expiry etc.
778 */
779
780 #define WEIGHT_IDLEPRIO 2
781 #define WMULT_IDLEPRIO (1 << 31)
782
783 /*
784 * Nice levels are multiplicative, with a gentle 10% change for every
785 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
786 * nice 1, it will get ~10% less CPU time than another CPU-bound task
787 * that remained on nice 0.
788 *
789 * The "10% effect" is relative and cumulative: from _any_ nice level,
790 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
791 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
792 * If a task goes up by ~10% and another task goes down by ~10% then
793 * the relative distance between them is ~25%.)
794 */
795 static const int prio_to_weight[40] = {
796 /* -20 */ 88761, 71755, 56483, 46273, 36291,
797 /* -15 */ 29154, 23254, 18705, 14949, 11916,
798 /* -10 */ 9548, 7620, 6100, 4904, 3906,
799 /* -5 */ 3121, 2501, 1991, 1586, 1277,
800 /* 0 */ 1024, 820, 655, 526, 423,
801 /* 5 */ 335, 272, 215, 172, 137,
802 /* 10 */ 110, 87, 70, 56, 45,
803 /* 15 */ 36, 29, 23, 18, 15,
804 };
805
806 /*
807 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
808 *
809 * In cases where the weight does not change often, we can use the
810 * precalculated inverse to speed up arithmetics by turning divisions
811 * into multiplications:
812 */
813 static const u32 prio_to_wmult[40] = {
814 /* -20 */ 48388, 59856, 76040, 92818, 118348,
815 /* -15 */ 147320, 184698, 229616, 287308, 360437,
816 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
817 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
818 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
819 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
820 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
821 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
822 };
823
824 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
825
826 /*
827 * runqueue iterator, to support SMP load-balancing between different
828 * scheduling classes, without having to expose their internal data
829 * structures to the load-balancing proper:
830 */
831 struct rq_iterator {
832 void *arg;
833 struct task_struct *(*start)(void *);
834 struct task_struct *(*next)(void *);
835 };
836
837 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
838 unsigned long max_nr_move, unsigned long max_load_move,
839 struct sched_domain *sd, enum cpu_idle_type idle,
840 int *all_pinned, unsigned long *load_moved,
841 int *this_best_prio, struct rq_iterator *iterator);
842
843 #include "sched_stats.h"
844 #include "sched_rt.c"
845 #include "sched_fair.c"
846 #include "sched_idletask.c"
847 #ifdef CONFIG_SCHED_DEBUG
848 # include "sched_debug.c"
849 #endif
850
851 #define sched_class_highest (&rt_sched_class)
852
853 /*
854 * Update delta_exec, delta_fair fields for rq.
855 *
856 * delta_fair clock advances at a rate inversely proportional to
857 * total load (rq->load.weight) on the runqueue, while
858 * delta_exec advances at the same rate as wall-clock (provided
859 * cpu is not idle).
860 *
861 * delta_exec / delta_fair is a measure of the (smoothened) load on this
862 * runqueue over any given interval. This (smoothened) load is used
863 * during load balance.
864 *
865 * This function is called /before/ updating rq->load
866 * and when switching tasks.
867 */
868 static inline void inc_load(struct rq *rq, const struct task_struct *p)
869 {
870 update_load_add(&rq->load, p->se.load.weight);
871 }
872
873 static inline void dec_load(struct rq *rq, const struct task_struct *p)
874 {
875 update_load_sub(&rq->load, p->se.load.weight);
876 }
877
878 static void inc_nr_running(struct task_struct *p, struct rq *rq)
879 {
880 rq->nr_running++;
881 inc_load(rq, p);
882 }
883
884 static void dec_nr_running(struct task_struct *p, struct rq *rq)
885 {
886 rq->nr_running--;
887 dec_load(rq, p);
888 }
889
890 static void set_load_weight(struct task_struct *p)
891 {
892 if (task_has_rt_policy(p)) {
893 p->se.load.weight = prio_to_weight[0] * 2;
894 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
895 return;
896 }
897
898 /*
899 * SCHED_IDLE tasks get minimal weight:
900 */
901 if (p->policy == SCHED_IDLE) {
902 p->se.load.weight = WEIGHT_IDLEPRIO;
903 p->se.load.inv_weight = WMULT_IDLEPRIO;
904 return;
905 }
906
907 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
908 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
909 }
910
911 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
912 {
913 sched_info_queued(p);
914 p->sched_class->enqueue_task(rq, p, wakeup);
915 p->se.on_rq = 1;
916 }
917
918 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
919 {
920 p->sched_class->dequeue_task(rq, p, sleep);
921 p->se.on_rq = 0;
922 }
923
924 /*
925 * __normal_prio - return the priority that is based on the static prio
926 */
927 static inline int __normal_prio(struct task_struct *p)
928 {
929 return p->static_prio;
930 }
931
932 /*
933 * Calculate the expected normal priority: i.e. priority
934 * without taking RT-inheritance into account. Might be
935 * boosted by interactivity modifiers. Changes upon fork,
936 * setprio syscalls, and whenever the interactivity
937 * estimator recalculates.
938 */
939 static inline int normal_prio(struct task_struct *p)
940 {
941 int prio;
942
943 if (task_has_rt_policy(p))
944 prio = MAX_RT_PRIO-1 - p->rt_priority;
945 else
946 prio = __normal_prio(p);
947 return prio;
948 }
949
950 /*
951 * Calculate the current priority, i.e. the priority
952 * taken into account by the scheduler. This value might
953 * be boosted by RT tasks, or might be boosted by
954 * interactivity modifiers. Will be RT if the task got
955 * RT-boosted. If not then it returns p->normal_prio.
956 */
957 static int effective_prio(struct task_struct *p)
958 {
959 p->normal_prio = normal_prio(p);
960 /*
961 * If we are RT tasks or we were boosted to RT priority,
962 * keep the priority unchanged. Otherwise, update priority
963 * to the normal priority:
964 */
965 if (!rt_prio(p->prio))
966 return p->normal_prio;
967 return p->prio;
968 }
969
970 /*
971 * activate_task - move a task to the runqueue.
972 */
973 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
974 {
975 if (p->state == TASK_UNINTERRUPTIBLE)
976 rq->nr_uninterruptible--;
977
978 enqueue_task(rq, p, wakeup);
979 inc_nr_running(p, rq);
980 }
981
982 /*
983 * activate_idle_task - move idle task to the _front_ of runqueue.
984 */
985 static inline void activate_idle_task(struct task_struct *p, struct rq *rq)
986 {
987 update_rq_clock(rq);
988
989 if (p->state == TASK_UNINTERRUPTIBLE)
990 rq->nr_uninterruptible--;
991
992 enqueue_task(rq, p, 0);
993 inc_nr_running(p, rq);
994 }
995
996 /*
997 * deactivate_task - remove a task from the runqueue.
998 */
999 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1000 {
1001 if (p->state == TASK_UNINTERRUPTIBLE)
1002 rq->nr_uninterruptible++;
1003
1004 dequeue_task(rq, p, sleep);
1005 dec_nr_running(p, rq);
1006 }
1007
1008 /**
1009 * task_curr - is this task currently executing on a CPU?
1010 * @p: the task in question.
1011 */
1012 inline int task_curr(const struct task_struct *p)
1013 {
1014 return cpu_curr(task_cpu(p)) == p;
1015 }
1016
1017 /* Used instead of source_load when we know the type == 0 */
1018 unsigned long weighted_cpuload(const int cpu)
1019 {
1020 return cpu_rq(cpu)->load.weight;
1021 }
1022
1023 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1024 {
1025 #ifdef CONFIG_SMP
1026 task_thread_info(p)->cpu = cpu;
1027 #endif
1028 set_task_cfs_rq(p);
1029 }
1030
1031 #ifdef CONFIG_SMP
1032
1033 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1034 {
1035 int old_cpu = task_cpu(p);
1036 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1037 u64 clock_offset;
1038
1039 clock_offset = old_rq->clock - new_rq->clock;
1040
1041 #ifdef CONFIG_SCHEDSTATS
1042 if (p->se.wait_start)
1043 p->se.wait_start -= clock_offset;
1044 if (p->se.sleep_start)
1045 p->se.sleep_start -= clock_offset;
1046 if (p->se.block_start)
1047 p->se.block_start -= clock_offset;
1048 #endif
1049 if (likely(new_rq->cfs.min_vruntime))
1050 p->se.vruntime -= old_rq->cfs.min_vruntime -
1051 new_rq->cfs.min_vruntime;
1052
1053 __set_task_cpu(p, new_cpu);
1054 }
1055
1056 struct migration_req {
1057 struct list_head list;
1058
1059 struct task_struct *task;
1060 int dest_cpu;
1061
1062 struct completion done;
1063 };
1064
1065 /*
1066 * The task's runqueue lock must be held.
1067 * Returns true if you have to wait for migration thread.
1068 */
1069 static int
1070 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1071 {
1072 struct rq *rq = task_rq(p);
1073
1074 /*
1075 * If the task is not on a runqueue (and not running), then
1076 * it is sufficient to simply update the task's cpu field.
1077 */
1078 if (!p->se.on_rq && !task_running(rq, p)) {
1079 set_task_cpu(p, dest_cpu);
1080 return 0;
1081 }
1082
1083 init_completion(&req->done);
1084 req->task = p;
1085 req->dest_cpu = dest_cpu;
1086 list_add(&req->list, &rq->migration_queue);
1087
1088 return 1;
1089 }
1090
1091 /*
1092 * wait_task_inactive - wait for a thread to unschedule.
1093 *
1094 * The caller must ensure that the task *will* unschedule sometime soon,
1095 * else this function might spin for a *long* time. This function can't
1096 * be called with interrupts off, or it may introduce deadlock with
1097 * smp_call_function() if an IPI is sent by the same process we are
1098 * waiting to become inactive.
1099 */
1100 void wait_task_inactive(struct task_struct *p)
1101 {
1102 unsigned long flags;
1103 int running, on_rq;
1104 struct rq *rq;
1105
1106 repeat:
1107 /*
1108 * We do the initial early heuristics without holding
1109 * any task-queue locks at all. We'll only try to get
1110 * the runqueue lock when things look like they will
1111 * work out!
1112 */
1113 rq = task_rq(p);
1114
1115 /*
1116 * If the task is actively running on another CPU
1117 * still, just relax and busy-wait without holding
1118 * any locks.
1119 *
1120 * NOTE! Since we don't hold any locks, it's not
1121 * even sure that "rq" stays as the right runqueue!
1122 * But we don't care, since "task_running()" will
1123 * return false if the runqueue has changed and p
1124 * is actually now running somewhere else!
1125 */
1126 while (task_running(rq, p))
1127 cpu_relax();
1128
1129 /*
1130 * Ok, time to look more closely! We need the rq
1131 * lock now, to be *sure*. If we're wrong, we'll
1132 * just go back and repeat.
1133 */
1134 rq = task_rq_lock(p, &flags);
1135 running = task_running(rq, p);
1136 on_rq = p->se.on_rq;
1137 task_rq_unlock(rq, &flags);
1138
1139 /*
1140 * Was it really running after all now that we
1141 * checked with the proper locks actually held?
1142 *
1143 * Oops. Go back and try again..
1144 */
1145 if (unlikely(running)) {
1146 cpu_relax();
1147 goto repeat;
1148 }
1149
1150 /*
1151 * It's not enough that it's not actively running,
1152 * it must be off the runqueue _entirely_, and not
1153 * preempted!
1154 *
1155 * So if it wa still runnable (but just not actively
1156 * running right now), it's preempted, and we should
1157 * yield - it could be a while.
1158 */
1159 if (unlikely(on_rq)) {
1160 yield();
1161 goto repeat;
1162 }
1163
1164 /*
1165 * Ahh, all good. It wasn't running, and it wasn't
1166 * runnable, which means that it will never become
1167 * running in the future either. We're all done!
1168 */
1169 }
1170
1171 /***
1172 * kick_process - kick a running thread to enter/exit the kernel
1173 * @p: the to-be-kicked thread
1174 *
1175 * Cause a process which is running on another CPU to enter
1176 * kernel-mode, without any delay. (to get signals handled.)
1177 *
1178 * NOTE: this function doesnt have to take the runqueue lock,
1179 * because all it wants to ensure is that the remote task enters
1180 * the kernel. If the IPI races and the task has been migrated
1181 * to another CPU then no harm is done and the purpose has been
1182 * achieved as well.
1183 */
1184 void kick_process(struct task_struct *p)
1185 {
1186 int cpu;
1187
1188 preempt_disable();
1189 cpu = task_cpu(p);
1190 if ((cpu != smp_processor_id()) && task_curr(p))
1191 smp_send_reschedule(cpu);
1192 preempt_enable();
1193 }
1194
1195 /*
1196 * Return a low guess at the load of a migration-source cpu weighted
1197 * according to the scheduling class and "nice" value.
1198 *
1199 * We want to under-estimate the load of migration sources, to
1200 * balance conservatively.
1201 */
1202 static inline unsigned long source_load(int cpu, int type)
1203 {
1204 struct rq *rq = cpu_rq(cpu);
1205 unsigned long total = weighted_cpuload(cpu);
1206
1207 if (type == 0)
1208 return total;
1209
1210 return min(rq->cpu_load[type-1], total);
1211 }
1212
1213 /*
1214 * Return a high guess at the load of a migration-target cpu weighted
1215 * according to the scheduling class and "nice" value.
1216 */
1217 static inline unsigned long target_load(int cpu, int type)
1218 {
1219 struct rq *rq = cpu_rq(cpu);
1220 unsigned long total = weighted_cpuload(cpu);
1221
1222 if (type == 0)
1223 return total;
1224
1225 return max(rq->cpu_load[type-1], total);
1226 }
1227
1228 /*
1229 * Return the average load per task on the cpu's run queue
1230 */
1231 static inline unsigned long cpu_avg_load_per_task(int cpu)
1232 {
1233 struct rq *rq = cpu_rq(cpu);
1234 unsigned long total = weighted_cpuload(cpu);
1235 unsigned long n = rq->nr_running;
1236
1237 return n ? total / n : SCHED_LOAD_SCALE;
1238 }
1239
1240 /*
1241 * find_idlest_group finds and returns the least busy CPU group within the
1242 * domain.
1243 */
1244 static struct sched_group *
1245 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1246 {
1247 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1248 unsigned long min_load = ULONG_MAX, this_load = 0;
1249 int load_idx = sd->forkexec_idx;
1250 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1251
1252 do {
1253 unsigned long load, avg_load;
1254 int local_group;
1255 int i;
1256
1257 /* Skip over this group if it has no CPUs allowed */
1258 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1259 goto nextgroup;
1260
1261 local_group = cpu_isset(this_cpu, group->cpumask);
1262
1263 /* Tally up the load of all CPUs in the group */
1264 avg_load = 0;
1265
1266 for_each_cpu_mask(i, group->cpumask) {
1267 /* Bias balancing toward cpus of our domain */
1268 if (local_group)
1269 load = source_load(i, load_idx);
1270 else
1271 load = target_load(i, load_idx);
1272
1273 avg_load += load;
1274 }
1275
1276 /* Adjust by relative CPU power of the group */
1277 avg_load = sg_div_cpu_power(group,
1278 avg_load * SCHED_LOAD_SCALE);
1279
1280 if (local_group) {
1281 this_load = avg_load;
1282 this = group;
1283 } else if (avg_load < min_load) {
1284 min_load = avg_load;
1285 idlest = group;
1286 }
1287 nextgroup:
1288 group = group->next;
1289 } while (group != sd->groups);
1290
1291 if (!idlest || 100*this_load < imbalance*min_load)
1292 return NULL;
1293 return idlest;
1294 }
1295
1296 /*
1297 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1298 */
1299 static int
1300 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1301 {
1302 cpumask_t tmp;
1303 unsigned long load, min_load = ULONG_MAX;
1304 int idlest = -1;
1305 int i;
1306
1307 /* Traverse only the allowed CPUs */
1308 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1309
1310 for_each_cpu_mask(i, tmp) {
1311 load = weighted_cpuload(i);
1312
1313 if (load < min_load || (load == min_load && i == this_cpu)) {
1314 min_load = load;
1315 idlest = i;
1316 }
1317 }
1318
1319 return idlest;
1320 }
1321
1322 /*
1323 * sched_balance_self: balance the current task (running on cpu) in domains
1324 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1325 * SD_BALANCE_EXEC.
1326 *
1327 * Balance, ie. select the least loaded group.
1328 *
1329 * Returns the target CPU number, or the same CPU if no balancing is needed.
1330 *
1331 * preempt must be disabled.
1332 */
1333 static int sched_balance_self(int cpu, int flag)
1334 {
1335 struct task_struct *t = current;
1336 struct sched_domain *tmp, *sd = NULL;
1337
1338 for_each_domain(cpu, tmp) {
1339 /*
1340 * If power savings logic is enabled for a domain, stop there.
1341 */
1342 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1343 break;
1344 if (tmp->flags & flag)
1345 sd = tmp;
1346 }
1347
1348 while (sd) {
1349 cpumask_t span;
1350 struct sched_group *group;
1351 int new_cpu, weight;
1352
1353 if (!(sd->flags & flag)) {
1354 sd = sd->child;
1355 continue;
1356 }
1357
1358 span = sd->span;
1359 group = find_idlest_group(sd, t, cpu);
1360 if (!group) {
1361 sd = sd->child;
1362 continue;
1363 }
1364
1365 new_cpu = find_idlest_cpu(group, t, cpu);
1366 if (new_cpu == -1 || new_cpu == cpu) {
1367 /* Now try balancing at a lower domain level of cpu */
1368 sd = sd->child;
1369 continue;
1370 }
1371
1372 /* Now try balancing at a lower domain level of new_cpu */
1373 cpu = new_cpu;
1374 sd = NULL;
1375 weight = cpus_weight(span);
1376 for_each_domain(cpu, tmp) {
1377 if (weight <= cpus_weight(tmp->span))
1378 break;
1379 if (tmp->flags & flag)
1380 sd = tmp;
1381 }
1382 /* while loop will break here if sd == NULL */
1383 }
1384
1385 return cpu;
1386 }
1387
1388 #endif /* CONFIG_SMP */
1389
1390 /*
1391 * wake_idle() will wake a task on an idle cpu if task->cpu is
1392 * not idle and an idle cpu is available. The span of cpus to
1393 * search starts with cpus closest then further out as needed,
1394 * so we always favor a closer, idle cpu.
1395 *
1396 * Returns the CPU we should wake onto.
1397 */
1398 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1399 static int wake_idle(int cpu, struct task_struct *p)
1400 {
1401 cpumask_t tmp;
1402 struct sched_domain *sd;
1403 int i;
1404
1405 /*
1406 * If it is idle, then it is the best cpu to run this task.
1407 *
1408 * This cpu is also the best, if it has more than one task already.
1409 * Siblings must be also busy(in most cases) as they didn't already
1410 * pickup the extra load from this cpu and hence we need not check
1411 * sibling runqueue info. This will avoid the checks and cache miss
1412 * penalities associated with that.
1413 */
1414 if (idle_cpu(cpu) || cpu_rq(cpu)->nr_running > 1)
1415 return cpu;
1416
1417 for_each_domain(cpu, sd) {
1418 if (sd->flags & SD_WAKE_IDLE) {
1419 cpus_and(tmp, sd->span, p->cpus_allowed);
1420 for_each_cpu_mask(i, tmp) {
1421 if (idle_cpu(i))
1422 return i;
1423 }
1424 } else {
1425 break;
1426 }
1427 }
1428 return cpu;
1429 }
1430 #else
1431 static inline int wake_idle(int cpu, struct task_struct *p)
1432 {
1433 return cpu;
1434 }
1435 #endif
1436
1437 /***
1438 * try_to_wake_up - wake up a thread
1439 * @p: the to-be-woken-up thread
1440 * @state: the mask of task states that can be woken
1441 * @sync: do a synchronous wakeup?
1442 *
1443 * Put it on the run-queue if it's not already there. The "current"
1444 * thread is always on the run-queue (except when the actual
1445 * re-schedule is in progress), and as such you're allowed to do
1446 * the simpler "current->state = TASK_RUNNING" to mark yourself
1447 * runnable without the overhead of this.
1448 *
1449 * returns failure only if the task is already active.
1450 */
1451 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1452 {
1453 int cpu, this_cpu, success = 0;
1454 unsigned long flags;
1455 long old_state;
1456 struct rq *rq;
1457 #ifdef CONFIG_SMP
1458 struct sched_domain *sd, *this_sd = NULL;
1459 unsigned long load, this_load;
1460 int new_cpu;
1461 #endif
1462
1463 rq = task_rq_lock(p, &flags);
1464 old_state = p->state;
1465 if (!(old_state & state))
1466 goto out;
1467
1468 if (p->se.on_rq)
1469 goto out_running;
1470
1471 cpu = task_cpu(p);
1472 this_cpu = smp_processor_id();
1473
1474 #ifdef CONFIG_SMP
1475 if (unlikely(task_running(rq, p)))
1476 goto out_activate;
1477
1478 new_cpu = cpu;
1479
1480 schedstat_inc(rq, ttwu_cnt);
1481 if (cpu == this_cpu) {
1482 schedstat_inc(rq, ttwu_local);
1483 goto out_set_cpu;
1484 }
1485
1486 for_each_domain(this_cpu, sd) {
1487 if (cpu_isset(cpu, sd->span)) {
1488 schedstat_inc(sd, ttwu_wake_remote);
1489 this_sd = sd;
1490 break;
1491 }
1492 }
1493
1494 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1495 goto out_set_cpu;
1496
1497 /*
1498 * Check for affine wakeup and passive balancing possibilities.
1499 */
1500 if (this_sd) {
1501 int idx = this_sd->wake_idx;
1502 unsigned int imbalance;
1503
1504 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1505
1506 load = source_load(cpu, idx);
1507 this_load = target_load(this_cpu, idx);
1508
1509 new_cpu = this_cpu; /* Wake to this CPU if we can */
1510
1511 if (this_sd->flags & SD_WAKE_AFFINE) {
1512 unsigned long tl = this_load;
1513 unsigned long tl_per_task;
1514
1515 tl_per_task = cpu_avg_load_per_task(this_cpu);
1516
1517 /*
1518 * If sync wakeup then subtract the (maximum possible)
1519 * effect of the currently running task from the load
1520 * of the current CPU:
1521 */
1522 if (sync)
1523 tl -= current->se.load.weight;
1524
1525 if ((tl <= load &&
1526 tl + target_load(cpu, idx) <= tl_per_task) ||
1527 100*(tl + p->se.load.weight) <= imbalance*load) {
1528 /*
1529 * This domain has SD_WAKE_AFFINE and
1530 * p is cache cold in this domain, and
1531 * there is no bad imbalance.
1532 */
1533 schedstat_inc(this_sd, ttwu_move_affine);
1534 goto out_set_cpu;
1535 }
1536 }
1537
1538 /*
1539 * Start passive balancing when half the imbalance_pct
1540 * limit is reached.
1541 */
1542 if (this_sd->flags & SD_WAKE_BALANCE) {
1543 if (imbalance*this_load <= 100*load) {
1544 schedstat_inc(this_sd, ttwu_move_balance);
1545 goto out_set_cpu;
1546 }
1547 }
1548 }
1549
1550 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1551 out_set_cpu:
1552 new_cpu = wake_idle(new_cpu, p);
1553 if (new_cpu != cpu) {
1554 set_task_cpu(p, new_cpu);
1555 task_rq_unlock(rq, &flags);
1556 /* might preempt at this point */
1557 rq = task_rq_lock(p, &flags);
1558 old_state = p->state;
1559 if (!(old_state & state))
1560 goto out;
1561 if (p->se.on_rq)
1562 goto out_running;
1563
1564 this_cpu = smp_processor_id();
1565 cpu = task_cpu(p);
1566 }
1567
1568 out_activate:
1569 #endif /* CONFIG_SMP */
1570 update_rq_clock(rq);
1571 activate_task(rq, p, 1);
1572 /*
1573 * Sync wakeups (i.e. those types of wakeups where the waker
1574 * has indicated that it will leave the CPU in short order)
1575 * don't trigger a preemption, if the woken up task will run on
1576 * this cpu. (in this case the 'I will reschedule' promise of
1577 * the waker guarantees that the freshly woken up task is going
1578 * to be considered on this CPU.)
1579 */
1580 if (!sync || cpu != this_cpu)
1581 check_preempt_curr(rq, p);
1582 success = 1;
1583
1584 out_running:
1585 p->state = TASK_RUNNING;
1586 out:
1587 task_rq_unlock(rq, &flags);
1588
1589 return success;
1590 }
1591
1592 int fastcall wake_up_process(struct task_struct *p)
1593 {
1594 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1595 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1596 }
1597 EXPORT_SYMBOL(wake_up_process);
1598
1599 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1600 {
1601 return try_to_wake_up(p, state, 0);
1602 }
1603
1604 /*
1605 * Perform scheduler related setup for a newly forked process p.
1606 * p is forked by current.
1607 *
1608 * __sched_fork() is basic setup used by init_idle() too:
1609 */
1610 static void __sched_fork(struct task_struct *p)
1611 {
1612 p->se.exec_start = 0;
1613 p->se.sum_exec_runtime = 0;
1614 p->se.prev_sum_exec_runtime = 0;
1615
1616 #ifdef CONFIG_SCHEDSTATS
1617 p->se.wait_start = 0;
1618 p->se.sum_sleep_runtime = 0;
1619 p->se.sleep_start = 0;
1620 p->se.block_start = 0;
1621 p->se.sleep_max = 0;
1622 p->se.block_max = 0;
1623 p->se.exec_max = 0;
1624 p->se.slice_max = 0;
1625 p->se.wait_max = 0;
1626 #endif
1627
1628 INIT_LIST_HEAD(&p->run_list);
1629 p->se.on_rq = 0;
1630
1631 #ifdef CONFIG_PREEMPT_NOTIFIERS
1632 INIT_HLIST_HEAD(&p->preempt_notifiers);
1633 #endif
1634
1635 /*
1636 * We mark the process as running here, but have not actually
1637 * inserted it onto the runqueue yet. This guarantees that
1638 * nobody will actually run it, and a signal or other external
1639 * event cannot wake it up and insert it on the runqueue either.
1640 */
1641 p->state = TASK_RUNNING;
1642 }
1643
1644 /*
1645 * fork()/clone()-time setup:
1646 */
1647 void sched_fork(struct task_struct *p, int clone_flags)
1648 {
1649 int cpu = get_cpu();
1650
1651 __sched_fork(p);
1652
1653 #ifdef CONFIG_SMP
1654 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1655 #endif
1656 __set_task_cpu(p, cpu);
1657
1658 /*
1659 * Make sure we do not leak PI boosting priority to the child:
1660 */
1661 p->prio = current->normal_prio;
1662
1663 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1664 if (likely(sched_info_on()))
1665 memset(&p->sched_info, 0, sizeof(p->sched_info));
1666 #endif
1667 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1668 p->oncpu = 0;
1669 #endif
1670 #ifdef CONFIG_PREEMPT
1671 /* Want to start with kernel preemption disabled. */
1672 task_thread_info(p)->preempt_count = 1;
1673 #endif
1674 put_cpu();
1675 }
1676
1677 /*
1678 * wake_up_new_task - wake up a newly created task for the first time.
1679 *
1680 * This function will do some initial scheduler statistics housekeeping
1681 * that must be done for every newly created context, then puts the task
1682 * on the runqueue and wakes it.
1683 */
1684 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1685 {
1686 unsigned long flags;
1687 struct rq *rq;
1688 int this_cpu;
1689
1690 rq = task_rq_lock(p, &flags);
1691 BUG_ON(p->state != TASK_RUNNING);
1692 this_cpu = smp_processor_id(); /* parent's CPU */
1693 update_rq_clock(rq);
1694
1695 p->prio = effective_prio(p);
1696
1697 if (rt_prio(p->prio))
1698 p->sched_class = &rt_sched_class;
1699 else
1700 p->sched_class = &fair_sched_class;
1701
1702 if (task_cpu(p) != this_cpu || !p->sched_class->task_new ||
1703 !current->se.on_rq) {
1704 activate_task(rq, p, 0);
1705 } else {
1706 /*
1707 * Let the scheduling class do new task startup
1708 * management (if any):
1709 */
1710 p->sched_class->task_new(rq, p);
1711 inc_nr_running(p, rq);
1712 }
1713 check_preempt_curr(rq, p);
1714 task_rq_unlock(rq, &flags);
1715 }
1716
1717 #ifdef CONFIG_PREEMPT_NOTIFIERS
1718
1719 /**
1720 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1721 * @notifier: notifier struct to register
1722 */
1723 void preempt_notifier_register(struct preempt_notifier *notifier)
1724 {
1725 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1726 }
1727 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1728
1729 /**
1730 * preempt_notifier_unregister - no longer interested in preemption notifications
1731 * @notifier: notifier struct to unregister
1732 *
1733 * This is safe to call from within a preemption notifier.
1734 */
1735 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1736 {
1737 hlist_del(&notifier->link);
1738 }
1739 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1740
1741 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1742 {
1743 struct preempt_notifier *notifier;
1744 struct hlist_node *node;
1745
1746 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1747 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1748 }
1749
1750 static void
1751 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1752 struct task_struct *next)
1753 {
1754 struct preempt_notifier *notifier;
1755 struct hlist_node *node;
1756
1757 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1758 notifier->ops->sched_out(notifier, next);
1759 }
1760
1761 #else
1762
1763 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1764 {
1765 }
1766
1767 static void
1768 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1769 struct task_struct *next)
1770 {
1771 }
1772
1773 #endif
1774
1775 /**
1776 * prepare_task_switch - prepare to switch tasks
1777 * @rq: the runqueue preparing to switch
1778 * @prev: the current task that is being switched out
1779 * @next: the task we are going to switch to.
1780 *
1781 * This is called with the rq lock held and interrupts off. It must
1782 * be paired with a subsequent finish_task_switch after the context
1783 * switch.
1784 *
1785 * prepare_task_switch sets up locking and calls architecture specific
1786 * hooks.
1787 */
1788 static inline void
1789 prepare_task_switch(struct rq *rq, struct task_struct *prev,
1790 struct task_struct *next)
1791 {
1792 fire_sched_out_preempt_notifiers(prev, next);
1793 prepare_lock_switch(rq, next);
1794 prepare_arch_switch(next);
1795 }
1796
1797 /**
1798 * finish_task_switch - clean up after a task-switch
1799 * @rq: runqueue associated with task-switch
1800 * @prev: the thread we just switched away from.
1801 *
1802 * finish_task_switch must be called after the context switch, paired
1803 * with a prepare_task_switch call before the context switch.
1804 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1805 * and do any other architecture-specific cleanup actions.
1806 *
1807 * Note that we may have delayed dropping an mm in context_switch(). If
1808 * so, we finish that here outside of the runqueue lock. (Doing it
1809 * with the lock held can cause deadlocks; see schedule() for
1810 * details.)
1811 */
1812 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1813 __releases(rq->lock)
1814 {
1815 struct mm_struct *mm = rq->prev_mm;
1816 long prev_state;
1817
1818 rq->prev_mm = NULL;
1819
1820 /*
1821 * A task struct has one reference for the use as "current".
1822 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1823 * schedule one last time. The schedule call will never return, and
1824 * the scheduled task must drop that reference.
1825 * The test for TASK_DEAD must occur while the runqueue locks are
1826 * still held, otherwise prev could be scheduled on another cpu, die
1827 * there before we look at prev->state, and then the reference would
1828 * be dropped twice.
1829 * Manfred Spraul <manfred@colorfullife.com>
1830 */
1831 prev_state = prev->state;
1832 finish_arch_switch(prev);
1833 finish_lock_switch(rq, prev);
1834 fire_sched_in_preempt_notifiers(current);
1835 if (mm)
1836 mmdrop(mm);
1837 if (unlikely(prev_state == TASK_DEAD)) {
1838 /*
1839 * Remove function-return probe instances associated with this
1840 * task and put them back on the free list.
1841 */
1842 kprobe_flush_task(prev);
1843 put_task_struct(prev);
1844 }
1845 }
1846
1847 /**
1848 * schedule_tail - first thing a freshly forked thread must call.
1849 * @prev: the thread we just switched away from.
1850 */
1851 asmlinkage void schedule_tail(struct task_struct *prev)
1852 __releases(rq->lock)
1853 {
1854 struct rq *rq = this_rq();
1855
1856 finish_task_switch(rq, prev);
1857 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1858 /* In this case, finish_task_switch does not reenable preemption */
1859 preempt_enable();
1860 #endif
1861 if (current->set_child_tid)
1862 put_user(current->pid, current->set_child_tid);
1863 }
1864
1865 /*
1866 * context_switch - switch to the new MM and the new
1867 * thread's register state.
1868 */
1869 static inline void
1870 context_switch(struct rq *rq, struct task_struct *prev,
1871 struct task_struct *next)
1872 {
1873 struct mm_struct *mm, *oldmm;
1874
1875 prepare_task_switch(rq, prev, next);
1876 mm = next->mm;
1877 oldmm = prev->active_mm;
1878 /*
1879 * For paravirt, this is coupled with an exit in switch_to to
1880 * combine the page table reload and the switch backend into
1881 * one hypercall.
1882 */
1883 arch_enter_lazy_cpu_mode();
1884
1885 if (unlikely(!mm)) {
1886 next->active_mm = oldmm;
1887 atomic_inc(&oldmm->mm_count);
1888 enter_lazy_tlb(oldmm, next);
1889 } else
1890 switch_mm(oldmm, mm, next);
1891
1892 if (unlikely(!prev->mm)) {
1893 prev->active_mm = NULL;
1894 rq->prev_mm = oldmm;
1895 }
1896 /*
1897 * Since the runqueue lock will be released by the next
1898 * task (which is an invalid locking op but in the case
1899 * of the scheduler it's an obvious special-case), so we
1900 * do an early lockdep release here:
1901 */
1902 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1903 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1904 #endif
1905
1906 /* Here we just switch the register state and the stack. */
1907 switch_to(prev, next, prev);
1908
1909 barrier();
1910 /*
1911 * this_rq must be evaluated again because prev may have moved
1912 * CPUs since it called schedule(), thus the 'rq' on its stack
1913 * frame will be invalid.
1914 */
1915 finish_task_switch(this_rq(), prev);
1916 }
1917
1918 /*
1919 * nr_running, nr_uninterruptible and nr_context_switches:
1920 *
1921 * externally visible scheduler statistics: current number of runnable
1922 * threads, current number of uninterruptible-sleeping threads, total
1923 * number of context switches performed since bootup.
1924 */
1925 unsigned long nr_running(void)
1926 {
1927 unsigned long i, sum = 0;
1928
1929 for_each_online_cpu(i)
1930 sum += cpu_rq(i)->nr_running;
1931
1932 return sum;
1933 }
1934
1935 unsigned long nr_uninterruptible(void)
1936 {
1937 unsigned long i, sum = 0;
1938
1939 for_each_possible_cpu(i)
1940 sum += cpu_rq(i)->nr_uninterruptible;
1941
1942 /*
1943 * Since we read the counters lockless, it might be slightly
1944 * inaccurate. Do not allow it to go below zero though:
1945 */
1946 if (unlikely((long)sum < 0))
1947 sum = 0;
1948
1949 return sum;
1950 }
1951
1952 unsigned long long nr_context_switches(void)
1953 {
1954 int i;
1955 unsigned long long sum = 0;
1956
1957 for_each_possible_cpu(i)
1958 sum += cpu_rq(i)->nr_switches;
1959
1960 return sum;
1961 }
1962
1963 unsigned long nr_iowait(void)
1964 {
1965 unsigned long i, sum = 0;
1966
1967 for_each_possible_cpu(i)
1968 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1969
1970 return sum;
1971 }
1972
1973 unsigned long nr_active(void)
1974 {
1975 unsigned long i, running = 0, uninterruptible = 0;
1976
1977 for_each_online_cpu(i) {
1978 running += cpu_rq(i)->nr_running;
1979 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1980 }
1981
1982 if (unlikely((long)uninterruptible < 0))
1983 uninterruptible = 0;
1984
1985 return running + uninterruptible;
1986 }
1987
1988 /*
1989 * Update rq->cpu_load[] statistics. This function is usually called every
1990 * scheduler tick (TICK_NSEC).
1991 */
1992 static void update_cpu_load(struct rq *this_rq)
1993 {
1994 unsigned long this_load = this_rq->load.weight;
1995 int i, scale;
1996
1997 this_rq->nr_load_updates++;
1998
1999 /* Update our load: */
2000 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2001 unsigned long old_load, new_load;
2002
2003 /* scale is effectively 1 << i now, and >> i divides by scale */
2004
2005 old_load = this_rq->cpu_load[i];
2006 new_load = this_load;
2007 /*
2008 * Round up the averaging division if load is increasing. This
2009 * prevents us from getting stuck on 9 if the load is 10, for
2010 * example.
2011 */
2012 if (new_load > old_load)
2013 new_load += scale-1;
2014 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2015 }
2016 }
2017
2018 #ifdef CONFIG_SMP
2019
2020 /*
2021 * double_rq_lock - safely lock two runqueues
2022 *
2023 * Note this does not disable interrupts like task_rq_lock,
2024 * you need to do so manually before calling.
2025 */
2026 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2027 __acquires(rq1->lock)
2028 __acquires(rq2->lock)
2029 {
2030 BUG_ON(!irqs_disabled());
2031 if (rq1 == rq2) {
2032 spin_lock(&rq1->lock);
2033 __acquire(rq2->lock); /* Fake it out ;) */
2034 } else {
2035 if (rq1 < rq2) {
2036 spin_lock(&rq1->lock);
2037 spin_lock(&rq2->lock);
2038 } else {
2039 spin_lock(&rq2->lock);
2040 spin_lock(&rq1->lock);
2041 }
2042 }
2043 update_rq_clock(rq1);
2044 update_rq_clock(rq2);
2045 }
2046
2047 /*
2048 * double_rq_unlock - safely unlock two runqueues
2049 *
2050 * Note this does not restore interrupts like task_rq_unlock,
2051 * you need to do so manually after calling.
2052 */
2053 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2054 __releases(rq1->lock)
2055 __releases(rq2->lock)
2056 {
2057 spin_unlock(&rq1->lock);
2058 if (rq1 != rq2)
2059 spin_unlock(&rq2->lock);
2060 else
2061 __release(rq2->lock);
2062 }
2063
2064 /*
2065 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2066 */
2067 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
2068 __releases(this_rq->lock)
2069 __acquires(busiest->lock)
2070 __acquires(this_rq->lock)
2071 {
2072 if (unlikely(!irqs_disabled())) {
2073 /* printk() doesn't work good under rq->lock */
2074 spin_unlock(&this_rq->lock);
2075 BUG_ON(1);
2076 }
2077 if (unlikely(!spin_trylock(&busiest->lock))) {
2078 if (busiest < this_rq) {
2079 spin_unlock(&this_rq->lock);
2080 spin_lock(&busiest->lock);
2081 spin_lock(&this_rq->lock);
2082 } else
2083 spin_lock(&busiest->lock);
2084 }
2085 }
2086
2087 /*
2088 * If dest_cpu is allowed for this process, migrate the task to it.
2089 * This is accomplished by forcing the cpu_allowed mask to only
2090 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2091 * the cpu_allowed mask is restored.
2092 */
2093 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2094 {
2095 struct migration_req req;
2096 unsigned long flags;
2097 struct rq *rq;
2098
2099 rq = task_rq_lock(p, &flags);
2100 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2101 || unlikely(cpu_is_offline(dest_cpu)))
2102 goto out;
2103
2104 /* force the process onto the specified CPU */
2105 if (migrate_task(p, dest_cpu, &req)) {
2106 /* Need to wait for migration thread (might exit: take ref). */
2107 struct task_struct *mt = rq->migration_thread;
2108
2109 get_task_struct(mt);
2110 task_rq_unlock(rq, &flags);
2111 wake_up_process(mt);
2112 put_task_struct(mt);
2113 wait_for_completion(&req.done);
2114
2115 return;
2116 }
2117 out:
2118 task_rq_unlock(rq, &flags);
2119 }
2120
2121 /*
2122 * sched_exec - execve() is a valuable balancing opportunity, because at
2123 * this point the task has the smallest effective memory and cache footprint.
2124 */
2125 void sched_exec(void)
2126 {
2127 int new_cpu, this_cpu = get_cpu();
2128 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2129 put_cpu();
2130 if (new_cpu != this_cpu)
2131 sched_migrate_task(current, new_cpu);
2132 }
2133
2134 /*
2135 * pull_task - move a task from a remote runqueue to the local runqueue.
2136 * Both runqueues must be locked.
2137 */
2138 static void pull_task(struct rq *src_rq, struct task_struct *p,
2139 struct rq *this_rq, int this_cpu)
2140 {
2141 deactivate_task(src_rq, p, 0);
2142 set_task_cpu(p, this_cpu);
2143 activate_task(this_rq, p, 0);
2144 /*
2145 * Note that idle threads have a prio of MAX_PRIO, for this test
2146 * to be always true for them.
2147 */
2148 check_preempt_curr(this_rq, p);
2149 }
2150
2151 /*
2152 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2153 */
2154 static
2155 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2156 struct sched_domain *sd, enum cpu_idle_type idle,
2157 int *all_pinned)
2158 {
2159 /*
2160 * We do not migrate tasks that are:
2161 * 1) running (obviously), or
2162 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2163 * 3) are cache-hot on their current CPU.
2164 */
2165 if (!cpu_isset(this_cpu, p->cpus_allowed))
2166 return 0;
2167 *all_pinned = 0;
2168
2169 if (task_running(rq, p))
2170 return 0;
2171
2172 return 1;
2173 }
2174
2175 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2176 unsigned long max_nr_move, unsigned long max_load_move,
2177 struct sched_domain *sd, enum cpu_idle_type idle,
2178 int *all_pinned, unsigned long *load_moved,
2179 int *this_best_prio, struct rq_iterator *iterator)
2180 {
2181 int pulled = 0, pinned = 0, skip_for_load;
2182 struct task_struct *p;
2183 long rem_load_move = max_load_move;
2184
2185 if (max_nr_move == 0 || max_load_move == 0)
2186 goto out;
2187
2188 pinned = 1;
2189
2190 /*
2191 * Start the load-balancing iterator:
2192 */
2193 p = iterator->start(iterator->arg);
2194 next:
2195 if (!p)
2196 goto out;
2197 /*
2198 * To help distribute high priority tasks accross CPUs we don't
2199 * skip a task if it will be the highest priority task (i.e. smallest
2200 * prio value) on its new queue regardless of its load weight
2201 */
2202 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2203 SCHED_LOAD_SCALE_FUZZ;
2204 if ((skip_for_load && p->prio >= *this_best_prio) ||
2205 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2206 p = iterator->next(iterator->arg);
2207 goto next;
2208 }
2209
2210 pull_task(busiest, p, this_rq, this_cpu);
2211 pulled++;
2212 rem_load_move -= p->se.load.weight;
2213
2214 /*
2215 * We only want to steal up to the prescribed number of tasks
2216 * and the prescribed amount of weighted load.
2217 */
2218 if (pulled < max_nr_move && rem_load_move > 0) {
2219 if (p->prio < *this_best_prio)
2220 *this_best_prio = p->prio;
2221 p = iterator->next(iterator->arg);
2222 goto next;
2223 }
2224 out:
2225 /*
2226 * Right now, this is the only place pull_task() is called,
2227 * so we can safely collect pull_task() stats here rather than
2228 * inside pull_task().
2229 */
2230 schedstat_add(sd, lb_gained[idle], pulled);
2231
2232 if (all_pinned)
2233 *all_pinned = pinned;
2234 *load_moved = max_load_move - rem_load_move;
2235 return pulled;
2236 }
2237
2238 /*
2239 * move_tasks tries to move up to max_load_move weighted load from busiest to
2240 * this_rq, as part of a balancing operation within domain "sd".
2241 * Returns 1 if successful and 0 otherwise.
2242 *
2243 * Called with both runqueues locked.
2244 */
2245 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2246 unsigned long max_load_move,
2247 struct sched_domain *sd, enum cpu_idle_type idle,
2248 int *all_pinned)
2249 {
2250 struct sched_class *class = sched_class_highest;
2251 unsigned long total_load_moved = 0;
2252 int this_best_prio = this_rq->curr->prio;
2253
2254 do {
2255 total_load_moved +=
2256 class->load_balance(this_rq, this_cpu, busiest,
2257 ULONG_MAX, max_load_move - total_load_moved,
2258 sd, idle, all_pinned, &this_best_prio);
2259 class = class->next;
2260 } while (class && max_load_move > total_load_moved);
2261
2262 return total_load_moved > 0;
2263 }
2264
2265 /*
2266 * move_one_task tries to move exactly one task from busiest to this_rq, as
2267 * part of active balancing operations within "domain".
2268 * Returns 1 if successful and 0 otherwise.
2269 *
2270 * Called with both runqueues locked.
2271 */
2272 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2273 struct sched_domain *sd, enum cpu_idle_type idle)
2274 {
2275 struct sched_class *class;
2276 int this_best_prio = MAX_PRIO;
2277
2278 for (class = sched_class_highest; class; class = class->next)
2279 if (class->load_balance(this_rq, this_cpu, busiest,
2280 1, ULONG_MAX, sd, idle, NULL,
2281 &this_best_prio))
2282 return 1;
2283
2284 return 0;
2285 }
2286
2287 /*
2288 * find_busiest_group finds and returns the busiest CPU group within the
2289 * domain. It calculates and returns the amount of weighted load which
2290 * should be moved to restore balance via the imbalance parameter.
2291 */
2292 static struct sched_group *
2293 find_busiest_group(struct sched_domain *sd, int this_cpu,
2294 unsigned long *imbalance, enum cpu_idle_type idle,
2295 int *sd_idle, cpumask_t *cpus, int *balance)
2296 {
2297 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2298 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2299 unsigned long max_pull;
2300 unsigned long busiest_load_per_task, busiest_nr_running;
2301 unsigned long this_load_per_task, this_nr_running;
2302 int load_idx;
2303 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2304 int power_savings_balance = 1;
2305 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2306 unsigned long min_nr_running = ULONG_MAX;
2307 struct sched_group *group_min = NULL, *group_leader = NULL;
2308 #endif
2309
2310 max_load = this_load = total_load = total_pwr = 0;
2311 busiest_load_per_task = busiest_nr_running = 0;
2312 this_load_per_task = this_nr_running = 0;
2313 if (idle == CPU_NOT_IDLE)
2314 load_idx = sd->busy_idx;
2315 else if (idle == CPU_NEWLY_IDLE)
2316 load_idx = sd->newidle_idx;
2317 else
2318 load_idx = sd->idle_idx;
2319
2320 do {
2321 unsigned long load, group_capacity;
2322 int local_group;
2323 int i;
2324 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2325 unsigned long sum_nr_running, sum_weighted_load;
2326
2327 local_group = cpu_isset(this_cpu, group->cpumask);
2328
2329 if (local_group)
2330 balance_cpu = first_cpu(group->cpumask);
2331
2332 /* Tally up the load of all CPUs in the group */
2333 sum_weighted_load = sum_nr_running = avg_load = 0;
2334
2335 for_each_cpu_mask(i, group->cpumask) {
2336 struct rq *rq;
2337
2338 if (!cpu_isset(i, *cpus))
2339 continue;
2340
2341 rq = cpu_rq(i);
2342
2343 if (*sd_idle && rq->nr_running)
2344 *sd_idle = 0;
2345
2346 /* Bias balancing toward cpus of our domain */
2347 if (local_group) {
2348 if (idle_cpu(i) && !first_idle_cpu) {
2349 first_idle_cpu = 1;
2350 balance_cpu = i;
2351 }
2352
2353 load = target_load(i, load_idx);
2354 } else
2355 load = source_load(i, load_idx);
2356
2357 avg_load += load;
2358 sum_nr_running += rq->nr_running;
2359 sum_weighted_load += weighted_cpuload(i);
2360 }
2361
2362 /*
2363 * First idle cpu or the first cpu(busiest) in this sched group
2364 * is eligible for doing load balancing at this and above
2365 * domains. In the newly idle case, we will allow all the cpu's
2366 * to do the newly idle load balance.
2367 */
2368 if (idle != CPU_NEWLY_IDLE && local_group &&
2369 balance_cpu != this_cpu && balance) {
2370 *balance = 0;
2371 goto ret;
2372 }
2373
2374 total_load += avg_load;
2375 total_pwr += group->__cpu_power;
2376
2377 /* Adjust by relative CPU power of the group */
2378 avg_load = sg_div_cpu_power(group,
2379 avg_load * SCHED_LOAD_SCALE);
2380
2381 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2382
2383 if (local_group) {
2384 this_load = avg_load;
2385 this = group;
2386 this_nr_running = sum_nr_running;
2387 this_load_per_task = sum_weighted_load;
2388 } else if (avg_load > max_load &&
2389 sum_nr_running > group_capacity) {
2390 max_load = avg_load;
2391 busiest = group;
2392 busiest_nr_running = sum_nr_running;
2393 busiest_load_per_task = sum_weighted_load;
2394 }
2395
2396 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2397 /*
2398 * Busy processors will not participate in power savings
2399 * balance.
2400 */
2401 if (idle == CPU_NOT_IDLE ||
2402 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2403 goto group_next;
2404
2405 /*
2406 * If the local group is idle or completely loaded
2407 * no need to do power savings balance at this domain
2408 */
2409 if (local_group && (this_nr_running >= group_capacity ||
2410 !this_nr_running))
2411 power_savings_balance = 0;
2412
2413 /*
2414 * If a group is already running at full capacity or idle,
2415 * don't include that group in power savings calculations
2416 */
2417 if (!power_savings_balance || sum_nr_running >= group_capacity
2418 || !sum_nr_running)
2419 goto group_next;
2420
2421 /*
2422 * Calculate the group which has the least non-idle load.
2423 * This is the group from where we need to pick up the load
2424 * for saving power
2425 */
2426 if ((sum_nr_running < min_nr_running) ||
2427 (sum_nr_running == min_nr_running &&
2428 first_cpu(group->cpumask) <
2429 first_cpu(group_min->cpumask))) {
2430 group_min = group;
2431 min_nr_running = sum_nr_running;
2432 min_load_per_task = sum_weighted_load /
2433 sum_nr_running;
2434 }
2435
2436 /*
2437 * Calculate the group which is almost near its
2438 * capacity but still has some space to pick up some load
2439 * from other group and save more power
2440 */
2441 if (sum_nr_running <= group_capacity - 1) {
2442 if (sum_nr_running > leader_nr_running ||
2443 (sum_nr_running == leader_nr_running &&
2444 first_cpu(group->cpumask) >
2445 first_cpu(group_leader->cpumask))) {
2446 group_leader = group;
2447 leader_nr_running = sum_nr_running;
2448 }
2449 }
2450 group_next:
2451 #endif
2452 group = group->next;
2453 } while (group != sd->groups);
2454
2455 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2456 goto out_balanced;
2457
2458 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2459
2460 if (this_load >= avg_load ||
2461 100*max_load <= sd->imbalance_pct*this_load)
2462 goto out_balanced;
2463
2464 busiest_load_per_task /= busiest_nr_running;
2465 /*
2466 * We're trying to get all the cpus to the average_load, so we don't
2467 * want to push ourselves above the average load, nor do we wish to
2468 * reduce the max loaded cpu below the average load, as either of these
2469 * actions would just result in more rebalancing later, and ping-pong
2470 * tasks around. Thus we look for the minimum possible imbalance.
2471 * Negative imbalances (*we* are more loaded than anyone else) will
2472 * be counted as no imbalance for these purposes -- we can't fix that
2473 * by pulling tasks to us. Be careful of negative numbers as they'll
2474 * appear as very large values with unsigned longs.
2475 */
2476 if (max_load <= busiest_load_per_task)
2477 goto out_balanced;
2478
2479 /*
2480 * In the presence of smp nice balancing, certain scenarios can have
2481 * max load less than avg load(as we skip the groups at or below
2482 * its cpu_power, while calculating max_load..)
2483 */
2484 if (max_load < avg_load) {
2485 *imbalance = 0;
2486 goto small_imbalance;
2487 }
2488
2489 /* Don't want to pull so many tasks that a group would go idle */
2490 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2491
2492 /* How much load to actually move to equalise the imbalance */
2493 *imbalance = min(max_pull * busiest->__cpu_power,
2494 (avg_load - this_load) * this->__cpu_power)
2495 / SCHED_LOAD_SCALE;
2496
2497 /*
2498 * if *imbalance is less than the average load per runnable task
2499 * there is no gaurantee that any tasks will be moved so we'll have
2500 * a think about bumping its value to force at least one task to be
2501 * moved
2502 */
2503 if (*imbalance < busiest_load_per_task) {
2504 unsigned long tmp, pwr_now, pwr_move;
2505 unsigned int imbn;
2506
2507 small_imbalance:
2508 pwr_move = pwr_now = 0;
2509 imbn = 2;
2510 if (this_nr_running) {
2511 this_load_per_task /= this_nr_running;
2512 if (busiest_load_per_task > this_load_per_task)
2513 imbn = 1;
2514 } else
2515 this_load_per_task = SCHED_LOAD_SCALE;
2516
2517 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2518 busiest_load_per_task * imbn) {
2519 *imbalance = busiest_load_per_task;
2520 return busiest;
2521 }
2522
2523 /*
2524 * OK, we don't have enough imbalance to justify moving tasks,
2525 * however we may be able to increase total CPU power used by
2526 * moving them.
2527 */
2528
2529 pwr_now += busiest->__cpu_power *
2530 min(busiest_load_per_task, max_load);
2531 pwr_now += this->__cpu_power *
2532 min(this_load_per_task, this_load);
2533 pwr_now /= SCHED_LOAD_SCALE;
2534
2535 /* Amount of load we'd subtract */
2536 tmp = sg_div_cpu_power(busiest,
2537 busiest_load_per_task * SCHED_LOAD_SCALE);
2538 if (max_load > tmp)
2539 pwr_move += busiest->__cpu_power *
2540 min(busiest_load_per_task, max_load - tmp);
2541
2542 /* Amount of load we'd add */
2543 if (max_load * busiest->__cpu_power <
2544 busiest_load_per_task * SCHED_LOAD_SCALE)
2545 tmp = sg_div_cpu_power(this,
2546 max_load * busiest->__cpu_power);
2547 else
2548 tmp = sg_div_cpu_power(this,
2549 busiest_load_per_task * SCHED_LOAD_SCALE);
2550 pwr_move += this->__cpu_power *
2551 min(this_load_per_task, this_load + tmp);
2552 pwr_move /= SCHED_LOAD_SCALE;
2553
2554 /* Move if we gain throughput */
2555 if (pwr_move > pwr_now)
2556 *imbalance = busiest_load_per_task;
2557 }
2558
2559 return busiest;
2560
2561 out_balanced:
2562 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2563 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2564 goto ret;
2565
2566 if (this == group_leader && group_leader != group_min) {
2567 *imbalance = min_load_per_task;
2568 return group_min;
2569 }
2570 #endif
2571 ret:
2572 *imbalance = 0;
2573 return NULL;
2574 }
2575
2576 /*
2577 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2578 */
2579 static struct rq *
2580 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
2581 unsigned long imbalance, cpumask_t *cpus)
2582 {
2583 struct rq *busiest = NULL, *rq;
2584 unsigned long max_load = 0;
2585 int i;
2586
2587 for_each_cpu_mask(i, group->cpumask) {
2588 unsigned long wl;
2589
2590 if (!cpu_isset(i, *cpus))
2591 continue;
2592
2593 rq = cpu_rq(i);
2594 wl = weighted_cpuload(i);
2595
2596 if (rq->nr_running == 1 && wl > imbalance)
2597 continue;
2598
2599 if (wl > max_load) {
2600 max_load = wl;
2601 busiest = rq;
2602 }
2603 }
2604
2605 return busiest;
2606 }
2607
2608 /*
2609 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2610 * so long as it is large enough.
2611 */
2612 #define MAX_PINNED_INTERVAL 512
2613
2614 /*
2615 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2616 * tasks if there is an imbalance.
2617 */
2618 static int load_balance(int this_cpu, struct rq *this_rq,
2619 struct sched_domain *sd, enum cpu_idle_type idle,
2620 int *balance)
2621 {
2622 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2623 struct sched_group *group;
2624 unsigned long imbalance;
2625 struct rq *busiest;
2626 cpumask_t cpus = CPU_MASK_ALL;
2627 unsigned long flags;
2628
2629 /*
2630 * When power savings policy is enabled for the parent domain, idle
2631 * sibling can pick up load irrespective of busy siblings. In this case,
2632 * let the state of idle sibling percolate up as CPU_IDLE, instead of
2633 * portraying it as CPU_NOT_IDLE.
2634 */
2635 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2636 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2637 sd_idle = 1;
2638
2639 schedstat_inc(sd, lb_cnt[idle]);
2640
2641 redo:
2642 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2643 &cpus, balance);
2644
2645 if (*balance == 0)
2646 goto out_balanced;
2647
2648 if (!group) {
2649 schedstat_inc(sd, lb_nobusyg[idle]);
2650 goto out_balanced;
2651 }
2652
2653 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2654 if (!busiest) {
2655 schedstat_inc(sd, lb_nobusyq[idle]);
2656 goto out_balanced;
2657 }
2658
2659 BUG_ON(busiest == this_rq);
2660
2661 schedstat_add(sd, lb_imbalance[idle], imbalance);
2662
2663 ld_moved = 0;
2664 if (busiest->nr_running > 1) {
2665 /*
2666 * Attempt to move tasks. If find_busiest_group has found
2667 * an imbalance but busiest->nr_running <= 1, the group is
2668 * still unbalanced. ld_moved simply stays zero, so it is
2669 * correctly treated as an imbalance.
2670 */
2671 local_irq_save(flags);
2672 double_rq_lock(this_rq, busiest);
2673 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2674 imbalance, sd, idle, &all_pinned);
2675 double_rq_unlock(this_rq, busiest);
2676 local_irq_restore(flags);
2677
2678 /*
2679 * some other cpu did the load balance for us.
2680 */
2681 if (ld_moved && this_cpu != smp_processor_id())
2682 resched_cpu(this_cpu);
2683
2684 /* All tasks on this runqueue were pinned by CPU affinity */
2685 if (unlikely(all_pinned)) {
2686 cpu_clear(cpu_of(busiest), cpus);
2687 if (!cpus_empty(cpus))
2688 goto redo;
2689 goto out_balanced;
2690 }
2691 }
2692
2693 if (!ld_moved) {
2694 schedstat_inc(sd, lb_failed[idle]);
2695 sd->nr_balance_failed++;
2696
2697 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2698
2699 spin_lock_irqsave(&busiest->lock, flags);
2700
2701 /* don't kick the migration_thread, if the curr
2702 * task on busiest cpu can't be moved to this_cpu
2703 */
2704 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2705 spin_unlock_irqrestore(&busiest->lock, flags);
2706 all_pinned = 1;
2707 goto out_one_pinned;
2708 }
2709
2710 if (!busiest->active_balance) {
2711 busiest->active_balance = 1;
2712 busiest->push_cpu = this_cpu;
2713 active_balance = 1;
2714 }
2715 spin_unlock_irqrestore(&busiest->lock, flags);
2716 if (active_balance)
2717 wake_up_process(busiest->migration_thread);
2718
2719 /*
2720 * We've kicked active balancing, reset the failure
2721 * counter.
2722 */
2723 sd->nr_balance_failed = sd->cache_nice_tries+1;
2724 }
2725 } else
2726 sd->nr_balance_failed = 0;
2727
2728 if (likely(!active_balance)) {
2729 /* We were unbalanced, so reset the balancing interval */
2730 sd->balance_interval = sd->min_interval;
2731 } else {
2732 /*
2733 * If we've begun active balancing, start to back off. This
2734 * case may not be covered by the all_pinned logic if there
2735 * is only 1 task on the busy runqueue (because we don't call
2736 * move_tasks).
2737 */
2738 if (sd->balance_interval < sd->max_interval)
2739 sd->balance_interval *= 2;
2740 }
2741
2742 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2743 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2744 return -1;
2745 return ld_moved;
2746
2747 out_balanced:
2748 schedstat_inc(sd, lb_balanced[idle]);
2749
2750 sd->nr_balance_failed = 0;
2751
2752 out_one_pinned:
2753 /* tune up the balancing interval */
2754 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2755 (sd->balance_interval < sd->max_interval))
2756 sd->balance_interval *= 2;
2757
2758 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2759 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2760 return -1;
2761 return 0;
2762 }
2763
2764 /*
2765 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2766 * tasks if there is an imbalance.
2767 *
2768 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
2769 * this_rq is locked.
2770 */
2771 static int
2772 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2773 {
2774 struct sched_group *group;
2775 struct rq *busiest = NULL;
2776 unsigned long imbalance;
2777 int ld_moved = 0;
2778 int sd_idle = 0;
2779 int all_pinned = 0;
2780 cpumask_t cpus = CPU_MASK_ALL;
2781
2782 /*
2783 * When power savings policy is enabled for the parent domain, idle
2784 * sibling can pick up load irrespective of busy siblings. In this case,
2785 * let the state of idle sibling percolate up as IDLE, instead of
2786 * portraying it as CPU_NOT_IDLE.
2787 */
2788 if (sd->flags & SD_SHARE_CPUPOWER &&
2789 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2790 sd_idle = 1;
2791
2792 schedstat_inc(sd, lb_cnt[CPU_NEWLY_IDLE]);
2793 redo:
2794 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
2795 &sd_idle, &cpus, NULL);
2796 if (!group) {
2797 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
2798 goto out_balanced;
2799 }
2800
2801 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
2802 &cpus);
2803 if (!busiest) {
2804 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
2805 goto out_balanced;
2806 }
2807
2808 BUG_ON(busiest == this_rq);
2809
2810 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
2811
2812 ld_moved = 0;
2813 if (busiest->nr_running > 1) {
2814 /* Attempt to move tasks */
2815 double_lock_balance(this_rq, busiest);
2816 /* this_rq->clock is already updated */
2817 update_rq_clock(busiest);
2818 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2819 imbalance, sd, CPU_NEWLY_IDLE,
2820 &all_pinned);
2821 spin_unlock(&busiest->lock);
2822
2823 if (unlikely(all_pinned)) {
2824 cpu_clear(cpu_of(busiest), cpus);
2825 if (!cpus_empty(cpus))
2826 goto redo;
2827 }
2828 }
2829
2830 if (!ld_moved) {
2831 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
2832 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2833 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2834 return -1;
2835 } else
2836 sd->nr_balance_failed = 0;
2837
2838 return ld_moved;
2839
2840 out_balanced:
2841 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
2842 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2843 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2844 return -1;
2845 sd->nr_balance_failed = 0;
2846
2847 return 0;
2848 }
2849
2850 /*
2851 * idle_balance is called by schedule() if this_cpu is about to become
2852 * idle. Attempts to pull tasks from other CPUs.
2853 */
2854 static void idle_balance(int this_cpu, struct rq *this_rq)
2855 {
2856 struct sched_domain *sd;
2857 int pulled_task = -1;
2858 unsigned long next_balance = jiffies + HZ;
2859
2860 for_each_domain(this_cpu, sd) {
2861 unsigned long interval;
2862
2863 if (!(sd->flags & SD_LOAD_BALANCE))
2864 continue;
2865
2866 if (sd->flags & SD_BALANCE_NEWIDLE)
2867 /* If we've pulled tasks over stop searching: */
2868 pulled_task = load_balance_newidle(this_cpu,
2869 this_rq, sd);
2870
2871 interval = msecs_to_jiffies(sd->balance_interval);
2872 if (time_after(next_balance, sd->last_balance + interval))
2873 next_balance = sd->last_balance + interval;
2874 if (pulled_task)
2875 break;
2876 }
2877 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
2878 /*
2879 * We are going idle. next_balance may be set based on
2880 * a busy processor. So reset next_balance.
2881 */
2882 this_rq->next_balance = next_balance;
2883 }
2884 }
2885
2886 /*
2887 * active_load_balance is run by migration threads. It pushes running tasks
2888 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2889 * running on each physical CPU where possible, and avoids physical /
2890 * logical imbalances.
2891 *
2892 * Called with busiest_rq locked.
2893 */
2894 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2895 {
2896 int target_cpu = busiest_rq->push_cpu;
2897 struct sched_domain *sd;
2898 struct rq *target_rq;
2899
2900 /* Is there any task to move? */
2901 if (busiest_rq->nr_running <= 1)
2902 return;
2903
2904 target_rq = cpu_rq(target_cpu);
2905
2906 /*
2907 * This condition is "impossible", if it occurs
2908 * we need to fix it. Originally reported by
2909 * Bjorn Helgaas on a 128-cpu setup.
2910 */
2911 BUG_ON(busiest_rq == target_rq);
2912
2913 /* move a task from busiest_rq to target_rq */
2914 double_lock_balance(busiest_rq, target_rq);
2915 update_rq_clock(busiest_rq);
2916 update_rq_clock(target_rq);
2917
2918 /* Search for an sd spanning us and the target CPU. */
2919 for_each_domain(target_cpu, sd) {
2920 if ((sd->flags & SD_LOAD_BALANCE) &&
2921 cpu_isset(busiest_cpu, sd->span))
2922 break;
2923 }
2924
2925 if (likely(sd)) {
2926 schedstat_inc(sd, alb_cnt);
2927
2928 if (move_one_task(target_rq, target_cpu, busiest_rq,
2929 sd, CPU_IDLE))
2930 schedstat_inc(sd, alb_pushed);
2931 else
2932 schedstat_inc(sd, alb_failed);
2933 }
2934 spin_unlock(&target_rq->lock);
2935 }
2936
2937 #ifdef CONFIG_NO_HZ
2938 static struct {
2939 atomic_t load_balancer;
2940 cpumask_t cpu_mask;
2941 } nohz ____cacheline_aligned = {
2942 .load_balancer = ATOMIC_INIT(-1),
2943 .cpu_mask = CPU_MASK_NONE,
2944 };
2945
2946 /*
2947 * This routine will try to nominate the ilb (idle load balancing)
2948 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
2949 * load balancing on behalf of all those cpus. If all the cpus in the system
2950 * go into this tickless mode, then there will be no ilb owner (as there is
2951 * no need for one) and all the cpus will sleep till the next wakeup event
2952 * arrives...
2953 *
2954 * For the ilb owner, tick is not stopped. And this tick will be used
2955 * for idle load balancing. ilb owner will still be part of
2956 * nohz.cpu_mask..
2957 *
2958 * While stopping the tick, this cpu will become the ilb owner if there
2959 * is no other owner. And will be the owner till that cpu becomes busy
2960 * or if all cpus in the system stop their ticks at which point
2961 * there is no need for ilb owner.
2962 *
2963 * When the ilb owner becomes busy, it nominates another owner, during the
2964 * next busy scheduler_tick()
2965 */
2966 int select_nohz_load_balancer(int stop_tick)
2967 {
2968 int cpu = smp_processor_id();
2969
2970 if (stop_tick) {
2971 cpu_set(cpu, nohz.cpu_mask);
2972 cpu_rq(cpu)->in_nohz_recently = 1;
2973
2974 /*
2975 * If we are going offline and still the leader, give up!
2976 */
2977 if (cpu_is_offline(cpu) &&
2978 atomic_read(&nohz.load_balancer) == cpu) {
2979 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
2980 BUG();
2981 return 0;
2982 }
2983
2984 /* time for ilb owner also to sleep */
2985 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
2986 if (atomic_read(&nohz.load_balancer) == cpu)
2987 atomic_set(&nohz.load_balancer, -1);
2988 return 0;
2989 }
2990
2991 if (atomic_read(&nohz.load_balancer) == -1) {
2992 /* make me the ilb owner */
2993 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
2994 return 1;
2995 } else if (atomic_read(&nohz.load_balancer) == cpu)
2996 return 1;
2997 } else {
2998 if (!cpu_isset(cpu, nohz.cpu_mask))
2999 return 0;
3000
3001 cpu_clear(cpu, nohz.cpu_mask);
3002
3003 if (atomic_read(&nohz.load_balancer) == cpu)
3004 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3005 BUG();
3006 }
3007 return 0;
3008 }
3009 #endif
3010
3011 static DEFINE_SPINLOCK(balancing);
3012
3013 /*
3014 * It checks each scheduling domain to see if it is due to be balanced,
3015 * and initiates a balancing operation if so.
3016 *
3017 * Balancing parameters are set up in arch_init_sched_domains.
3018 */
3019 static inline void rebalance_domains(int cpu, enum cpu_idle_type idle)
3020 {
3021 int balance = 1;
3022 struct rq *rq = cpu_rq(cpu);
3023 unsigned long interval;
3024 struct sched_domain *sd;
3025 /* Earliest time when we have to do rebalance again */
3026 unsigned long next_balance = jiffies + 60*HZ;
3027 int update_next_balance = 0;
3028
3029 for_each_domain(cpu, sd) {
3030 if (!(sd->flags & SD_LOAD_BALANCE))
3031 continue;
3032
3033 interval = sd->balance_interval;
3034 if (idle != CPU_IDLE)
3035 interval *= sd->busy_factor;
3036
3037 /* scale ms to jiffies */
3038 interval = msecs_to_jiffies(interval);
3039 if (unlikely(!interval))
3040 interval = 1;
3041 if (interval > HZ*NR_CPUS/10)
3042 interval = HZ*NR_CPUS/10;
3043
3044
3045 if (sd->flags & SD_SERIALIZE) {
3046 if (!spin_trylock(&balancing))
3047 goto out;
3048 }
3049
3050 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3051 if (load_balance(cpu, rq, sd, idle, &balance)) {
3052 /*
3053 * We've pulled tasks over so either we're no
3054 * longer idle, or one of our SMT siblings is
3055 * not idle.
3056 */
3057 idle = CPU_NOT_IDLE;
3058 }
3059 sd->last_balance = jiffies;
3060 }
3061 if (sd->flags & SD_SERIALIZE)
3062 spin_unlock(&balancing);
3063 out:
3064 if (time_after(next_balance, sd->last_balance + interval)) {
3065 next_balance = sd->last_balance + interval;
3066 update_next_balance = 1;
3067 }
3068
3069 /*
3070 * Stop the load balance at this level. There is another
3071 * CPU in our sched group which is doing load balancing more
3072 * actively.
3073 */
3074 if (!balance)
3075 break;
3076 }
3077
3078 /*
3079 * next_balance will be updated only when there is a need.
3080 * When the cpu is attached to null domain for ex, it will not be
3081 * updated.
3082 */
3083 if (likely(update_next_balance))
3084 rq->next_balance = next_balance;
3085 }
3086
3087 /*
3088 * run_rebalance_domains is triggered when needed from the scheduler tick.
3089 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3090 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3091 */
3092 static void run_rebalance_domains(struct softirq_action *h)
3093 {
3094 int this_cpu = smp_processor_id();
3095 struct rq *this_rq = cpu_rq(this_cpu);
3096 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3097 CPU_IDLE : CPU_NOT_IDLE;
3098
3099 rebalance_domains(this_cpu, idle);
3100
3101 #ifdef CONFIG_NO_HZ
3102 /*
3103 * If this cpu is the owner for idle load balancing, then do the
3104 * balancing on behalf of the other idle cpus whose ticks are
3105 * stopped.
3106 */
3107 if (this_rq->idle_at_tick &&
3108 atomic_read(&nohz.load_balancer) == this_cpu) {
3109 cpumask_t cpus = nohz.cpu_mask;
3110 struct rq *rq;
3111 int balance_cpu;
3112
3113 cpu_clear(this_cpu, cpus);
3114 for_each_cpu_mask(balance_cpu, cpus) {
3115 /*
3116 * If this cpu gets work to do, stop the load balancing
3117 * work being done for other cpus. Next load
3118 * balancing owner will pick it up.
3119 */
3120 if (need_resched())
3121 break;
3122
3123 rebalance_domains(balance_cpu, CPU_IDLE);
3124
3125 rq = cpu_rq(balance_cpu);
3126 if (time_after(this_rq->next_balance, rq->next_balance))
3127 this_rq->next_balance = rq->next_balance;
3128 }
3129 }
3130 #endif
3131 }
3132
3133 /*
3134 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3135 *
3136 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3137 * idle load balancing owner or decide to stop the periodic load balancing,
3138 * if the whole system is idle.
3139 */
3140 static inline void trigger_load_balance(struct rq *rq, int cpu)
3141 {
3142 #ifdef CONFIG_NO_HZ
3143 /*
3144 * If we were in the nohz mode recently and busy at the current
3145 * scheduler tick, then check if we need to nominate new idle
3146 * load balancer.
3147 */
3148 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3149 rq->in_nohz_recently = 0;
3150
3151 if (atomic_read(&nohz.load_balancer) == cpu) {
3152 cpu_clear(cpu, nohz.cpu_mask);
3153 atomic_set(&nohz.load_balancer, -1);
3154 }
3155
3156 if (atomic_read(&nohz.load_balancer) == -1) {
3157 /*
3158 * simple selection for now: Nominate the
3159 * first cpu in the nohz list to be the next
3160 * ilb owner.
3161 *
3162 * TBD: Traverse the sched domains and nominate
3163 * the nearest cpu in the nohz.cpu_mask.
3164 */
3165 int ilb = first_cpu(nohz.cpu_mask);
3166
3167 if (ilb != NR_CPUS)
3168 resched_cpu(ilb);
3169 }
3170 }
3171
3172 /*
3173 * If this cpu is idle and doing idle load balancing for all the
3174 * cpus with ticks stopped, is it time for that to stop?
3175 */
3176 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3177 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3178 resched_cpu(cpu);
3179 return;
3180 }
3181
3182 /*
3183 * If this cpu is idle and the idle load balancing is done by
3184 * someone else, then no need raise the SCHED_SOFTIRQ
3185 */
3186 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3187 cpu_isset(cpu, nohz.cpu_mask))
3188 return;
3189 #endif
3190 if (time_after_eq(jiffies, rq->next_balance))
3191 raise_softirq(SCHED_SOFTIRQ);
3192 }
3193
3194 #else /* CONFIG_SMP */
3195
3196 /*
3197 * on UP we do not need to balance between CPUs:
3198 */
3199 static inline void idle_balance(int cpu, struct rq *rq)
3200 {
3201 }
3202
3203 /* Avoid "used but not defined" warning on UP */
3204 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3205 unsigned long max_nr_move, unsigned long max_load_move,
3206 struct sched_domain *sd, enum cpu_idle_type idle,
3207 int *all_pinned, unsigned long *load_moved,
3208 int *this_best_prio, struct rq_iterator *iterator)
3209 {
3210 *load_moved = 0;
3211
3212 return 0;
3213 }
3214
3215 #endif
3216
3217 DEFINE_PER_CPU(struct kernel_stat, kstat);
3218
3219 EXPORT_PER_CPU_SYMBOL(kstat);
3220
3221 /*
3222 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3223 * that have not yet been banked in case the task is currently running.
3224 */
3225 unsigned long long task_sched_runtime(struct task_struct *p)
3226 {
3227 unsigned long flags;
3228 u64 ns, delta_exec;
3229 struct rq *rq;
3230
3231 rq = task_rq_lock(p, &flags);
3232 ns = p->se.sum_exec_runtime;
3233 if (rq->curr == p) {
3234 update_rq_clock(rq);
3235 delta_exec = rq->clock - p->se.exec_start;
3236 if ((s64)delta_exec > 0)
3237 ns += delta_exec;
3238 }
3239 task_rq_unlock(rq, &flags);
3240
3241 return ns;
3242 }
3243
3244 /*
3245 * Account user cpu time to a process.
3246 * @p: the process that the cpu time gets accounted to
3247 * @hardirq_offset: the offset to subtract from hardirq_count()
3248 * @cputime: the cpu time spent in user space since the last update
3249 */
3250 void account_user_time(struct task_struct *p, cputime_t cputime)
3251 {
3252 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3253 cputime64_t tmp;
3254
3255 p->utime = cputime_add(p->utime, cputime);
3256
3257 /* Add user time to cpustat. */
3258 tmp = cputime_to_cputime64(cputime);
3259 if (TASK_NICE(p) > 0)
3260 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3261 else
3262 cpustat->user = cputime64_add(cpustat->user, tmp);
3263 }
3264
3265 /*
3266 * Account system cpu time to a process.
3267 * @p: the process that the cpu time gets accounted to
3268 * @hardirq_offset: the offset to subtract from hardirq_count()
3269 * @cputime: the cpu time spent in kernel space since the last update
3270 */
3271 void account_system_time(struct task_struct *p, int hardirq_offset,
3272 cputime_t cputime)
3273 {
3274 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3275 struct rq *rq = this_rq();
3276 cputime64_t tmp;
3277
3278 p->stime = cputime_add(p->stime, cputime);
3279
3280 /* Add system time to cpustat. */
3281 tmp = cputime_to_cputime64(cputime);
3282 if (hardirq_count() - hardirq_offset)
3283 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3284 else if (softirq_count())
3285 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3286 else if (p != rq->idle)
3287 cpustat->system = cputime64_add(cpustat->system, tmp);
3288 else if (atomic_read(&rq->nr_iowait) > 0)
3289 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3290 else
3291 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3292 /* Account for system time used */
3293 acct_update_integrals(p);
3294 }
3295
3296 /*
3297 * Account for involuntary wait time.
3298 * @p: the process from which the cpu time has been stolen
3299 * @steal: the cpu time spent in involuntary wait
3300 */
3301 void account_steal_time(struct task_struct *p, cputime_t steal)
3302 {
3303 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3304 cputime64_t tmp = cputime_to_cputime64(steal);
3305 struct rq *rq = this_rq();
3306
3307 if (p == rq->idle) {
3308 p->stime = cputime_add(p->stime, steal);
3309 if (atomic_read(&rq->nr_iowait) > 0)
3310 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3311 else
3312 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3313 } else
3314 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3315 }
3316
3317 /*
3318 * This function gets called by the timer code, with HZ frequency.
3319 * We call it with interrupts disabled.
3320 *
3321 * It also gets called by the fork code, when changing the parent's
3322 * timeslices.
3323 */
3324 void scheduler_tick(void)
3325 {
3326 int cpu = smp_processor_id();
3327 struct rq *rq = cpu_rq(cpu);
3328 struct task_struct *curr = rq->curr;
3329 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3330
3331 spin_lock(&rq->lock);
3332 __update_rq_clock(rq);
3333 /*
3334 * Let rq->clock advance by at least TICK_NSEC:
3335 */
3336 if (unlikely(rq->clock < next_tick))
3337 rq->clock = next_tick;
3338 rq->tick_timestamp = rq->clock;
3339 update_cpu_load(rq);
3340 if (curr != rq->idle) /* FIXME: needed? */
3341 curr->sched_class->task_tick(rq, curr);
3342 spin_unlock(&rq->lock);
3343
3344 #ifdef CONFIG_SMP
3345 rq->idle_at_tick = idle_cpu(cpu);
3346 trigger_load_balance(rq, cpu);
3347 #endif
3348 }
3349
3350 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3351
3352 void fastcall add_preempt_count(int val)
3353 {
3354 /*
3355 * Underflow?
3356 */
3357 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3358 return;
3359 preempt_count() += val;
3360 /*
3361 * Spinlock count overflowing soon?
3362 */
3363 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3364 PREEMPT_MASK - 10);
3365 }
3366 EXPORT_SYMBOL(add_preempt_count);
3367
3368 void fastcall sub_preempt_count(int val)
3369 {
3370 /*
3371 * Underflow?
3372 */
3373 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3374 return;
3375 /*
3376 * Is the spinlock portion underflowing?
3377 */
3378 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3379 !(preempt_count() & PREEMPT_MASK)))
3380 return;
3381
3382 preempt_count() -= val;
3383 }
3384 EXPORT_SYMBOL(sub_preempt_count);
3385
3386 #endif
3387
3388 /*
3389 * Print scheduling while atomic bug:
3390 */
3391 static noinline void __schedule_bug(struct task_struct *prev)
3392 {
3393 printk(KERN_ERR "BUG: scheduling while atomic: %s/0x%08x/%d\n",
3394 prev->comm, preempt_count(), prev->pid);
3395 debug_show_held_locks(prev);
3396 if (irqs_disabled())
3397 print_irqtrace_events(prev);
3398 dump_stack();
3399 }
3400
3401 /*
3402 * Various schedule()-time debugging checks and statistics:
3403 */
3404 static inline void schedule_debug(struct task_struct *prev)
3405 {
3406 /*
3407 * Test if we are atomic. Since do_exit() needs to call into
3408 * schedule() atomically, we ignore that path for now.
3409 * Otherwise, whine if we are scheduling when we should not be.
3410 */
3411 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3412 __schedule_bug(prev);
3413
3414 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3415
3416 schedstat_inc(this_rq(), sched_cnt);
3417 }
3418
3419 /*
3420 * Pick up the highest-prio task:
3421 */
3422 static inline struct task_struct *
3423 pick_next_task(struct rq *rq, struct task_struct *prev)
3424 {
3425 struct sched_class *class;
3426 struct task_struct *p;
3427
3428 /*
3429 * Optimization: we know that if all tasks are in
3430 * the fair class we can call that function directly:
3431 */
3432 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3433 p = fair_sched_class.pick_next_task(rq);
3434 if (likely(p))
3435 return p;
3436 }
3437
3438 class = sched_class_highest;
3439 for ( ; ; ) {
3440 p = class->pick_next_task(rq);
3441 if (p)
3442 return p;
3443 /*
3444 * Will never be NULL as the idle class always
3445 * returns a non-NULL p:
3446 */
3447 class = class->next;
3448 }
3449 }
3450
3451 /*
3452 * schedule() is the main scheduler function.
3453 */
3454 asmlinkage void __sched schedule(void)
3455 {
3456 struct task_struct *prev, *next;
3457 long *switch_count;
3458 struct rq *rq;
3459 int cpu;
3460
3461 need_resched:
3462 preempt_disable();
3463 cpu = smp_processor_id();
3464 rq = cpu_rq(cpu);
3465 rcu_qsctr_inc(cpu);
3466 prev = rq->curr;
3467 switch_count = &prev->nivcsw;
3468
3469 release_kernel_lock(prev);
3470 need_resched_nonpreemptible:
3471
3472 schedule_debug(prev);
3473
3474 spin_lock_irq(&rq->lock);
3475 clear_tsk_need_resched(prev);
3476 __update_rq_clock(rq);
3477
3478 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3479 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3480 unlikely(signal_pending(prev)))) {
3481 prev->state = TASK_RUNNING;
3482 } else {
3483 deactivate_task(rq, prev, 1);
3484 }
3485 switch_count = &prev->nvcsw;
3486 }
3487
3488 if (unlikely(!rq->nr_running))
3489 idle_balance(cpu, rq);
3490
3491 prev->sched_class->put_prev_task(rq, prev);
3492 next = pick_next_task(rq, prev);
3493
3494 sched_info_switch(prev, next);
3495
3496 if (likely(prev != next)) {
3497 rq->nr_switches++;
3498 rq->curr = next;
3499 ++*switch_count;
3500
3501 context_switch(rq, prev, next); /* unlocks the rq */
3502 } else
3503 spin_unlock_irq(&rq->lock);
3504
3505 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3506 cpu = smp_processor_id();
3507 rq = cpu_rq(cpu);
3508 goto need_resched_nonpreemptible;
3509 }
3510 preempt_enable_no_resched();
3511 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3512 goto need_resched;
3513 }
3514 EXPORT_SYMBOL(schedule);
3515
3516 #ifdef CONFIG_PREEMPT
3517 /*
3518 * this is the entry point to schedule() from in-kernel preemption
3519 * off of preempt_enable. Kernel preemptions off return from interrupt
3520 * occur there and call schedule directly.
3521 */
3522 asmlinkage void __sched preempt_schedule(void)
3523 {
3524 struct thread_info *ti = current_thread_info();
3525 #ifdef CONFIG_PREEMPT_BKL
3526 struct task_struct *task = current;
3527 int saved_lock_depth;
3528 #endif
3529 /*
3530 * If there is a non-zero preempt_count or interrupts are disabled,
3531 * we do not want to preempt the current task. Just return..
3532 */
3533 if (likely(ti->preempt_count || irqs_disabled()))
3534 return;
3535
3536 need_resched:
3537 add_preempt_count(PREEMPT_ACTIVE);
3538 /*
3539 * We keep the big kernel semaphore locked, but we
3540 * clear ->lock_depth so that schedule() doesnt
3541 * auto-release the semaphore:
3542 */
3543 #ifdef CONFIG_PREEMPT_BKL
3544 saved_lock_depth = task->lock_depth;
3545 task->lock_depth = -1;
3546 #endif
3547 schedule();
3548 #ifdef CONFIG_PREEMPT_BKL
3549 task->lock_depth = saved_lock_depth;
3550 #endif
3551 sub_preempt_count(PREEMPT_ACTIVE);
3552
3553 /* we could miss a preemption opportunity between schedule and now */
3554 barrier();
3555 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3556 goto need_resched;
3557 }
3558 EXPORT_SYMBOL(preempt_schedule);
3559
3560 /*
3561 * this is the entry point to schedule() from kernel preemption
3562 * off of irq context.
3563 * Note, that this is called and return with irqs disabled. This will
3564 * protect us against recursive calling from irq.
3565 */
3566 asmlinkage void __sched preempt_schedule_irq(void)
3567 {
3568 struct thread_info *ti = current_thread_info();
3569 #ifdef CONFIG_PREEMPT_BKL
3570 struct task_struct *task = current;
3571 int saved_lock_depth;
3572 #endif
3573 /* Catch callers which need to be fixed */
3574 BUG_ON(ti->preempt_count || !irqs_disabled());
3575
3576 need_resched:
3577 add_preempt_count(PREEMPT_ACTIVE);
3578 /*
3579 * We keep the big kernel semaphore locked, but we
3580 * clear ->lock_depth so that schedule() doesnt
3581 * auto-release the semaphore:
3582 */
3583 #ifdef CONFIG_PREEMPT_BKL
3584 saved_lock_depth = task->lock_depth;
3585 task->lock_depth = -1;
3586 #endif
3587 local_irq_enable();
3588 schedule();
3589 local_irq_disable();
3590 #ifdef CONFIG_PREEMPT_BKL
3591 task->lock_depth = saved_lock_depth;
3592 #endif
3593 sub_preempt_count(PREEMPT_ACTIVE);
3594
3595 /* we could miss a preemption opportunity between schedule and now */
3596 barrier();
3597 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3598 goto need_resched;
3599 }
3600
3601 #endif /* CONFIG_PREEMPT */
3602
3603 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3604 void *key)
3605 {
3606 return try_to_wake_up(curr->private, mode, sync);
3607 }
3608 EXPORT_SYMBOL(default_wake_function);
3609
3610 /*
3611 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3612 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3613 * number) then we wake all the non-exclusive tasks and one exclusive task.
3614 *
3615 * There are circumstances in which we can try to wake a task which has already
3616 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3617 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3618 */
3619 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3620 int nr_exclusive, int sync, void *key)
3621 {
3622 wait_queue_t *curr, *next;
3623
3624 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3625 unsigned flags = curr->flags;
3626
3627 if (curr->func(curr, mode, sync, key) &&
3628 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3629 break;
3630 }
3631 }
3632
3633 /**
3634 * __wake_up - wake up threads blocked on a waitqueue.
3635 * @q: the waitqueue
3636 * @mode: which threads
3637 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3638 * @key: is directly passed to the wakeup function
3639 */
3640 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3641 int nr_exclusive, void *key)
3642 {
3643 unsigned long flags;
3644
3645 spin_lock_irqsave(&q->lock, flags);
3646 __wake_up_common(q, mode, nr_exclusive, 0, key);
3647 spin_unlock_irqrestore(&q->lock, flags);
3648 }
3649 EXPORT_SYMBOL(__wake_up);
3650
3651 /*
3652 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3653 */
3654 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3655 {
3656 __wake_up_common(q, mode, 1, 0, NULL);
3657 }
3658
3659 /**
3660 * __wake_up_sync - wake up threads blocked on a waitqueue.
3661 * @q: the waitqueue
3662 * @mode: which threads
3663 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3664 *
3665 * The sync wakeup differs that the waker knows that it will schedule
3666 * away soon, so while the target thread will be woken up, it will not
3667 * be migrated to another CPU - ie. the two threads are 'synchronized'
3668 * with each other. This can prevent needless bouncing between CPUs.
3669 *
3670 * On UP it can prevent extra preemption.
3671 */
3672 void fastcall
3673 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3674 {
3675 unsigned long flags;
3676 int sync = 1;
3677
3678 if (unlikely(!q))
3679 return;
3680
3681 if (unlikely(!nr_exclusive))
3682 sync = 0;
3683
3684 spin_lock_irqsave(&q->lock, flags);
3685 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3686 spin_unlock_irqrestore(&q->lock, flags);
3687 }
3688 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3689
3690 void fastcall complete(struct completion *x)
3691 {
3692 unsigned long flags;
3693
3694 spin_lock_irqsave(&x->wait.lock, flags);
3695 x->done++;
3696 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3697 1, 0, NULL);
3698 spin_unlock_irqrestore(&x->wait.lock, flags);
3699 }
3700 EXPORT_SYMBOL(complete);
3701
3702 void fastcall complete_all(struct completion *x)
3703 {
3704 unsigned long flags;
3705
3706 spin_lock_irqsave(&x->wait.lock, flags);
3707 x->done += UINT_MAX/2;
3708 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3709 0, 0, NULL);
3710 spin_unlock_irqrestore(&x->wait.lock, flags);
3711 }
3712 EXPORT_SYMBOL(complete_all);
3713
3714 void fastcall __sched wait_for_completion(struct completion *x)
3715 {
3716 might_sleep();
3717
3718 spin_lock_irq(&x->wait.lock);
3719 if (!x->done) {
3720 DECLARE_WAITQUEUE(wait, current);
3721
3722 wait.flags |= WQ_FLAG_EXCLUSIVE;
3723 __add_wait_queue_tail(&x->wait, &wait);
3724 do {
3725 __set_current_state(TASK_UNINTERRUPTIBLE);
3726 spin_unlock_irq(&x->wait.lock);
3727 schedule();
3728 spin_lock_irq(&x->wait.lock);
3729 } while (!x->done);
3730 __remove_wait_queue(&x->wait, &wait);
3731 }
3732 x->done--;
3733 spin_unlock_irq(&x->wait.lock);
3734 }
3735 EXPORT_SYMBOL(wait_for_completion);
3736
3737 unsigned long fastcall __sched
3738 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3739 {
3740 might_sleep();
3741
3742 spin_lock_irq(&x->wait.lock);
3743 if (!x->done) {
3744 DECLARE_WAITQUEUE(wait, current);
3745
3746 wait.flags |= WQ_FLAG_EXCLUSIVE;
3747 __add_wait_queue_tail(&x->wait, &wait);
3748 do {
3749 __set_current_state(TASK_UNINTERRUPTIBLE);
3750 spin_unlock_irq(&x->wait.lock);
3751 timeout = schedule_timeout(timeout);
3752 spin_lock_irq(&x->wait.lock);
3753 if (!timeout) {
3754 __remove_wait_queue(&x->wait, &wait);
3755 goto out;
3756 }
3757 } while (!x->done);
3758 __remove_wait_queue(&x->wait, &wait);
3759 }
3760 x->done--;
3761 out:
3762 spin_unlock_irq(&x->wait.lock);
3763 return timeout;
3764 }
3765 EXPORT_SYMBOL(wait_for_completion_timeout);
3766
3767 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3768 {
3769 int ret = 0;
3770
3771 might_sleep();
3772
3773 spin_lock_irq(&x->wait.lock);
3774 if (!x->done) {
3775 DECLARE_WAITQUEUE(wait, current);
3776
3777 wait.flags |= WQ_FLAG_EXCLUSIVE;
3778 __add_wait_queue_tail(&x->wait, &wait);
3779 do {
3780 if (signal_pending(current)) {
3781 ret = -ERESTARTSYS;
3782 __remove_wait_queue(&x->wait, &wait);
3783 goto out;
3784 }
3785 __set_current_state(TASK_INTERRUPTIBLE);
3786 spin_unlock_irq(&x->wait.lock);
3787 schedule();
3788 spin_lock_irq(&x->wait.lock);
3789 } while (!x->done);
3790 __remove_wait_queue(&x->wait, &wait);
3791 }
3792 x->done--;
3793 out:
3794 spin_unlock_irq(&x->wait.lock);
3795
3796 return ret;
3797 }
3798 EXPORT_SYMBOL(wait_for_completion_interruptible);
3799
3800 unsigned long fastcall __sched
3801 wait_for_completion_interruptible_timeout(struct completion *x,
3802 unsigned long timeout)
3803 {
3804 might_sleep();
3805
3806 spin_lock_irq(&x->wait.lock);
3807 if (!x->done) {
3808 DECLARE_WAITQUEUE(wait, current);
3809
3810 wait.flags |= WQ_FLAG_EXCLUSIVE;
3811 __add_wait_queue_tail(&x->wait, &wait);
3812 do {
3813 if (signal_pending(current)) {
3814 timeout = -ERESTARTSYS;
3815 __remove_wait_queue(&x->wait, &wait);
3816 goto out;
3817 }
3818 __set_current_state(TASK_INTERRUPTIBLE);
3819 spin_unlock_irq(&x->wait.lock);
3820 timeout = schedule_timeout(timeout);
3821 spin_lock_irq(&x->wait.lock);
3822 if (!timeout) {
3823 __remove_wait_queue(&x->wait, &wait);
3824 goto out;
3825 }
3826 } while (!x->done);
3827 __remove_wait_queue(&x->wait, &wait);
3828 }
3829 x->done--;
3830 out:
3831 spin_unlock_irq(&x->wait.lock);
3832 return timeout;
3833 }
3834 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3835
3836 static inline void
3837 sleep_on_head(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3838 {
3839 spin_lock_irqsave(&q->lock, *flags);
3840 __add_wait_queue(q, wait);
3841 spin_unlock(&q->lock);
3842 }
3843
3844 static inline void
3845 sleep_on_tail(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3846 {
3847 spin_lock_irq(&q->lock);
3848 __remove_wait_queue(q, wait);
3849 spin_unlock_irqrestore(&q->lock, *flags);
3850 }
3851
3852 void __sched interruptible_sleep_on(wait_queue_head_t *q)
3853 {
3854 unsigned long flags;
3855 wait_queue_t wait;
3856
3857 init_waitqueue_entry(&wait, current);
3858
3859 current->state = TASK_INTERRUPTIBLE;
3860
3861 sleep_on_head(q, &wait, &flags);
3862 schedule();
3863 sleep_on_tail(q, &wait, &flags);
3864 }
3865 EXPORT_SYMBOL(interruptible_sleep_on);
3866
3867 long __sched
3868 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3869 {
3870 unsigned long flags;
3871 wait_queue_t wait;
3872
3873 init_waitqueue_entry(&wait, current);
3874
3875 current->state = TASK_INTERRUPTIBLE;
3876
3877 sleep_on_head(q, &wait, &flags);
3878 timeout = schedule_timeout(timeout);
3879 sleep_on_tail(q, &wait, &flags);
3880
3881 return timeout;
3882 }
3883 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3884
3885 void __sched sleep_on(wait_queue_head_t *q)
3886 {
3887 unsigned long flags;
3888 wait_queue_t wait;
3889
3890 init_waitqueue_entry(&wait, current);
3891
3892 current->state = TASK_UNINTERRUPTIBLE;
3893
3894 sleep_on_head(q, &wait, &flags);
3895 schedule();
3896 sleep_on_tail(q, &wait, &flags);
3897 }
3898 EXPORT_SYMBOL(sleep_on);
3899
3900 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3901 {
3902 unsigned long flags;
3903 wait_queue_t wait;
3904
3905 init_waitqueue_entry(&wait, current);
3906
3907 current->state = TASK_UNINTERRUPTIBLE;
3908
3909 sleep_on_head(q, &wait, &flags);
3910 timeout = schedule_timeout(timeout);
3911 sleep_on_tail(q, &wait, &flags);
3912
3913 return timeout;
3914 }
3915 EXPORT_SYMBOL(sleep_on_timeout);
3916
3917 #ifdef CONFIG_RT_MUTEXES
3918
3919 /*
3920 * rt_mutex_setprio - set the current priority of a task
3921 * @p: task
3922 * @prio: prio value (kernel-internal form)
3923 *
3924 * This function changes the 'effective' priority of a task. It does
3925 * not touch ->normal_prio like __setscheduler().
3926 *
3927 * Used by the rt_mutex code to implement priority inheritance logic.
3928 */
3929 void rt_mutex_setprio(struct task_struct *p, int prio)
3930 {
3931 unsigned long flags;
3932 int oldprio, on_rq, running;
3933 struct rq *rq;
3934
3935 BUG_ON(prio < 0 || prio > MAX_PRIO);
3936
3937 rq = task_rq_lock(p, &flags);
3938 update_rq_clock(rq);
3939
3940 oldprio = p->prio;
3941 on_rq = p->se.on_rq;
3942 running = task_running(rq, p);
3943 if (on_rq) {
3944 dequeue_task(rq, p, 0);
3945 if (running)
3946 p->sched_class->put_prev_task(rq, p);
3947 }
3948
3949 if (rt_prio(prio))
3950 p->sched_class = &rt_sched_class;
3951 else
3952 p->sched_class = &fair_sched_class;
3953
3954 p->prio = prio;
3955
3956 if (on_rq) {
3957 if (running)
3958 p->sched_class->set_curr_task(rq);
3959 enqueue_task(rq, p, 0);
3960 /*
3961 * Reschedule if we are currently running on this runqueue and
3962 * our priority decreased, or if we are not currently running on
3963 * this runqueue and our priority is higher than the current's
3964 */
3965 if (running) {
3966 if (p->prio > oldprio)
3967 resched_task(rq->curr);
3968 } else {
3969 check_preempt_curr(rq, p);
3970 }
3971 }
3972 task_rq_unlock(rq, &flags);
3973 }
3974
3975 #endif
3976
3977 void set_user_nice(struct task_struct *p, long nice)
3978 {
3979 int old_prio, delta, on_rq;
3980 unsigned long flags;
3981 struct rq *rq;
3982
3983 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3984 return;
3985 /*
3986 * We have to be careful, if called from sys_setpriority(),
3987 * the task might be in the middle of scheduling on another CPU.
3988 */
3989 rq = task_rq_lock(p, &flags);
3990 update_rq_clock(rq);
3991 /*
3992 * The RT priorities are set via sched_setscheduler(), but we still
3993 * allow the 'normal' nice value to be set - but as expected
3994 * it wont have any effect on scheduling until the task is
3995 * SCHED_FIFO/SCHED_RR:
3996 */
3997 if (task_has_rt_policy(p)) {
3998 p->static_prio = NICE_TO_PRIO(nice);
3999 goto out_unlock;
4000 }
4001 on_rq = p->se.on_rq;
4002 if (on_rq) {
4003 dequeue_task(rq, p, 0);
4004 dec_load(rq, p);
4005 }
4006
4007 p->static_prio = NICE_TO_PRIO(nice);
4008 set_load_weight(p);
4009 old_prio = p->prio;
4010 p->prio = effective_prio(p);
4011 delta = p->prio - old_prio;
4012
4013 if (on_rq) {
4014 enqueue_task(rq, p, 0);
4015 inc_load(rq, p);
4016 /*
4017 * If the task increased its priority or is running and
4018 * lowered its priority, then reschedule its CPU:
4019 */
4020 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4021 resched_task(rq->curr);
4022 }
4023 out_unlock:
4024 task_rq_unlock(rq, &flags);
4025 }
4026 EXPORT_SYMBOL(set_user_nice);
4027
4028 /*
4029 * can_nice - check if a task can reduce its nice value
4030 * @p: task
4031 * @nice: nice value
4032 */
4033 int can_nice(const struct task_struct *p, const int nice)
4034 {
4035 /* convert nice value [19,-20] to rlimit style value [1,40] */
4036 int nice_rlim = 20 - nice;
4037
4038 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4039 capable(CAP_SYS_NICE));
4040 }
4041
4042 #ifdef __ARCH_WANT_SYS_NICE
4043
4044 /*
4045 * sys_nice - change the priority of the current process.
4046 * @increment: priority increment
4047 *
4048 * sys_setpriority is a more generic, but much slower function that
4049 * does similar things.
4050 */
4051 asmlinkage long sys_nice(int increment)
4052 {
4053 long nice, retval;
4054
4055 /*
4056 * Setpriority might change our priority at the same moment.
4057 * We don't have to worry. Conceptually one call occurs first
4058 * and we have a single winner.
4059 */
4060 if (increment < -40)
4061 increment = -40;
4062 if (increment > 40)
4063 increment = 40;
4064
4065 nice = PRIO_TO_NICE(current->static_prio) + increment;
4066 if (nice < -20)
4067 nice = -20;
4068 if (nice > 19)
4069 nice = 19;
4070
4071 if (increment < 0 && !can_nice(current, nice))
4072 return -EPERM;
4073
4074 retval = security_task_setnice(current, nice);
4075 if (retval)
4076 return retval;
4077
4078 set_user_nice(current, nice);
4079 return 0;
4080 }
4081
4082 #endif
4083
4084 /**
4085 * task_prio - return the priority value of a given task.
4086 * @p: the task in question.
4087 *
4088 * This is the priority value as seen by users in /proc.
4089 * RT tasks are offset by -200. Normal tasks are centered
4090 * around 0, value goes from -16 to +15.
4091 */
4092 int task_prio(const struct task_struct *p)
4093 {
4094 return p->prio - MAX_RT_PRIO;
4095 }
4096
4097 /**
4098 * task_nice - return the nice value of a given task.
4099 * @p: the task in question.
4100 */
4101 int task_nice(const struct task_struct *p)
4102 {
4103 return TASK_NICE(p);
4104 }
4105 EXPORT_SYMBOL_GPL(task_nice);
4106
4107 /**
4108 * idle_cpu - is a given cpu idle currently?
4109 * @cpu: the processor in question.
4110 */
4111 int idle_cpu(int cpu)
4112 {
4113 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4114 }
4115
4116 /**
4117 * idle_task - return the idle task for a given cpu.
4118 * @cpu: the processor in question.
4119 */
4120 struct task_struct *idle_task(int cpu)
4121 {
4122 return cpu_rq(cpu)->idle;
4123 }
4124
4125 /**
4126 * find_process_by_pid - find a process with a matching PID value.
4127 * @pid: the pid in question.
4128 */
4129 static inline struct task_struct *find_process_by_pid(pid_t pid)
4130 {
4131 return pid ? find_task_by_pid(pid) : current;
4132 }
4133
4134 /* Actually do priority change: must hold rq lock. */
4135 static void
4136 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4137 {
4138 BUG_ON(p->se.on_rq);
4139
4140 p->policy = policy;
4141 switch (p->policy) {
4142 case SCHED_NORMAL:
4143 case SCHED_BATCH:
4144 case SCHED_IDLE:
4145 p->sched_class = &fair_sched_class;
4146 break;
4147 case SCHED_FIFO:
4148 case SCHED_RR:
4149 p->sched_class = &rt_sched_class;
4150 break;
4151 }
4152
4153 p->rt_priority = prio;
4154 p->normal_prio = normal_prio(p);
4155 /* we are holding p->pi_lock already */
4156 p->prio = rt_mutex_getprio(p);
4157 set_load_weight(p);
4158 }
4159
4160 /**
4161 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4162 * @p: the task in question.
4163 * @policy: new policy.
4164 * @param: structure containing the new RT priority.
4165 *
4166 * NOTE that the task may be already dead.
4167 */
4168 int sched_setscheduler(struct task_struct *p, int policy,
4169 struct sched_param *param)
4170 {
4171 int retval, oldprio, oldpolicy = -1, on_rq, running;
4172 unsigned long flags;
4173 struct rq *rq;
4174
4175 /* may grab non-irq protected spin_locks */
4176 BUG_ON(in_interrupt());
4177 recheck:
4178 /* double check policy once rq lock held */
4179 if (policy < 0)
4180 policy = oldpolicy = p->policy;
4181 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4182 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4183 policy != SCHED_IDLE)
4184 return -EINVAL;
4185 /*
4186 * Valid priorities for SCHED_FIFO and SCHED_RR are
4187 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4188 * SCHED_BATCH and SCHED_IDLE is 0.
4189 */
4190 if (param->sched_priority < 0 ||
4191 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4192 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4193 return -EINVAL;
4194 if (rt_policy(policy) != (param->sched_priority != 0))
4195 return -EINVAL;
4196
4197 /*
4198 * Allow unprivileged RT tasks to decrease priority:
4199 */
4200 if (!capable(CAP_SYS_NICE)) {
4201 if (rt_policy(policy)) {
4202 unsigned long rlim_rtprio;
4203
4204 if (!lock_task_sighand(p, &flags))
4205 return -ESRCH;
4206 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4207 unlock_task_sighand(p, &flags);
4208
4209 /* can't set/change the rt policy */
4210 if (policy != p->policy && !rlim_rtprio)
4211 return -EPERM;
4212
4213 /* can't increase priority */
4214 if (param->sched_priority > p->rt_priority &&
4215 param->sched_priority > rlim_rtprio)
4216 return -EPERM;
4217 }
4218 /*
4219 * Like positive nice levels, dont allow tasks to
4220 * move out of SCHED_IDLE either:
4221 */
4222 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4223 return -EPERM;
4224
4225 /* can't change other user's priorities */
4226 if ((current->euid != p->euid) &&
4227 (current->euid != p->uid))
4228 return -EPERM;
4229 }
4230
4231 retval = security_task_setscheduler(p, policy, param);
4232 if (retval)
4233 return retval;
4234 /*
4235 * make sure no PI-waiters arrive (or leave) while we are
4236 * changing the priority of the task:
4237 */
4238 spin_lock_irqsave(&p->pi_lock, flags);
4239 /*
4240 * To be able to change p->policy safely, the apropriate
4241 * runqueue lock must be held.
4242 */
4243 rq = __task_rq_lock(p);
4244 /* recheck policy now with rq lock held */
4245 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4246 policy = oldpolicy = -1;
4247 __task_rq_unlock(rq);
4248 spin_unlock_irqrestore(&p->pi_lock, flags);
4249 goto recheck;
4250 }
4251 update_rq_clock(rq);
4252 on_rq = p->se.on_rq;
4253 running = task_running(rq, p);
4254 if (on_rq) {
4255 deactivate_task(rq, p, 0);
4256 if (running)
4257 p->sched_class->put_prev_task(rq, p);
4258 }
4259
4260 oldprio = p->prio;
4261 __setscheduler(rq, p, policy, param->sched_priority);
4262
4263 if (on_rq) {
4264 if (running)
4265 p->sched_class->set_curr_task(rq);
4266 activate_task(rq, p, 0);
4267 /*
4268 * Reschedule if we are currently running on this runqueue and
4269 * our priority decreased, or if we are not currently running on
4270 * this runqueue and our priority is higher than the current's
4271 */
4272 if (running) {
4273 if (p->prio > oldprio)
4274 resched_task(rq->curr);
4275 } else {
4276 check_preempt_curr(rq, p);
4277 }
4278 }
4279 __task_rq_unlock(rq);
4280 spin_unlock_irqrestore(&p->pi_lock, flags);
4281
4282 rt_mutex_adjust_pi(p);
4283
4284 return 0;
4285 }
4286 EXPORT_SYMBOL_GPL(sched_setscheduler);
4287
4288 static int
4289 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4290 {
4291 struct sched_param lparam;
4292 struct task_struct *p;
4293 int retval;
4294
4295 if (!param || pid < 0)
4296 return -EINVAL;
4297 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4298 return -EFAULT;
4299
4300 rcu_read_lock();
4301 retval = -ESRCH;
4302 p = find_process_by_pid(pid);
4303 if (p != NULL)
4304 retval = sched_setscheduler(p, policy, &lparam);
4305 rcu_read_unlock();
4306
4307 return retval;
4308 }
4309
4310 /**
4311 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4312 * @pid: the pid in question.
4313 * @policy: new policy.
4314 * @param: structure containing the new RT priority.
4315 */
4316 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4317 struct sched_param __user *param)
4318 {
4319 /* negative values for policy are not valid */
4320 if (policy < 0)
4321 return -EINVAL;
4322
4323 return do_sched_setscheduler(pid, policy, param);
4324 }
4325
4326 /**
4327 * sys_sched_setparam - set/change the RT priority of a thread
4328 * @pid: the pid in question.
4329 * @param: structure containing the new RT priority.
4330 */
4331 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4332 {
4333 return do_sched_setscheduler(pid, -1, param);
4334 }
4335
4336 /**
4337 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4338 * @pid: the pid in question.
4339 */
4340 asmlinkage long sys_sched_getscheduler(pid_t pid)
4341 {
4342 struct task_struct *p;
4343 int retval = -EINVAL;
4344
4345 if (pid < 0)
4346 goto out_nounlock;
4347
4348 retval = -ESRCH;
4349 read_lock(&tasklist_lock);
4350 p = find_process_by_pid(pid);
4351 if (p) {
4352 retval = security_task_getscheduler(p);
4353 if (!retval)
4354 retval = p->policy;
4355 }
4356 read_unlock(&tasklist_lock);
4357
4358 out_nounlock:
4359 return retval;
4360 }
4361
4362 /**
4363 * sys_sched_getscheduler - get the RT priority of a thread
4364 * @pid: the pid in question.
4365 * @param: structure containing the RT priority.
4366 */
4367 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4368 {
4369 struct sched_param lp;
4370 struct task_struct *p;
4371 int retval = -EINVAL;
4372
4373 if (!param || pid < 0)
4374 goto out_nounlock;
4375
4376 read_lock(&tasklist_lock);
4377 p = find_process_by_pid(pid);
4378 retval = -ESRCH;
4379 if (!p)
4380 goto out_unlock;
4381
4382 retval = security_task_getscheduler(p);
4383 if (retval)
4384 goto out_unlock;
4385
4386 lp.sched_priority = p->rt_priority;
4387 read_unlock(&tasklist_lock);
4388
4389 /*
4390 * This one might sleep, we cannot do it with a spinlock held ...
4391 */
4392 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4393
4394 out_nounlock:
4395 return retval;
4396
4397 out_unlock:
4398 read_unlock(&tasklist_lock);
4399 return retval;
4400 }
4401
4402 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4403 {
4404 cpumask_t cpus_allowed;
4405 struct task_struct *p;
4406 int retval;
4407
4408 mutex_lock(&sched_hotcpu_mutex);
4409 read_lock(&tasklist_lock);
4410
4411 p = find_process_by_pid(pid);
4412 if (!p) {
4413 read_unlock(&tasklist_lock);
4414 mutex_unlock(&sched_hotcpu_mutex);
4415 return -ESRCH;
4416 }
4417
4418 /*
4419 * It is not safe to call set_cpus_allowed with the
4420 * tasklist_lock held. We will bump the task_struct's
4421 * usage count and then drop tasklist_lock.
4422 */
4423 get_task_struct(p);
4424 read_unlock(&tasklist_lock);
4425
4426 retval = -EPERM;
4427 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4428 !capable(CAP_SYS_NICE))
4429 goto out_unlock;
4430
4431 retval = security_task_setscheduler(p, 0, NULL);
4432 if (retval)
4433 goto out_unlock;
4434
4435 cpus_allowed = cpuset_cpus_allowed(p);
4436 cpus_and(new_mask, new_mask, cpus_allowed);
4437 retval = set_cpus_allowed(p, new_mask);
4438
4439 out_unlock:
4440 put_task_struct(p);
4441 mutex_unlock(&sched_hotcpu_mutex);
4442 return retval;
4443 }
4444
4445 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4446 cpumask_t *new_mask)
4447 {
4448 if (len < sizeof(cpumask_t)) {
4449 memset(new_mask, 0, sizeof(cpumask_t));
4450 } else if (len > sizeof(cpumask_t)) {
4451 len = sizeof(cpumask_t);
4452 }
4453 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4454 }
4455
4456 /**
4457 * sys_sched_setaffinity - set the cpu affinity of a process
4458 * @pid: pid of the process
4459 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4460 * @user_mask_ptr: user-space pointer to the new cpu mask
4461 */
4462 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4463 unsigned long __user *user_mask_ptr)
4464 {
4465 cpumask_t new_mask;
4466 int retval;
4467
4468 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4469 if (retval)
4470 return retval;
4471
4472 return sched_setaffinity(pid, new_mask);
4473 }
4474
4475 /*
4476 * Represents all cpu's present in the system
4477 * In systems capable of hotplug, this map could dynamically grow
4478 * as new cpu's are detected in the system via any platform specific
4479 * method, such as ACPI for e.g.
4480 */
4481
4482 cpumask_t cpu_present_map __read_mostly;
4483 EXPORT_SYMBOL(cpu_present_map);
4484
4485 #ifndef CONFIG_SMP
4486 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4487 EXPORT_SYMBOL(cpu_online_map);
4488
4489 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4490 EXPORT_SYMBOL(cpu_possible_map);
4491 #endif
4492
4493 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4494 {
4495 struct task_struct *p;
4496 int retval;
4497
4498 mutex_lock(&sched_hotcpu_mutex);
4499 read_lock(&tasklist_lock);
4500
4501 retval = -ESRCH;
4502 p = find_process_by_pid(pid);
4503 if (!p)
4504 goto out_unlock;
4505
4506 retval = security_task_getscheduler(p);
4507 if (retval)
4508 goto out_unlock;
4509
4510 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4511
4512 out_unlock:
4513 read_unlock(&tasklist_lock);
4514 mutex_unlock(&sched_hotcpu_mutex);
4515
4516 return retval;
4517 }
4518
4519 /**
4520 * sys_sched_getaffinity - get the cpu affinity of a process
4521 * @pid: pid of the process
4522 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4523 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4524 */
4525 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4526 unsigned long __user *user_mask_ptr)
4527 {
4528 int ret;
4529 cpumask_t mask;
4530
4531 if (len < sizeof(cpumask_t))
4532 return -EINVAL;
4533
4534 ret = sched_getaffinity(pid, &mask);
4535 if (ret < 0)
4536 return ret;
4537
4538 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4539 return -EFAULT;
4540
4541 return sizeof(cpumask_t);
4542 }
4543
4544 /**
4545 * sys_sched_yield - yield the current processor to other threads.
4546 *
4547 * This function yields the current CPU to other tasks. If there are no
4548 * other threads running on this CPU then this function will return.
4549 */
4550 asmlinkage long sys_sched_yield(void)
4551 {
4552 struct rq *rq = this_rq_lock();
4553
4554 schedstat_inc(rq, yld_cnt);
4555 current->sched_class->yield_task(rq);
4556
4557 /*
4558 * Since we are going to call schedule() anyway, there's
4559 * no need to preempt or enable interrupts:
4560 */
4561 __release(rq->lock);
4562 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4563 _raw_spin_unlock(&rq->lock);
4564 preempt_enable_no_resched();
4565
4566 schedule();
4567
4568 return 0;
4569 }
4570
4571 static void __cond_resched(void)
4572 {
4573 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4574 __might_sleep(__FILE__, __LINE__);
4575 #endif
4576 /*
4577 * The BKS might be reacquired before we have dropped
4578 * PREEMPT_ACTIVE, which could trigger a second
4579 * cond_resched() call.
4580 */
4581 do {
4582 add_preempt_count(PREEMPT_ACTIVE);
4583 schedule();
4584 sub_preempt_count(PREEMPT_ACTIVE);
4585 } while (need_resched());
4586 }
4587
4588 int __sched cond_resched(void)
4589 {
4590 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4591 system_state == SYSTEM_RUNNING) {
4592 __cond_resched();
4593 return 1;
4594 }
4595 return 0;
4596 }
4597 EXPORT_SYMBOL(cond_resched);
4598
4599 /*
4600 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4601 * call schedule, and on return reacquire the lock.
4602 *
4603 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4604 * operations here to prevent schedule() from being called twice (once via
4605 * spin_unlock(), once by hand).
4606 */
4607 int cond_resched_lock(spinlock_t *lock)
4608 {
4609 int ret = 0;
4610
4611 if (need_lockbreak(lock)) {
4612 spin_unlock(lock);
4613 cpu_relax();
4614 ret = 1;
4615 spin_lock(lock);
4616 }
4617 if (need_resched() && system_state == SYSTEM_RUNNING) {
4618 spin_release(&lock->dep_map, 1, _THIS_IP_);
4619 _raw_spin_unlock(lock);
4620 preempt_enable_no_resched();
4621 __cond_resched();
4622 ret = 1;
4623 spin_lock(lock);
4624 }
4625 return ret;
4626 }
4627 EXPORT_SYMBOL(cond_resched_lock);
4628
4629 int __sched cond_resched_softirq(void)
4630 {
4631 BUG_ON(!in_softirq());
4632
4633 if (need_resched() && system_state == SYSTEM_RUNNING) {
4634 local_bh_enable();
4635 __cond_resched();
4636 local_bh_disable();
4637 return 1;
4638 }
4639 return 0;
4640 }
4641 EXPORT_SYMBOL(cond_resched_softirq);
4642
4643 /**
4644 * yield - yield the current processor to other threads.
4645 *
4646 * This is a shortcut for kernel-space yielding - it marks the
4647 * thread runnable and calls sys_sched_yield().
4648 */
4649 void __sched yield(void)
4650 {
4651 set_current_state(TASK_RUNNING);
4652 sys_sched_yield();
4653 }
4654 EXPORT_SYMBOL(yield);
4655
4656 /*
4657 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4658 * that process accounting knows that this is a task in IO wait state.
4659 *
4660 * But don't do that if it is a deliberate, throttling IO wait (this task
4661 * has set its backing_dev_info: the queue against which it should throttle)
4662 */
4663 void __sched io_schedule(void)
4664 {
4665 struct rq *rq = &__raw_get_cpu_var(runqueues);
4666
4667 delayacct_blkio_start();
4668 atomic_inc(&rq->nr_iowait);
4669 schedule();
4670 atomic_dec(&rq->nr_iowait);
4671 delayacct_blkio_end();
4672 }
4673 EXPORT_SYMBOL(io_schedule);
4674
4675 long __sched io_schedule_timeout(long timeout)
4676 {
4677 struct rq *rq = &__raw_get_cpu_var(runqueues);
4678 long ret;
4679
4680 delayacct_blkio_start();
4681 atomic_inc(&rq->nr_iowait);
4682 ret = schedule_timeout(timeout);
4683 atomic_dec(&rq->nr_iowait);
4684 delayacct_blkio_end();
4685 return ret;
4686 }
4687
4688 /**
4689 * sys_sched_get_priority_max - return maximum RT priority.
4690 * @policy: scheduling class.
4691 *
4692 * this syscall returns the maximum rt_priority that can be used
4693 * by a given scheduling class.
4694 */
4695 asmlinkage long sys_sched_get_priority_max(int policy)
4696 {
4697 int ret = -EINVAL;
4698
4699 switch (policy) {
4700 case SCHED_FIFO:
4701 case SCHED_RR:
4702 ret = MAX_USER_RT_PRIO-1;
4703 break;
4704 case SCHED_NORMAL:
4705 case SCHED_BATCH:
4706 case SCHED_IDLE:
4707 ret = 0;
4708 break;
4709 }
4710 return ret;
4711 }
4712
4713 /**
4714 * sys_sched_get_priority_min - return minimum RT priority.
4715 * @policy: scheduling class.
4716 *
4717 * this syscall returns the minimum rt_priority that can be used
4718 * by a given scheduling class.
4719 */
4720 asmlinkage long sys_sched_get_priority_min(int policy)
4721 {
4722 int ret = -EINVAL;
4723
4724 switch (policy) {
4725 case SCHED_FIFO:
4726 case SCHED_RR:
4727 ret = 1;
4728 break;
4729 case SCHED_NORMAL:
4730 case SCHED_BATCH:
4731 case SCHED_IDLE:
4732 ret = 0;
4733 }
4734 return ret;
4735 }
4736
4737 /**
4738 * sys_sched_rr_get_interval - return the default timeslice of a process.
4739 * @pid: pid of the process.
4740 * @interval: userspace pointer to the timeslice value.
4741 *
4742 * this syscall writes the default timeslice value of a given process
4743 * into the user-space timespec buffer. A value of '0' means infinity.
4744 */
4745 asmlinkage
4746 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4747 {
4748 struct task_struct *p;
4749 int retval = -EINVAL;
4750 struct timespec t;
4751
4752 if (pid < 0)
4753 goto out_nounlock;
4754
4755 retval = -ESRCH;
4756 read_lock(&tasklist_lock);
4757 p = find_process_by_pid(pid);
4758 if (!p)
4759 goto out_unlock;
4760
4761 retval = security_task_getscheduler(p);
4762 if (retval)
4763 goto out_unlock;
4764
4765 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4766 0 : static_prio_timeslice(p->static_prio), &t);
4767 read_unlock(&tasklist_lock);
4768 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4769 out_nounlock:
4770 return retval;
4771 out_unlock:
4772 read_unlock(&tasklist_lock);
4773 return retval;
4774 }
4775
4776 static const char stat_nam[] = "RSDTtZX";
4777
4778 static void show_task(struct task_struct *p)
4779 {
4780 unsigned long free = 0;
4781 unsigned state;
4782
4783 state = p->state ? __ffs(p->state) + 1 : 0;
4784 printk("%-13.13s %c", p->comm,
4785 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4786 #if BITS_PER_LONG == 32
4787 if (state == TASK_RUNNING)
4788 printk(" running ");
4789 else
4790 printk(" %08lx ", thread_saved_pc(p));
4791 #else
4792 if (state == TASK_RUNNING)
4793 printk(" running task ");
4794 else
4795 printk(" %016lx ", thread_saved_pc(p));
4796 #endif
4797 #ifdef CONFIG_DEBUG_STACK_USAGE
4798 {
4799 unsigned long *n = end_of_stack(p);
4800 while (!*n)
4801 n++;
4802 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4803 }
4804 #endif
4805 printk("%5lu %5d %6d\n", free, p->pid, p->parent->pid);
4806
4807 if (state != TASK_RUNNING)
4808 show_stack(p, NULL);
4809 }
4810
4811 void show_state_filter(unsigned long state_filter)
4812 {
4813 struct task_struct *g, *p;
4814
4815 #if BITS_PER_LONG == 32
4816 printk(KERN_INFO
4817 " task PC stack pid father\n");
4818 #else
4819 printk(KERN_INFO
4820 " task PC stack pid father\n");
4821 #endif
4822 read_lock(&tasklist_lock);
4823 do_each_thread(g, p) {
4824 /*
4825 * reset the NMI-timeout, listing all files on a slow
4826 * console might take alot of time:
4827 */
4828 touch_nmi_watchdog();
4829 if (!state_filter || (p->state & state_filter))
4830 show_task(p);
4831 } while_each_thread(g, p);
4832
4833 touch_all_softlockup_watchdogs();
4834
4835 #ifdef CONFIG_SCHED_DEBUG
4836 sysrq_sched_debug_show();
4837 #endif
4838 read_unlock(&tasklist_lock);
4839 /*
4840 * Only show locks if all tasks are dumped:
4841 */
4842 if (state_filter == -1)
4843 debug_show_all_locks();
4844 }
4845
4846 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4847 {
4848 idle->sched_class = &idle_sched_class;
4849 }
4850
4851 /**
4852 * init_idle - set up an idle thread for a given CPU
4853 * @idle: task in question
4854 * @cpu: cpu the idle task belongs to
4855 *
4856 * NOTE: this function does not set the idle thread's NEED_RESCHED
4857 * flag, to make booting more robust.
4858 */
4859 void __cpuinit init_idle(struct task_struct *idle, int cpu)
4860 {
4861 struct rq *rq = cpu_rq(cpu);
4862 unsigned long flags;
4863
4864 __sched_fork(idle);
4865 idle->se.exec_start = sched_clock();
4866
4867 idle->prio = idle->normal_prio = MAX_PRIO;
4868 idle->cpus_allowed = cpumask_of_cpu(cpu);
4869 __set_task_cpu(idle, cpu);
4870
4871 spin_lock_irqsave(&rq->lock, flags);
4872 rq->curr = rq->idle = idle;
4873 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4874 idle->oncpu = 1;
4875 #endif
4876 spin_unlock_irqrestore(&rq->lock, flags);
4877
4878 /* Set the preempt count _outside_ the spinlocks! */
4879 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4880 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4881 #else
4882 task_thread_info(idle)->preempt_count = 0;
4883 #endif
4884 /*
4885 * The idle tasks have their own, simple scheduling class:
4886 */
4887 idle->sched_class = &idle_sched_class;
4888 }
4889
4890 /*
4891 * In a system that switches off the HZ timer nohz_cpu_mask
4892 * indicates which cpus entered this state. This is used
4893 * in the rcu update to wait only for active cpus. For system
4894 * which do not switch off the HZ timer nohz_cpu_mask should
4895 * always be CPU_MASK_NONE.
4896 */
4897 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4898
4899 #ifdef CONFIG_SMP
4900 /*
4901 * This is how migration works:
4902 *
4903 * 1) we queue a struct migration_req structure in the source CPU's
4904 * runqueue and wake up that CPU's migration thread.
4905 * 2) we down() the locked semaphore => thread blocks.
4906 * 3) migration thread wakes up (implicitly it forces the migrated
4907 * thread off the CPU)
4908 * 4) it gets the migration request and checks whether the migrated
4909 * task is still in the wrong runqueue.
4910 * 5) if it's in the wrong runqueue then the migration thread removes
4911 * it and puts it into the right queue.
4912 * 6) migration thread up()s the semaphore.
4913 * 7) we wake up and the migration is done.
4914 */
4915
4916 /*
4917 * Change a given task's CPU affinity. Migrate the thread to a
4918 * proper CPU and schedule it away if the CPU it's executing on
4919 * is removed from the allowed bitmask.
4920 *
4921 * NOTE: the caller must have a valid reference to the task, the
4922 * task must not exit() & deallocate itself prematurely. The
4923 * call is not atomic; no spinlocks may be held.
4924 */
4925 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
4926 {
4927 struct migration_req req;
4928 unsigned long flags;
4929 struct rq *rq;
4930 int ret = 0;
4931
4932 rq = task_rq_lock(p, &flags);
4933 if (!cpus_intersects(new_mask, cpu_online_map)) {
4934 ret = -EINVAL;
4935 goto out;
4936 }
4937
4938 p->cpus_allowed = new_mask;
4939 /* Can the task run on the task's current CPU? If so, we're done */
4940 if (cpu_isset(task_cpu(p), new_mask))
4941 goto out;
4942
4943 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4944 /* Need help from migration thread: drop lock and wait. */
4945 task_rq_unlock(rq, &flags);
4946 wake_up_process(rq->migration_thread);
4947 wait_for_completion(&req.done);
4948 tlb_migrate_finish(p->mm);
4949 return 0;
4950 }
4951 out:
4952 task_rq_unlock(rq, &flags);
4953
4954 return ret;
4955 }
4956 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4957
4958 /*
4959 * Move (not current) task off this cpu, onto dest cpu. We're doing
4960 * this because either it can't run here any more (set_cpus_allowed()
4961 * away from this CPU, or CPU going down), or because we're
4962 * attempting to rebalance this task on exec (sched_exec).
4963 *
4964 * So we race with normal scheduler movements, but that's OK, as long
4965 * as the task is no longer on this CPU.
4966 *
4967 * Returns non-zero if task was successfully migrated.
4968 */
4969 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4970 {
4971 struct rq *rq_dest, *rq_src;
4972 int ret = 0, on_rq;
4973
4974 if (unlikely(cpu_is_offline(dest_cpu)))
4975 return ret;
4976
4977 rq_src = cpu_rq(src_cpu);
4978 rq_dest = cpu_rq(dest_cpu);
4979
4980 double_rq_lock(rq_src, rq_dest);
4981 /* Already moved. */
4982 if (task_cpu(p) != src_cpu)
4983 goto out;
4984 /* Affinity changed (again). */
4985 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4986 goto out;
4987
4988 on_rq = p->se.on_rq;
4989 if (on_rq)
4990 deactivate_task(rq_src, p, 0);
4991
4992 set_task_cpu(p, dest_cpu);
4993 if (on_rq) {
4994 activate_task(rq_dest, p, 0);
4995 check_preempt_curr(rq_dest, p);
4996 }
4997 ret = 1;
4998 out:
4999 double_rq_unlock(rq_src, rq_dest);
5000 return ret;
5001 }
5002
5003 /*
5004 * migration_thread - this is a highprio system thread that performs
5005 * thread migration by bumping thread off CPU then 'pushing' onto
5006 * another runqueue.
5007 */
5008 static int migration_thread(void *data)
5009 {
5010 int cpu = (long)data;
5011 struct rq *rq;
5012
5013 rq = cpu_rq(cpu);
5014 BUG_ON(rq->migration_thread != current);
5015
5016 set_current_state(TASK_INTERRUPTIBLE);
5017 while (!kthread_should_stop()) {
5018 struct migration_req *req;
5019 struct list_head *head;
5020
5021 spin_lock_irq(&rq->lock);
5022
5023 if (cpu_is_offline(cpu)) {
5024 spin_unlock_irq(&rq->lock);
5025 goto wait_to_die;
5026 }
5027
5028 if (rq->active_balance) {
5029 active_load_balance(rq, cpu);
5030 rq->active_balance = 0;
5031 }
5032
5033 head = &rq->migration_queue;
5034
5035 if (list_empty(head)) {
5036 spin_unlock_irq(&rq->lock);
5037 schedule();
5038 set_current_state(TASK_INTERRUPTIBLE);
5039 continue;
5040 }
5041 req = list_entry(head->next, struct migration_req, list);
5042 list_del_init(head->next);
5043
5044 spin_unlock(&rq->lock);
5045 __migrate_task(req->task, cpu, req->dest_cpu);
5046 local_irq_enable();
5047
5048 complete(&req->done);
5049 }
5050 __set_current_state(TASK_RUNNING);
5051 return 0;
5052
5053 wait_to_die:
5054 /* Wait for kthread_stop */
5055 set_current_state(TASK_INTERRUPTIBLE);
5056 while (!kthread_should_stop()) {
5057 schedule();
5058 set_current_state(TASK_INTERRUPTIBLE);
5059 }
5060 __set_current_state(TASK_RUNNING);
5061 return 0;
5062 }
5063
5064 #ifdef CONFIG_HOTPLUG_CPU
5065 /*
5066 * Figure out where task on dead CPU should go, use force if neccessary.
5067 * NOTE: interrupts should be disabled by the caller
5068 */
5069 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5070 {
5071 unsigned long flags;
5072 cpumask_t mask;
5073 struct rq *rq;
5074 int dest_cpu;
5075
5076 restart:
5077 /* On same node? */
5078 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5079 cpus_and(mask, mask, p->cpus_allowed);
5080 dest_cpu = any_online_cpu(mask);
5081
5082 /* On any allowed CPU? */
5083 if (dest_cpu == NR_CPUS)
5084 dest_cpu = any_online_cpu(p->cpus_allowed);
5085
5086 /* No more Mr. Nice Guy. */
5087 if (dest_cpu == NR_CPUS) {
5088 rq = task_rq_lock(p, &flags);
5089 cpus_setall(p->cpus_allowed);
5090 dest_cpu = any_online_cpu(p->cpus_allowed);
5091 task_rq_unlock(rq, &flags);
5092
5093 /*
5094 * Don't tell them about moving exiting tasks or
5095 * kernel threads (both mm NULL), since they never
5096 * leave kernel.
5097 */
5098 if (p->mm && printk_ratelimit())
5099 printk(KERN_INFO "process %d (%s) no "
5100 "longer affine to cpu%d\n",
5101 p->pid, p->comm, dead_cpu);
5102 }
5103 if (!__migrate_task(p, dead_cpu, dest_cpu))
5104 goto restart;
5105 }
5106
5107 /*
5108 * While a dead CPU has no uninterruptible tasks queued at this point,
5109 * it might still have a nonzero ->nr_uninterruptible counter, because
5110 * for performance reasons the counter is not stricly tracking tasks to
5111 * their home CPUs. So we just add the counter to another CPU's counter,
5112 * to keep the global sum constant after CPU-down:
5113 */
5114 static void migrate_nr_uninterruptible(struct rq *rq_src)
5115 {
5116 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5117 unsigned long flags;
5118
5119 local_irq_save(flags);
5120 double_rq_lock(rq_src, rq_dest);
5121 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5122 rq_src->nr_uninterruptible = 0;
5123 double_rq_unlock(rq_src, rq_dest);
5124 local_irq_restore(flags);
5125 }
5126
5127 /* Run through task list and migrate tasks from the dead cpu. */
5128 static void migrate_live_tasks(int src_cpu)
5129 {
5130 struct task_struct *p, *t;
5131
5132 write_lock_irq(&tasklist_lock);
5133
5134 do_each_thread(t, p) {
5135 if (p == current)
5136 continue;
5137
5138 if (task_cpu(p) == src_cpu)
5139 move_task_off_dead_cpu(src_cpu, p);
5140 } while_each_thread(t, p);
5141
5142 write_unlock_irq(&tasklist_lock);
5143 }
5144
5145 /*
5146 * Schedules idle task to be the next runnable task on current CPU.
5147 * It does so by boosting its priority to highest possible and adding it to
5148 * the _front_ of the runqueue. Used by CPU offline code.
5149 */
5150 void sched_idle_next(void)
5151 {
5152 int this_cpu = smp_processor_id();
5153 struct rq *rq = cpu_rq(this_cpu);
5154 struct task_struct *p = rq->idle;
5155 unsigned long flags;
5156
5157 /* cpu has to be offline */
5158 BUG_ON(cpu_online(this_cpu));
5159
5160 /*
5161 * Strictly not necessary since rest of the CPUs are stopped by now
5162 * and interrupts disabled on the current cpu.
5163 */
5164 spin_lock_irqsave(&rq->lock, flags);
5165
5166 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5167
5168 /* Add idle task to the _front_ of its priority queue: */
5169 activate_idle_task(p, rq);
5170
5171 spin_unlock_irqrestore(&rq->lock, flags);
5172 }
5173
5174 /*
5175 * Ensures that the idle task is using init_mm right before its cpu goes
5176 * offline.
5177 */
5178 void idle_task_exit(void)
5179 {
5180 struct mm_struct *mm = current->active_mm;
5181
5182 BUG_ON(cpu_online(smp_processor_id()));
5183
5184 if (mm != &init_mm)
5185 switch_mm(mm, &init_mm, current);
5186 mmdrop(mm);
5187 }
5188
5189 /* called under rq->lock with disabled interrupts */
5190 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5191 {
5192 struct rq *rq = cpu_rq(dead_cpu);
5193
5194 /* Must be exiting, otherwise would be on tasklist. */
5195 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5196
5197 /* Cannot have done final schedule yet: would have vanished. */
5198 BUG_ON(p->state == TASK_DEAD);
5199
5200 get_task_struct(p);
5201
5202 /*
5203 * Drop lock around migration; if someone else moves it,
5204 * that's OK. No task can be added to this CPU, so iteration is
5205 * fine.
5206 * NOTE: interrupts should be left disabled --dev@
5207 */
5208 spin_unlock(&rq->lock);
5209 move_task_off_dead_cpu(dead_cpu, p);
5210 spin_lock(&rq->lock);
5211
5212 put_task_struct(p);
5213 }
5214
5215 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5216 static void migrate_dead_tasks(unsigned int dead_cpu)
5217 {
5218 struct rq *rq = cpu_rq(dead_cpu);
5219 struct task_struct *next;
5220
5221 for ( ; ; ) {
5222 if (!rq->nr_running)
5223 break;
5224 update_rq_clock(rq);
5225 next = pick_next_task(rq, rq->curr);
5226 if (!next)
5227 break;
5228 migrate_dead(dead_cpu, next);
5229
5230 }
5231 }
5232 #endif /* CONFIG_HOTPLUG_CPU */
5233
5234 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5235
5236 static struct ctl_table sd_ctl_dir[] = {
5237 {
5238 .procname = "sched_domain",
5239 .mode = 0555,
5240 },
5241 {0,},
5242 };
5243
5244 static struct ctl_table sd_ctl_root[] = {
5245 {
5246 .ctl_name = CTL_KERN,
5247 .procname = "kernel",
5248 .mode = 0555,
5249 .child = sd_ctl_dir,
5250 },
5251 {0,},
5252 };
5253
5254 static struct ctl_table *sd_alloc_ctl_entry(int n)
5255 {
5256 struct ctl_table *entry =
5257 kmalloc(n * sizeof(struct ctl_table), GFP_KERNEL);
5258
5259 BUG_ON(!entry);
5260 memset(entry, 0, n * sizeof(struct ctl_table));
5261
5262 return entry;
5263 }
5264
5265 static void
5266 set_table_entry(struct ctl_table *entry,
5267 const char *procname, void *data, int maxlen,
5268 mode_t mode, proc_handler *proc_handler)
5269 {
5270 entry->procname = procname;
5271 entry->data = data;
5272 entry->maxlen = maxlen;
5273 entry->mode = mode;
5274 entry->proc_handler = proc_handler;
5275 }
5276
5277 static struct ctl_table *
5278 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5279 {
5280 struct ctl_table *table = sd_alloc_ctl_entry(14);
5281
5282 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5283 sizeof(long), 0644, proc_doulongvec_minmax);
5284 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5285 sizeof(long), 0644, proc_doulongvec_minmax);
5286 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5287 sizeof(int), 0644, proc_dointvec_minmax);
5288 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5289 sizeof(int), 0644, proc_dointvec_minmax);
5290 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5291 sizeof(int), 0644, proc_dointvec_minmax);
5292 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5293 sizeof(int), 0644, proc_dointvec_minmax);
5294 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5295 sizeof(int), 0644, proc_dointvec_minmax);
5296 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5297 sizeof(int), 0644, proc_dointvec_minmax);
5298 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5299 sizeof(int), 0644, proc_dointvec_minmax);
5300 set_table_entry(&table[10], "cache_nice_tries",
5301 &sd->cache_nice_tries,
5302 sizeof(int), 0644, proc_dointvec_minmax);
5303 set_table_entry(&table[12], "flags", &sd->flags,
5304 sizeof(int), 0644, proc_dointvec_minmax);
5305
5306 return table;
5307 }
5308
5309 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5310 {
5311 struct ctl_table *entry, *table;
5312 struct sched_domain *sd;
5313 int domain_num = 0, i;
5314 char buf[32];
5315
5316 for_each_domain(cpu, sd)
5317 domain_num++;
5318 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5319
5320 i = 0;
5321 for_each_domain(cpu, sd) {
5322 snprintf(buf, 32, "domain%d", i);
5323 entry->procname = kstrdup(buf, GFP_KERNEL);
5324 entry->mode = 0555;
5325 entry->child = sd_alloc_ctl_domain_table(sd);
5326 entry++;
5327 i++;
5328 }
5329 return table;
5330 }
5331
5332 static struct ctl_table_header *sd_sysctl_header;
5333 static void init_sched_domain_sysctl(void)
5334 {
5335 int i, cpu_num = num_online_cpus();
5336 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5337 char buf[32];
5338
5339 sd_ctl_dir[0].child = entry;
5340
5341 for (i = 0; i < cpu_num; i++, entry++) {
5342 snprintf(buf, 32, "cpu%d", i);
5343 entry->procname = kstrdup(buf, GFP_KERNEL);
5344 entry->mode = 0555;
5345 entry->child = sd_alloc_ctl_cpu_table(i);
5346 }
5347 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5348 }
5349 #else
5350 static void init_sched_domain_sysctl(void)
5351 {
5352 }
5353 #endif
5354
5355 /*
5356 * migration_call - callback that gets triggered when a CPU is added.
5357 * Here we can start up the necessary migration thread for the new CPU.
5358 */
5359 static int __cpuinit
5360 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5361 {
5362 struct task_struct *p;
5363 int cpu = (long)hcpu;
5364 unsigned long flags;
5365 struct rq *rq;
5366
5367 switch (action) {
5368 case CPU_LOCK_ACQUIRE:
5369 mutex_lock(&sched_hotcpu_mutex);
5370 break;
5371
5372 case CPU_UP_PREPARE:
5373 case CPU_UP_PREPARE_FROZEN:
5374 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5375 if (IS_ERR(p))
5376 return NOTIFY_BAD;
5377 kthread_bind(p, cpu);
5378 /* Must be high prio: stop_machine expects to yield to it. */
5379 rq = task_rq_lock(p, &flags);
5380 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5381 task_rq_unlock(rq, &flags);
5382 cpu_rq(cpu)->migration_thread = p;
5383 break;
5384
5385 case CPU_ONLINE:
5386 case CPU_ONLINE_FROZEN:
5387 /* Strictly unneccessary, as first user will wake it. */
5388 wake_up_process(cpu_rq(cpu)->migration_thread);
5389 break;
5390
5391 #ifdef CONFIG_HOTPLUG_CPU
5392 case CPU_UP_CANCELED:
5393 case CPU_UP_CANCELED_FROZEN:
5394 if (!cpu_rq(cpu)->migration_thread)
5395 break;
5396 /* Unbind it from offline cpu so it can run. Fall thru. */
5397 kthread_bind(cpu_rq(cpu)->migration_thread,
5398 any_online_cpu(cpu_online_map));
5399 kthread_stop(cpu_rq(cpu)->migration_thread);
5400 cpu_rq(cpu)->migration_thread = NULL;
5401 break;
5402
5403 case CPU_DEAD:
5404 case CPU_DEAD_FROZEN:
5405 migrate_live_tasks(cpu);
5406 rq = cpu_rq(cpu);
5407 kthread_stop(rq->migration_thread);
5408 rq->migration_thread = NULL;
5409 /* Idle task back to normal (off runqueue, low prio) */
5410 rq = task_rq_lock(rq->idle, &flags);
5411 update_rq_clock(rq);
5412 deactivate_task(rq, rq->idle, 0);
5413 rq->idle->static_prio = MAX_PRIO;
5414 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5415 rq->idle->sched_class = &idle_sched_class;
5416 migrate_dead_tasks(cpu);
5417 task_rq_unlock(rq, &flags);
5418 migrate_nr_uninterruptible(rq);
5419 BUG_ON(rq->nr_running != 0);
5420
5421 /* No need to migrate the tasks: it was best-effort if
5422 * they didn't take sched_hotcpu_mutex. Just wake up
5423 * the requestors. */
5424 spin_lock_irq(&rq->lock);
5425 while (!list_empty(&rq->migration_queue)) {
5426 struct migration_req *req;
5427
5428 req = list_entry(rq->migration_queue.next,
5429 struct migration_req, list);
5430 list_del_init(&req->list);
5431 complete(&req->done);
5432 }
5433 spin_unlock_irq(&rq->lock);
5434 break;
5435 #endif
5436 case CPU_LOCK_RELEASE:
5437 mutex_unlock(&sched_hotcpu_mutex);
5438 break;
5439 }
5440 return NOTIFY_OK;
5441 }
5442
5443 /* Register at highest priority so that task migration (migrate_all_tasks)
5444 * happens before everything else.
5445 */
5446 static struct notifier_block __cpuinitdata migration_notifier = {
5447 .notifier_call = migration_call,
5448 .priority = 10
5449 };
5450
5451 int __init migration_init(void)
5452 {
5453 void *cpu = (void *)(long)smp_processor_id();
5454 int err;
5455
5456 /* Start one for the boot CPU: */
5457 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5458 BUG_ON(err == NOTIFY_BAD);
5459 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5460 register_cpu_notifier(&migration_notifier);
5461
5462 return 0;
5463 }
5464 #endif
5465
5466 #ifdef CONFIG_SMP
5467
5468 /* Number of possible processor ids */
5469 int nr_cpu_ids __read_mostly = NR_CPUS;
5470 EXPORT_SYMBOL(nr_cpu_ids);
5471
5472 #undef SCHED_DOMAIN_DEBUG
5473 #ifdef SCHED_DOMAIN_DEBUG
5474 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5475 {
5476 int level = 0;
5477
5478 if (!sd) {
5479 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5480 return;
5481 }
5482
5483 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5484
5485 do {
5486 int i;
5487 char str[NR_CPUS];
5488 struct sched_group *group = sd->groups;
5489 cpumask_t groupmask;
5490
5491 cpumask_scnprintf(str, NR_CPUS, sd->span);
5492 cpus_clear(groupmask);
5493
5494 printk(KERN_DEBUG);
5495 for (i = 0; i < level + 1; i++)
5496 printk(" ");
5497 printk("domain %d: ", level);
5498
5499 if (!(sd->flags & SD_LOAD_BALANCE)) {
5500 printk("does not load-balance\n");
5501 if (sd->parent)
5502 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5503 " has parent");
5504 break;
5505 }
5506
5507 printk("span %s\n", str);
5508
5509 if (!cpu_isset(cpu, sd->span))
5510 printk(KERN_ERR "ERROR: domain->span does not contain "
5511 "CPU%d\n", cpu);
5512 if (!cpu_isset(cpu, group->cpumask))
5513 printk(KERN_ERR "ERROR: domain->groups does not contain"
5514 " CPU%d\n", cpu);
5515
5516 printk(KERN_DEBUG);
5517 for (i = 0; i < level + 2; i++)
5518 printk(" ");
5519 printk("groups:");
5520 do {
5521 if (!group) {
5522 printk("\n");
5523 printk(KERN_ERR "ERROR: group is NULL\n");
5524 break;
5525 }
5526
5527 if (!group->__cpu_power) {
5528 printk("\n");
5529 printk(KERN_ERR "ERROR: domain->cpu_power not "
5530 "set\n");
5531 }
5532
5533 if (!cpus_weight(group->cpumask)) {
5534 printk("\n");
5535 printk(KERN_ERR "ERROR: empty group\n");
5536 }
5537
5538 if (cpus_intersects(groupmask, group->cpumask)) {
5539 printk("\n");
5540 printk(KERN_ERR "ERROR: repeated CPUs\n");
5541 }
5542
5543 cpus_or(groupmask, groupmask, group->cpumask);
5544
5545 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5546 printk(" %s", str);
5547
5548 group = group->next;
5549 } while (group != sd->groups);
5550 printk("\n");
5551
5552 if (!cpus_equal(sd->span, groupmask))
5553 printk(KERN_ERR "ERROR: groups don't span "
5554 "domain->span\n");
5555
5556 level++;
5557 sd = sd->parent;
5558 if (!sd)
5559 continue;
5560
5561 if (!cpus_subset(groupmask, sd->span))
5562 printk(KERN_ERR "ERROR: parent span is not a superset "
5563 "of domain->span\n");
5564
5565 } while (sd);
5566 }
5567 #else
5568 # define sched_domain_debug(sd, cpu) do { } while (0)
5569 #endif
5570
5571 static int sd_degenerate(struct sched_domain *sd)
5572 {
5573 if (cpus_weight(sd->span) == 1)
5574 return 1;
5575
5576 /* Following flags need at least 2 groups */
5577 if (sd->flags & (SD_LOAD_BALANCE |
5578 SD_BALANCE_NEWIDLE |
5579 SD_BALANCE_FORK |
5580 SD_BALANCE_EXEC |
5581 SD_SHARE_CPUPOWER |
5582 SD_SHARE_PKG_RESOURCES)) {
5583 if (sd->groups != sd->groups->next)
5584 return 0;
5585 }
5586
5587 /* Following flags don't use groups */
5588 if (sd->flags & (SD_WAKE_IDLE |
5589 SD_WAKE_AFFINE |
5590 SD_WAKE_BALANCE))
5591 return 0;
5592
5593 return 1;
5594 }
5595
5596 static int
5597 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5598 {
5599 unsigned long cflags = sd->flags, pflags = parent->flags;
5600
5601 if (sd_degenerate(parent))
5602 return 1;
5603
5604 if (!cpus_equal(sd->span, parent->span))
5605 return 0;
5606
5607 /* Does parent contain flags not in child? */
5608 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5609 if (cflags & SD_WAKE_AFFINE)
5610 pflags &= ~SD_WAKE_BALANCE;
5611 /* Flags needing groups don't count if only 1 group in parent */
5612 if (parent->groups == parent->groups->next) {
5613 pflags &= ~(SD_LOAD_BALANCE |
5614 SD_BALANCE_NEWIDLE |
5615 SD_BALANCE_FORK |
5616 SD_BALANCE_EXEC |
5617 SD_SHARE_CPUPOWER |
5618 SD_SHARE_PKG_RESOURCES);
5619 }
5620 if (~cflags & pflags)
5621 return 0;
5622
5623 return 1;
5624 }
5625
5626 /*
5627 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5628 * hold the hotplug lock.
5629 */
5630 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5631 {
5632 struct rq *rq = cpu_rq(cpu);
5633 struct sched_domain *tmp;
5634
5635 /* Remove the sched domains which do not contribute to scheduling. */
5636 for (tmp = sd; tmp; tmp = tmp->parent) {
5637 struct sched_domain *parent = tmp->parent;
5638 if (!parent)
5639 break;
5640 if (sd_parent_degenerate(tmp, parent)) {
5641 tmp->parent = parent->parent;
5642 if (parent->parent)
5643 parent->parent->child = tmp;
5644 }
5645 }
5646
5647 if (sd && sd_degenerate(sd)) {
5648 sd = sd->parent;
5649 if (sd)
5650 sd->child = NULL;
5651 }
5652
5653 sched_domain_debug(sd, cpu);
5654
5655 rcu_assign_pointer(rq->sd, sd);
5656 }
5657
5658 /* cpus with isolated domains */
5659 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
5660
5661 /* Setup the mask of cpus configured for isolated domains */
5662 static int __init isolated_cpu_setup(char *str)
5663 {
5664 int ints[NR_CPUS], i;
5665
5666 str = get_options(str, ARRAY_SIZE(ints), ints);
5667 cpus_clear(cpu_isolated_map);
5668 for (i = 1; i <= ints[0]; i++)
5669 if (ints[i] < NR_CPUS)
5670 cpu_set(ints[i], cpu_isolated_map);
5671 return 1;
5672 }
5673
5674 __setup ("isolcpus=", isolated_cpu_setup);
5675
5676 /*
5677 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5678 * to a function which identifies what group(along with sched group) a CPU
5679 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5680 * (due to the fact that we keep track of groups covered with a cpumask_t).
5681 *
5682 * init_sched_build_groups will build a circular linked list of the groups
5683 * covered by the given span, and will set each group's ->cpumask correctly,
5684 * and ->cpu_power to 0.
5685 */
5686 static void
5687 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5688 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5689 struct sched_group **sg))
5690 {
5691 struct sched_group *first = NULL, *last = NULL;
5692 cpumask_t covered = CPU_MASK_NONE;
5693 int i;
5694
5695 for_each_cpu_mask(i, span) {
5696 struct sched_group *sg;
5697 int group = group_fn(i, cpu_map, &sg);
5698 int j;
5699
5700 if (cpu_isset(i, covered))
5701 continue;
5702
5703 sg->cpumask = CPU_MASK_NONE;
5704 sg->__cpu_power = 0;
5705
5706 for_each_cpu_mask(j, span) {
5707 if (group_fn(j, cpu_map, NULL) != group)
5708 continue;
5709
5710 cpu_set(j, covered);
5711 cpu_set(j, sg->cpumask);
5712 }
5713 if (!first)
5714 first = sg;
5715 if (last)
5716 last->next = sg;
5717 last = sg;
5718 }
5719 last->next = first;
5720 }
5721
5722 #define SD_NODES_PER_DOMAIN 16
5723
5724 #ifdef CONFIG_NUMA
5725
5726 /**
5727 * find_next_best_node - find the next node to include in a sched_domain
5728 * @node: node whose sched_domain we're building
5729 * @used_nodes: nodes already in the sched_domain
5730 *
5731 * Find the next node to include in a given scheduling domain. Simply
5732 * finds the closest node not already in the @used_nodes map.
5733 *
5734 * Should use nodemask_t.
5735 */
5736 static int find_next_best_node(int node, unsigned long *used_nodes)
5737 {
5738 int i, n, val, min_val, best_node = 0;
5739
5740 min_val = INT_MAX;
5741
5742 for (i = 0; i < MAX_NUMNODES; i++) {
5743 /* Start at @node */
5744 n = (node + i) % MAX_NUMNODES;
5745
5746 if (!nr_cpus_node(n))
5747 continue;
5748
5749 /* Skip already used nodes */
5750 if (test_bit(n, used_nodes))
5751 continue;
5752
5753 /* Simple min distance search */
5754 val = node_distance(node, n);
5755
5756 if (val < min_val) {
5757 min_val = val;
5758 best_node = n;
5759 }
5760 }
5761
5762 set_bit(best_node, used_nodes);
5763 return best_node;
5764 }
5765
5766 /**
5767 * sched_domain_node_span - get a cpumask for a node's sched_domain
5768 * @node: node whose cpumask we're constructing
5769 * @size: number of nodes to include in this span
5770 *
5771 * Given a node, construct a good cpumask for its sched_domain to span. It
5772 * should be one that prevents unnecessary balancing, but also spreads tasks
5773 * out optimally.
5774 */
5775 static cpumask_t sched_domain_node_span(int node)
5776 {
5777 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5778 cpumask_t span, nodemask;
5779 int i;
5780
5781 cpus_clear(span);
5782 bitmap_zero(used_nodes, MAX_NUMNODES);
5783
5784 nodemask = node_to_cpumask(node);
5785 cpus_or(span, span, nodemask);
5786 set_bit(node, used_nodes);
5787
5788 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5789 int next_node = find_next_best_node(node, used_nodes);
5790
5791 nodemask = node_to_cpumask(next_node);
5792 cpus_or(span, span, nodemask);
5793 }
5794
5795 return span;
5796 }
5797 #endif
5798
5799 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
5800
5801 /*
5802 * SMT sched-domains:
5803 */
5804 #ifdef CONFIG_SCHED_SMT
5805 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5806 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
5807
5808 static int cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map,
5809 struct sched_group **sg)
5810 {
5811 if (sg)
5812 *sg = &per_cpu(sched_group_cpus, cpu);
5813 return cpu;
5814 }
5815 #endif
5816
5817 /*
5818 * multi-core sched-domains:
5819 */
5820 #ifdef CONFIG_SCHED_MC
5821 static DEFINE_PER_CPU(struct sched_domain, core_domains);
5822 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
5823 #endif
5824
5825 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
5826 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5827 struct sched_group **sg)
5828 {
5829 int group;
5830 cpumask_t mask = cpu_sibling_map[cpu];
5831 cpus_and(mask, mask, *cpu_map);
5832 group = first_cpu(mask);
5833 if (sg)
5834 *sg = &per_cpu(sched_group_core, group);
5835 return group;
5836 }
5837 #elif defined(CONFIG_SCHED_MC)
5838 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5839 struct sched_group **sg)
5840 {
5841 if (sg)
5842 *sg = &per_cpu(sched_group_core, cpu);
5843 return cpu;
5844 }
5845 #endif
5846
5847 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5848 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
5849
5850 static int cpu_to_phys_group(int cpu, const cpumask_t *cpu_map,
5851 struct sched_group **sg)
5852 {
5853 int group;
5854 #ifdef CONFIG_SCHED_MC
5855 cpumask_t mask = cpu_coregroup_map(cpu);
5856 cpus_and(mask, mask, *cpu_map);
5857 group = first_cpu(mask);
5858 #elif defined(CONFIG_SCHED_SMT)
5859 cpumask_t mask = cpu_sibling_map[cpu];
5860 cpus_and(mask, mask, *cpu_map);
5861 group = first_cpu(mask);
5862 #else
5863 group = cpu;
5864 #endif
5865 if (sg)
5866 *sg = &per_cpu(sched_group_phys, group);
5867 return group;
5868 }
5869
5870 #ifdef CONFIG_NUMA
5871 /*
5872 * The init_sched_build_groups can't handle what we want to do with node
5873 * groups, so roll our own. Now each node has its own list of groups which
5874 * gets dynamically allocated.
5875 */
5876 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5877 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5878
5879 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5880 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
5881
5882 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
5883 struct sched_group **sg)
5884 {
5885 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
5886 int group;
5887
5888 cpus_and(nodemask, nodemask, *cpu_map);
5889 group = first_cpu(nodemask);
5890
5891 if (sg)
5892 *sg = &per_cpu(sched_group_allnodes, group);
5893 return group;
5894 }
5895
5896 static void init_numa_sched_groups_power(struct sched_group *group_head)
5897 {
5898 struct sched_group *sg = group_head;
5899 int j;
5900
5901 if (!sg)
5902 return;
5903 next_sg:
5904 for_each_cpu_mask(j, sg->cpumask) {
5905 struct sched_domain *sd;
5906
5907 sd = &per_cpu(phys_domains, j);
5908 if (j != first_cpu(sd->groups->cpumask)) {
5909 /*
5910 * Only add "power" once for each
5911 * physical package.
5912 */
5913 continue;
5914 }
5915
5916 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
5917 }
5918 sg = sg->next;
5919 if (sg != group_head)
5920 goto next_sg;
5921 }
5922 #endif
5923
5924 #ifdef CONFIG_NUMA
5925 /* Free memory allocated for various sched_group structures */
5926 static void free_sched_groups(const cpumask_t *cpu_map)
5927 {
5928 int cpu, i;
5929
5930 for_each_cpu_mask(cpu, *cpu_map) {
5931 struct sched_group **sched_group_nodes
5932 = sched_group_nodes_bycpu[cpu];
5933
5934 if (!sched_group_nodes)
5935 continue;
5936
5937 for (i = 0; i < MAX_NUMNODES; i++) {
5938 cpumask_t nodemask = node_to_cpumask(i);
5939 struct sched_group *oldsg, *sg = sched_group_nodes[i];
5940
5941 cpus_and(nodemask, nodemask, *cpu_map);
5942 if (cpus_empty(nodemask))
5943 continue;
5944
5945 if (sg == NULL)
5946 continue;
5947 sg = sg->next;
5948 next_sg:
5949 oldsg = sg;
5950 sg = sg->next;
5951 kfree(oldsg);
5952 if (oldsg != sched_group_nodes[i])
5953 goto next_sg;
5954 }
5955 kfree(sched_group_nodes);
5956 sched_group_nodes_bycpu[cpu] = NULL;
5957 }
5958 }
5959 #else
5960 static void free_sched_groups(const cpumask_t *cpu_map)
5961 {
5962 }
5963 #endif
5964
5965 /*
5966 * Initialize sched groups cpu_power.
5967 *
5968 * cpu_power indicates the capacity of sched group, which is used while
5969 * distributing the load between different sched groups in a sched domain.
5970 * Typically cpu_power for all the groups in a sched domain will be same unless
5971 * there are asymmetries in the topology. If there are asymmetries, group
5972 * having more cpu_power will pickup more load compared to the group having
5973 * less cpu_power.
5974 *
5975 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
5976 * the maximum number of tasks a group can handle in the presence of other idle
5977 * or lightly loaded groups in the same sched domain.
5978 */
5979 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5980 {
5981 struct sched_domain *child;
5982 struct sched_group *group;
5983
5984 WARN_ON(!sd || !sd->groups);
5985
5986 if (cpu != first_cpu(sd->groups->cpumask))
5987 return;
5988
5989 child = sd->child;
5990
5991 sd->groups->__cpu_power = 0;
5992
5993 /*
5994 * For perf policy, if the groups in child domain share resources
5995 * (for example cores sharing some portions of the cache hierarchy
5996 * or SMT), then set this domain groups cpu_power such that each group
5997 * can handle only one task, when there are other idle groups in the
5998 * same sched domain.
5999 */
6000 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6001 (child->flags &
6002 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6003 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6004 return;
6005 }
6006
6007 /*
6008 * add cpu_power of each child group to this groups cpu_power
6009 */
6010 group = child->groups;
6011 do {
6012 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6013 group = group->next;
6014 } while (group != child->groups);
6015 }
6016
6017 /*
6018 * Build sched domains for a given set of cpus and attach the sched domains
6019 * to the individual cpus
6020 */
6021 static int build_sched_domains(const cpumask_t *cpu_map)
6022 {
6023 int i;
6024 #ifdef CONFIG_NUMA
6025 struct sched_group **sched_group_nodes = NULL;
6026 int sd_allnodes = 0;
6027
6028 /*
6029 * Allocate the per-node list of sched groups
6030 */
6031 sched_group_nodes = kzalloc(sizeof(struct sched_group *)*MAX_NUMNODES,
6032 GFP_KERNEL);
6033 if (!sched_group_nodes) {
6034 printk(KERN_WARNING "Can not alloc sched group node list\n");
6035 return -ENOMEM;
6036 }
6037 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6038 #endif
6039
6040 /*
6041 * Set up domains for cpus specified by the cpu_map.
6042 */
6043 for_each_cpu_mask(i, *cpu_map) {
6044 struct sched_domain *sd = NULL, *p;
6045 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6046
6047 cpus_and(nodemask, nodemask, *cpu_map);
6048
6049 #ifdef CONFIG_NUMA
6050 if (cpus_weight(*cpu_map) >
6051 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6052 sd = &per_cpu(allnodes_domains, i);
6053 *sd = SD_ALLNODES_INIT;
6054 sd->span = *cpu_map;
6055 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6056 p = sd;
6057 sd_allnodes = 1;
6058 } else
6059 p = NULL;
6060
6061 sd = &per_cpu(node_domains, i);
6062 *sd = SD_NODE_INIT;
6063 sd->span = sched_domain_node_span(cpu_to_node(i));
6064 sd->parent = p;
6065 if (p)
6066 p->child = sd;
6067 cpus_and(sd->span, sd->span, *cpu_map);
6068 #endif
6069
6070 p = sd;
6071 sd = &per_cpu(phys_domains, i);
6072 *sd = SD_CPU_INIT;
6073 sd->span = nodemask;
6074 sd->parent = p;
6075 if (p)
6076 p->child = sd;
6077 cpu_to_phys_group(i, cpu_map, &sd->groups);
6078
6079 #ifdef CONFIG_SCHED_MC
6080 p = sd;
6081 sd = &per_cpu(core_domains, i);
6082 *sd = SD_MC_INIT;
6083 sd->span = cpu_coregroup_map(i);
6084 cpus_and(sd->span, sd->span, *cpu_map);
6085 sd->parent = p;
6086 p->child = sd;
6087 cpu_to_core_group(i, cpu_map, &sd->groups);
6088 #endif
6089
6090 #ifdef CONFIG_SCHED_SMT
6091 p = sd;
6092 sd = &per_cpu(cpu_domains, i);
6093 *sd = SD_SIBLING_INIT;
6094 sd->span = cpu_sibling_map[i];
6095 cpus_and(sd->span, sd->span, *cpu_map);
6096 sd->parent = p;
6097 p->child = sd;
6098 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6099 #endif
6100 }
6101
6102 #ifdef CONFIG_SCHED_SMT
6103 /* Set up CPU (sibling) groups */
6104 for_each_cpu_mask(i, *cpu_map) {
6105 cpumask_t this_sibling_map = cpu_sibling_map[i];
6106 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6107 if (i != first_cpu(this_sibling_map))
6108 continue;
6109
6110 init_sched_build_groups(this_sibling_map, cpu_map,
6111 &cpu_to_cpu_group);
6112 }
6113 #endif
6114
6115 #ifdef CONFIG_SCHED_MC
6116 /* Set up multi-core groups */
6117 for_each_cpu_mask(i, *cpu_map) {
6118 cpumask_t this_core_map = cpu_coregroup_map(i);
6119 cpus_and(this_core_map, this_core_map, *cpu_map);
6120 if (i != first_cpu(this_core_map))
6121 continue;
6122 init_sched_build_groups(this_core_map, cpu_map,
6123 &cpu_to_core_group);
6124 }
6125 #endif
6126
6127 /* Set up physical groups */
6128 for (i = 0; i < MAX_NUMNODES; i++) {
6129 cpumask_t nodemask = node_to_cpumask(i);
6130
6131 cpus_and(nodemask, nodemask, *cpu_map);
6132 if (cpus_empty(nodemask))
6133 continue;
6134
6135 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6136 }
6137
6138 #ifdef CONFIG_NUMA
6139 /* Set up node groups */
6140 if (sd_allnodes)
6141 init_sched_build_groups(*cpu_map, cpu_map,
6142 &cpu_to_allnodes_group);
6143
6144 for (i = 0; i < MAX_NUMNODES; i++) {
6145 /* Set up node groups */
6146 struct sched_group *sg, *prev;
6147 cpumask_t nodemask = node_to_cpumask(i);
6148 cpumask_t domainspan;
6149 cpumask_t covered = CPU_MASK_NONE;
6150 int j;
6151
6152 cpus_and(nodemask, nodemask, *cpu_map);
6153 if (cpus_empty(nodemask)) {
6154 sched_group_nodes[i] = NULL;
6155 continue;
6156 }
6157
6158 domainspan = sched_domain_node_span(i);
6159 cpus_and(domainspan, domainspan, *cpu_map);
6160
6161 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6162 if (!sg) {
6163 printk(KERN_WARNING "Can not alloc domain group for "
6164 "node %d\n", i);
6165 goto error;
6166 }
6167 sched_group_nodes[i] = sg;
6168 for_each_cpu_mask(j, nodemask) {
6169 struct sched_domain *sd;
6170
6171 sd = &per_cpu(node_domains, j);
6172 sd->groups = sg;
6173 }
6174 sg->__cpu_power = 0;
6175 sg->cpumask = nodemask;
6176 sg->next = sg;
6177 cpus_or(covered, covered, nodemask);
6178 prev = sg;
6179
6180 for (j = 0; j < MAX_NUMNODES; j++) {
6181 cpumask_t tmp, notcovered;
6182 int n = (i + j) % MAX_NUMNODES;
6183
6184 cpus_complement(notcovered, covered);
6185 cpus_and(tmp, notcovered, *cpu_map);
6186 cpus_and(tmp, tmp, domainspan);
6187 if (cpus_empty(tmp))
6188 break;
6189
6190 nodemask = node_to_cpumask(n);
6191 cpus_and(tmp, tmp, nodemask);
6192 if (cpus_empty(tmp))
6193 continue;
6194
6195 sg = kmalloc_node(sizeof(struct sched_group),
6196 GFP_KERNEL, i);
6197 if (!sg) {
6198 printk(KERN_WARNING
6199 "Can not alloc domain group for node %d\n", j);
6200 goto error;
6201 }
6202 sg->__cpu_power = 0;
6203 sg->cpumask = tmp;
6204 sg->next = prev->next;
6205 cpus_or(covered, covered, tmp);
6206 prev->next = sg;
6207 prev = sg;
6208 }
6209 }
6210 #endif
6211
6212 /* Calculate CPU power for physical packages and nodes */
6213 #ifdef CONFIG_SCHED_SMT
6214 for_each_cpu_mask(i, *cpu_map) {
6215 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6216
6217 init_sched_groups_power(i, sd);
6218 }
6219 #endif
6220 #ifdef CONFIG_SCHED_MC
6221 for_each_cpu_mask(i, *cpu_map) {
6222 struct sched_domain *sd = &per_cpu(core_domains, i);
6223
6224 init_sched_groups_power(i, sd);
6225 }
6226 #endif
6227
6228 for_each_cpu_mask(i, *cpu_map) {
6229 struct sched_domain *sd = &per_cpu(phys_domains, i);
6230
6231 init_sched_groups_power(i, sd);
6232 }
6233
6234 #ifdef CONFIG_NUMA
6235 for (i = 0; i < MAX_NUMNODES; i++)
6236 init_numa_sched_groups_power(sched_group_nodes[i]);
6237
6238 if (sd_allnodes) {
6239 struct sched_group *sg;
6240
6241 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6242 init_numa_sched_groups_power(sg);
6243 }
6244 #endif
6245
6246 /* Attach the domains */
6247 for_each_cpu_mask(i, *cpu_map) {
6248 struct sched_domain *sd;
6249 #ifdef CONFIG_SCHED_SMT
6250 sd = &per_cpu(cpu_domains, i);
6251 #elif defined(CONFIG_SCHED_MC)
6252 sd = &per_cpu(core_domains, i);
6253 #else
6254 sd = &per_cpu(phys_domains, i);
6255 #endif
6256 cpu_attach_domain(sd, i);
6257 }
6258
6259 return 0;
6260
6261 #ifdef CONFIG_NUMA
6262 error:
6263 free_sched_groups(cpu_map);
6264 return -ENOMEM;
6265 #endif
6266 }
6267 /*
6268 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6269 */
6270 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6271 {
6272 cpumask_t cpu_default_map;
6273 int err;
6274
6275 /*
6276 * Setup mask for cpus without special case scheduling requirements.
6277 * For now this just excludes isolated cpus, but could be used to
6278 * exclude other special cases in the future.
6279 */
6280 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6281
6282 err = build_sched_domains(&cpu_default_map);
6283
6284 return err;
6285 }
6286
6287 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6288 {
6289 free_sched_groups(cpu_map);
6290 }
6291
6292 /*
6293 * Detach sched domains from a group of cpus specified in cpu_map
6294 * These cpus will now be attached to the NULL domain
6295 */
6296 static void detach_destroy_domains(const cpumask_t *cpu_map)
6297 {
6298 int i;
6299
6300 for_each_cpu_mask(i, *cpu_map)
6301 cpu_attach_domain(NULL, i);
6302 synchronize_sched();
6303 arch_destroy_sched_domains(cpu_map);
6304 }
6305
6306 /*
6307 * Partition sched domains as specified by the cpumasks below.
6308 * This attaches all cpus from the cpumasks to the NULL domain,
6309 * waits for a RCU quiescent period, recalculates sched
6310 * domain information and then attaches them back to the
6311 * correct sched domains
6312 * Call with hotplug lock held
6313 */
6314 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6315 {
6316 cpumask_t change_map;
6317 int err = 0;
6318
6319 cpus_and(*partition1, *partition1, cpu_online_map);
6320 cpus_and(*partition2, *partition2, cpu_online_map);
6321 cpus_or(change_map, *partition1, *partition2);
6322
6323 /* Detach sched domains from all of the affected cpus */
6324 detach_destroy_domains(&change_map);
6325 if (!cpus_empty(*partition1))
6326 err = build_sched_domains(partition1);
6327 if (!err && !cpus_empty(*partition2))
6328 err = build_sched_domains(partition2);
6329
6330 return err;
6331 }
6332
6333 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6334 static int arch_reinit_sched_domains(void)
6335 {
6336 int err;
6337
6338 mutex_lock(&sched_hotcpu_mutex);
6339 detach_destroy_domains(&cpu_online_map);
6340 err = arch_init_sched_domains(&cpu_online_map);
6341 mutex_unlock(&sched_hotcpu_mutex);
6342
6343 return err;
6344 }
6345
6346 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6347 {
6348 int ret;
6349
6350 if (buf[0] != '0' && buf[0] != '1')
6351 return -EINVAL;
6352
6353 if (smt)
6354 sched_smt_power_savings = (buf[0] == '1');
6355 else
6356 sched_mc_power_savings = (buf[0] == '1');
6357
6358 ret = arch_reinit_sched_domains();
6359
6360 return ret ? ret : count;
6361 }
6362
6363 #ifdef CONFIG_SCHED_MC
6364 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6365 {
6366 return sprintf(page, "%u\n", sched_mc_power_savings);
6367 }
6368 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6369 const char *buf, size_t count)
6370 {
6371 return sched_power_savings_store(buf, count, 0);
6372 }
6373 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6374 sched_mc_power_savings_store);
6375 #endif
6376
6377 #ifdef CONFIG_SCHED_SMT
6378 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6379 {
6380 return sprintf(page, "%u\n", sched_smt_power_savings);
6381 }
6382 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6383 const char *buf, size_t count)
6384 {
6385 return sched_power_savings_store(buf, count, 1);
6386 }
6387 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6388 sched_smt_power_savings_store);
6389 #endif
6390
6391 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6392 {
6393 int err = 0;
6394
6395 #ifdef CONFIG_SCHED_SMT
6396 if (smt_capable())
6397 err = sysfs_create_file(&cls->kset.kobj,
6398 &attr_sched_smt_power_savings.attr);
6399 #endif
6400 #ifdef CONFIG_SCHED_MC
6401 if (!err && mc_capable())
6402 err = sysfs_create_file(&cls->kset.kobj,
6403 &attr_sched_mc_power_savings.attr);
6404 #endif
6405 return err;
6406 }
6407 #endif
6408
6409 /*
6410 * Force a reinitialization of the sched domains hierarchy. The domains
6411 * and groups cannot be updated in place without racing with the balancing
6412 * code, so we temporarily attach all running cpus to the NULL domain
6413 * which will prevent rebalancing while the sched domains are recalculated.
6414 */
6415 static int update_sched_domains(struct notifier_block *nfb,
6416 unsigned long action, void *hcpu)
6417 {
6418 switch (action) {
6419 case CPU_UP_PREPARE:
6420 case CPU_UP_PREPARE_FROZEN:
6421 case CPU_DOWN_PREPARE:
6422 case CPU_DOWN_PREPARE_FROZEN:
6423 detach_destroy_domains(&cpu_online_map);
6424 return NOTIFY_OK;
6425
6426 case CPU_UP_CANCELED:
6427 case CPU_UP_CANCELED_FROZEN:
6428 case CPU_DOWN_FAILED:
6429 case CPU_DOWN_FAILED_FROZEN:
6430 case CPU_ONLINE:
6431 case CPU_ONLINE_FROZEN:
6432 case CPU_DEAD:
6433 case CPU_DEAD_FROZEN:
6434 /*
6435 * Fall through and re-initialise the domains.
6436 */
6437 break;
6438 default:
6439 return NOTIFY_DONE;
6440 }
6441
6442 /* The hotplug lock is already held by cpu_up/cpu_down */
6443 arch_init_sched_domains(&cpu_online_map);
6444
6445 return NOTIFY_OK;
6446 }
6447
6448 void __init sched_init_smp(void)
6449 {
6450 cpumask_t non_isolated_cpus;
6451
6452 mutex_lock(&sched_hotcpu_mutex);
6453 arch_init_sched_domains(&cpu_online_map);
6454 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
6455 if (cpus_empty(non_isolated_cpus))
6456 cpu_set(smp_processor_id(), non_isolated_cpus);
6457 mutex_unlock(&sched_hotcpu_mutex);
6458 /* XXX: Theoretical race here - CPU may be hotplugged now */
6459 hotcpu_notifier(update_sched_domains, 0);
6460
6461 init_sched_domain_sysctl();
6462
6463 /* Move init over to a non-isolated CPU */
6464 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6465 BUG();
6466 }
6467 #else
6468 void __init sched_init_smp(void)
6469 {
6470 }
6471 #endif /* CONFIG_SMP */
6472
6473 int in_sched_functions(unsigned long addr)
6474 {
6475 /* Linker adds these: start and end of __sched functions */
6476 extern char __sched_text_start[], __sched_text_end[];
6477
6478 return in_lock_functions(addr) ||
6479 (addr >= (unsigned long)__sched_text_start
6480 && addr < (unsigned long)__sched_text_end);
6481 }
6482
6483 static inline void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
6484 {
6485 cfs_rq->tasks_timeline = RB_ROOT;
6486 #ifdef CONFIG_FAIR_GROUP_SCHED
6487 cfs_rq->rq = rq;
6488 #endif
6489 }
6490
6491 void __init sched_init(void)
6492 {
6493 int highest_cpu = 0;
6494 int i, j;
6495
6496 /*
6497 * Link up the scheduling class hierarchy:
6498 */
6499 rt_sched_class.next = &fair_sched_class;
6500 fair_sched_class.next = &idle_sched_class;
6501 idle_sched_class.next = NULL;
6502
6503 for_each_possible_cpu(i) {
6504 struct rt_prio_array *array;
6505 struct rq *rq;
6506
6507 rq = cpu_rq(i);
6508 spin_lock_init(&rq->lock);
6509 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6510 rq->nr_running = 0;
6511 rq->clock = 1;
6512 init_cfs_rq(&rq->cfs, rq);
6513 #ifdef CONFIG_FAIR_GROUP_SCHED
6514 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6515 {
6516 struct cfs_rq *cfs_rq = &per_cpu(init_cfs_rq, i);
6517 struct sched_entity *se =
6518 &per_cpu(init_sched_entity, i);
6519
6520 init_cfs_rq_p[i] = cfs_rq;
6521 init_cfs_rq(cfs_rq, rq);
6522 cfs_rq->tg = &init_task_grp;
6523 list_add(&cfs_rq->leaf_cfs_rq_list,
6524 &rq->leaf_cfs_rq_list);
6525
6526 init_sched_entity_p[i] = se;
6527 se->cfs_rq = &rq->cfs;
6528 se->my_q = cfs_rq;
6529 se->load.weight = init_task_grp_load;
6530 se->load.inv_weight =
6531 div64_64(1ULL<<32, init_task_grp_load);
6532 se->parent = NULL;
6533 }
6534 init_task_grp.shares = init_task_grp_load;
6535 #endif
6536
6537 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6538 rq->cpu_load[j] = 0;
6539 #ifdef CONFIG_SMP
6540 rq->sd = NULL;
6541 rq->active_balance = 0;
6542 rq->next_balance = jiffies;
6543 rq->push_cpu = 0;
6544 rq->cpu = i;
6545 rq->migration_thread = NULL;
6546 INIT_LIST_HEAD(&rq->migration_queue);
6547 #endif
6548 atomic_set(&rq->nr_iowait, 0);
6549
6550 array = &rq->rt.active;
6551 for (j = 0; j < MAX_RT_PRIO; j++) {
6552 INIT_LIST_HEAD(array->queue + j);
6553 __clear_bit(j, array->bitmap);
6554 }
6555 highest_cpu = i;
6556 /* delimiter for bitsearch: */
6557 __set_bit(MAX_RT_PRIO, array->bitmap);
6558 }
6559
6560 set_load_weight(&init_task);
6561
6562 #ifdef CONFIG_PREEMPT_NOTIFIERS
6563 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
6564 #endif
6565
6566 #ifdef CONFIG_SMP
6567 nr_cpu_ids = highest_cpu + 1;
6568 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
6569 #endif
6570
6571 #ifdef CONFIG_RT_MUTEXES
6572 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6573 #endif
6574
6575 /*
6576 * The boot idle thread does lazy MMU switching as well:
6577 */
6578 atomic_inc(&init_mm.mm_count);
6579 enter_lazy_tlb(&init_mm, current);
6580
6581 /*
6582 * Make us the idle thread. Technically, schedule() should not be
6583 * called from this thread, however somewhere below it might be,
6584 * but because we are the idle thread, we just pick up running again
6585 * when this runqueue becomes "idle".
6586 */
6587 init_idle(current, smp_processor_id());
6588 /*
6589 * During early bootup we pretend to be a normal task:
6590 */
6591 current->sched_class = &fair_sched_class;
6592 }
6593
6594 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6595 void __might_sleep(char *file, int line)
6596 {
6597 #ifdef in_atomic
6598 static unsigned long prev_jiffy; /* ratelimiting */
6599
6600 if ((in_atomic() || irqs_disabled()) &&
6601 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6602 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6603 return;
6604 prev_jiffy = jiffies;
6605 printk(KERN_ERR "BUG: sleeping function called from invalid"
6606 " context at %s:%d\n", file, line);
6607 printk("in_atomic():%d, irqs_disabled():%d\n",
6608 in_atomic(), irqs_disabled());
6609 debug_show_held_locks(current);
6610 if (irqs_disabled())
6611 print_irqtrace_events(current);
6612 dump_stack();
6613 }
6614 #endif
6615 }
6616 EXPORT_SYMBOL(__might_sleep);
6617 #endif
6618
6619 #ifdef CONFIG_MAGIC_SYSRQ
6620 void normalize_rt_tasks(void)
6621 {
6622 struct task_struct *g, *p;
6623 unsigned long flags;
6624 struct rq *rq;
6625 int on_rq;
6626
6627 read_lock_irq(&tasklist_lock);
6628 do_each_thread(g, p) {
6629 p->se.exec_start = 0;
6630 #ifdef CONFIG_SCHEDSTATS
6631 p->se.wait_start = 0;
6632 p->se.sleep_start = 0;
6633 p->se.block_start = 0;
6634 #endif
6635 task_rq(p)->clock = 0;
6636
6637 if (!rt_task(p)) {
6638 /*
6639 * Renice negative nice level userspace
6640 * tasks back to 0:
6641 */
6642 if (TASK_NICE(p) < 0 && p->mm)
6643 set_user_nice(p, 0);
6644 continue;
6645 }
6646
6647 spin_lock_irqsave(&p->pi_lock, flags);
6648 rq = __task_rq_lock(p);
6649 #ifdef CONFIG_SMP
6650 /*
6651 * Do not touch the migration thread:
6652 */
6653 if (p == rq->migration_thread)
6654 goto out_unlock;
6655 #endif
6656
6657 update_rq_clock(rq);
6658 on_rq = p->se.on_rq;
6659 if (on_rq)
6660 deactivate_task(rq, p, 0);
6661 __setscheduler(rq, p, SCHED_NORMAL, 0);
6662 if (on_rq) {
6663 activate_task(rq, p, 0);
6664 resched_task(rq->curr);
6665 }
6666 #ifdef CONFIG_SMP
6667 out_unlock:
6668 #endif
6669 __task_rq_unlock(rq);
6670 spin_unlock_irqrestore(&p->pi_lock, flags);
6671 } while_each_thread(g, p);
6672
6673 read_unlock_irq(&tasklist_lock);
6674 }
6675
6676 #endif /* CONFIG_MAGIC_SYSRQ */
6677
6678 #ifdef CONFIG_IA64
6679 /*
6680 * These functions are only useful for the IA64 MCA handling.
6681 *
6682 * They can only be called when the whole system has been
6683 * stopped - every CPU needs to be quiescent, and no scheduling
6684 * activity can take place. Using them for anything else would
6685 * be a serious bug, and as a result, they aren't even visible
6686 * under any other configuration.
6687 */
6688
6689 /**
6690 * curr_task - return the current task for a given cpu.
6691 * @cpu: the processor in question.
6692 *
6693 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6694 */
6695 struct task_struct *curr_task(int cpu)
6696 {
6697 return cpu_curr(cpu);
6698 }
6699
6700 /**
6701 * set_curr_task - set the current task for a given cpu.
6702 * @cpu: the processor in question.
6703 * @p: the task pointer to set.
6704 *
6705 * Description: This function must only be used when non-maskable interrupts
6706 * are serviced on a separate stack. It allows the architecture to switch the
6707 * notion of the current task on a cpu in a non-blocking manner. This function
6708 * must be called with all CPU's synchronized, and interrupts disabled, the
6709 * and caller must save the original value of the current task (see
6710 * curr_task() above) and restore that value before reenabling interrupts and
6711 * re-starting the system.
6712 *
6713 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6714 */
6715 void set_curr_task(int cpu, struct task_struct *p)
6716 {
6717 cpu_curr(cpu) = p;
6718 }
6719
6720 #endif
6721
6722 #ifdef CONFIG_FAIR_GROUP_SCHED
6723
6724 /* allocate runqueue etc for a new task group */
6725 struct task_grp *sched_create_group(void)
6726 {
6727 struct task_grp *tg;
6728 struct cfs_rq *cfs_rq;
6729 struct sched_entity *se;
6730 struct rq *rq;
6731 int i;
6732
6733 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
6734 if (!tg)
6735 return ERR_PTR(-ENOMEM);
6736
6737 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
6738 if (!tg->cfs_rq)
6739 goto err;
6740 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
6741 if (!tg->se)
6742 goto err;
6743
6744 for_each_possible_cpu(i) {
6745 rq = cpu_rq(i);
6746
6747 cfs_rq = kmalloc_node(sizeof(struct cfs_rq), GFP_KERNEL,
6748 cpu_to_node(i));
6749 if (!cfs_rq)
6750 goto err;
6751
6752 se = kmalloc_node(sizeof(struct sched_entity), GFP_KERNEL,
6753 cpu_to_node(i));
6754 if (!se)
6755 goto err;
6756
6757 memset(cfs_rq, 0, sizeof(struct cfs_rq));
6758 memset(se, 0, sizeof(struct sched_entity));
6759
6760 tg->cfs_rq[i] = cfs_rq;
6761 init_cfs_rq(cfs_rq, rq);
6762 cfs_rq->tg = tg;
6763
6764 tg->se[i] = se;
6765 se->cfs_rq = &rq->cfs;
6766 se->my_q = cfs_rq;
6767 se->load.weight = NICE_0_LOAD;
6768 se->load.inv_weight = div64_64(1ULL<<32, NICE_0_LOAD);
6769 se->parent = NULL;
6770 }
6771
6772 for_each_possible_cpu(i) {
6773 rq = cpu_rq(i);
6774 cfs_rq = tg->cfs_rq[i];
6775 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
6776 }
6777
6778 tg->shares = NICE_0_LOAD;
6779
6780 return tg;
6781
6782 err:
6783 for_each_possible_cpu(i) {
6784 if (tg->cfs_rq && tg->cfs_rq[i])
6785 kfree(tg->cfs_rq[i]);
6786 if (tg->se && tg->se[i])
6787 kfree(tg->se[i]);
6788 }
6789 if (tg->cfs_rq)
6790 kfree(tg->cfs_rq);
6791 if (tg->se)
6792 kfree(tg->se);
6793 if (tg)
6794 kfree(tg);
6795
6796 return ERR_PTR(-ENOMEM);
6797 }
6798
6799 /* rcu callback to free various structures associated with a task group */
6800 static void free_sched_group(struct rcu_head *rhp)
6801 {
6802 struct cfs_rq *cfs_rq = container_of(rhp, struct cfs_rq, rcu);
6803 struct task_grp *tg = cfs_rq->tg;
6804 struct sched_entity *se;
6805 int i;
6806
6807 /* now it should be safe to free those cfs_rqs */
6808 for_each_possible_cpu(i) {
6809 cfs_rq = tg->cfs_rq[i];
6810 kfree(cfs_rq);
6811
6812 se = tg->se[i];
6813 kfree(se);
6814 }
6815
6816 kfree(tg->cfs_rq);
6817 kfree(tg->se);
6818 kfree(tg);
6819 }
6820
6821 /* Destroy runqueue etc associated with a task group */
6822 void sched_destroy_group(struct task_grp *tg)
6823 {
6824 struct cfs_rq *cfs_rq;
6825 int i;
6826
6827 for_each_possible_cpu(i) {
6828 cfs_rq = tg->cfs_rq[i];
6829 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
6830 }
6831
6832 cfs_rq = tg->cfs_rq[0];
6833
6834 /* wait for possible concurrent references to cfs_rqs complete */
6835 call_rcu(&cfs_rq->rcu, free_sched_group);
6836 }
6837
6838 /* change task's runqueue when it moves between groups.
6839 * The caller of this function should have put the task in its new group
6840 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
6841 * reflect its new group.
6842 */
6843 void sched_move_task(struct task_struct *tsk)
6844 {
6845 int on_rq, running;
6846 unsigned long flags;
6847 struct rq *rq;
6848
6849 rq = task_rq_lock(tsk, &flags);
6850
6851 if (tsk->sched_class != &fair_sched_class)
6852 goto done;
6853
6854 update_rq_clock(rq);
6855
6856 running = task_running(rq, tsk);
6857 on_rq = tsk->se.on_rq;
6858
6859 if (on_rq) {
6860 dequeue_task(rq, tsk, 0);
6861 if (unlikely(running))
6862 tsk->sched_class->put_prev_task(rq, tsk);
6863 }
6864
6865 set_task_cfs_rq(tsk);
6866
6867 if (on_rq) {
6868 if (unlikely(running))
6869 tsk->sched_class->set_curr_task(rq);
6870 enqueue_task(rq, tsk, 0);
6871 }
6872
6873 done:
6874 task_rq_unlock(rq, &flags);
6875 }
6876
6877 static void set_se_shares(struct sched_entity *se, unsigned long shares)
6878 {
6879 struct cfs_rq *cfs_rq = se->cfs_rq;
6880 struct rq *rq = cfs_rq->rq;
6881 int on_rq;
6882
6883 spin_lock_irq(&rq->lock);
6884
6885 on_rq = se->on_rq;
6886 if (on_rq)
6887 dequeue_entity(cfs_rq, se, 0);
6888
6889 se->load.weight = shares;
6890 se->load.inv_weight = div64_64((1ULL<<32), shares);
6891
6892 if (on_rq)
6893 enqueue_entity(cfs_rq, se, 0);
6894
6895 spin_unlock_irq(&rq->lock);
6896 }
6897
6898 int sched_group_set_shares(struct task_grp *tg, unsigned long shares)
6899 {
6900 int i;
6901
6902 if (tg->shares == shares)
6903 return 0;
6904
6905 /* return -EINVAL if the new value is not sane */
6906
6907 tg->shares = shares;
6908 for_each_possible_cpu(i)
6909 set_se_shares(tg->se[i], shares);
6910
6911 return 0;
6912 }
6913
6914 #endif /* CONFIG_FAIR_GROUP_SCHED */
This page took 0.158704 seconds and 4 git commands to generate.