4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
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
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
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/capability.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/debug_locks.h>
34 #include <linux/security.h>
35 #include <linux/notifier.h>
36 #include <linux/profile.h>
37 #include <linux/suspend.h>
38 #include <linux/vmalloc.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <linux/kprobes.h>
56 #include <asm/unistd.h>
59 * Convert user-nice values [ -20 ... 0 ... 19 ]
60 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
63 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
64 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
65 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
68 * 'User priority' is the nice value converted to something we
69 * can work with better when scaling various scheduler parameters,
70 * it's a [ 0 ... 39 ] range.
72 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
73 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
74 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
77 * Some helpers for converting nanosecond timing to jiffy resolution
79 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
80 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
83 * These are the 'tuning knobs' of the scheduler:
85 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
86 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
87 * Timeslices get refilled after they expire.
89 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
90 #define DEF_TIMESLICE (100 * HZ / 1000)
91 #define ON_RUNQUEUE_WEIGHT 30
92 #define CHILD_PENALTY 95
93 #define PARENT_PENALTY 100
95 #define PRIO_BONUS_RATIO 25
96 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
97 #define INTERACTIVE_DELTA 2
98 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
99 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
100 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
103 * If a task is 'interactive' then we reinsert it in the active
104 * array after it has expired its current timeslice. (it will not
105 * continue to run immediately, it will still roundrobin with
106 * other interactive tasks.)
108 * This part scales the interactivity limit depending on niceness.
110 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
111 * Here are a few examples of different nice levels:
113 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
114 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
115 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
117 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
119 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
120 * priority range a task can explore, a value of '1' means the
121 * task is rated interactive.)
123 * Ie. nice +19 tasks can never get 'interactive' enough to be
124 * reinserted into the active array. And only heavily CPU-hog nice -20
125 * tasks will be expired. Default nice 0 tasks are somewhere between,
126 * it takes some effort for them to get interactive, but it's not
130 #define CURRENT_BONUS(p) \
131 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
134 #define GRANULARITY (10 * HZ / 1000 ? : 1)
137 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
138 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
141 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
142 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
145 #define SCALE(v1,v1_max,v2_max) \
146 (v1) * (v2_max) / (v1_max)
149 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
152 #define TASK_INTERACTIVE(p) \
153 ((p)->prio <= (p)->static_prio - DELTA(p))
155 #define INTERACTIVE_SLEEP(p) \
156 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
157 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
159 #define TASK_PREEMPTS_CURR(p, rq) \
160 ((p)->prio < (rq)->curr->prio)
163 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
164 * to time slice values: [800ms ... 100ms ... 5ms]
166 * The higher a thread's priority, the bigger timeslices
167 * it gets during one round of execution. But even the lowest
168 * priority thread gets MIN_TIMESLICE worth of execution time.
171 #define SCALE_PRIO(x, prio) \
172 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
174 static unsigned int static_prio_timeslice(int static_prio
)
176 if (static_prio
< NICE_TO_PRIO(0))
177 return SCALE_PRIO(DEF_TIMESLICE
* 4, static_prio
);
179 return SCALE_PRIO(DEF_TIMESLICE
, static_prio
);
182 static inline unsigned int task_timeslice(struct task_struct
*p
)
184 return static_prio_timeslice(p
->static_prio
);
188 * These are the runqueue data structures:
192 unsigned int nr_active
;
193 DECLARE_BITMAP(bitmap
, MAX_PRIO
+1); /* include 1 bit for delimiter */
194 struct list_head queue
[MAX_PRIO
];
198 * This is the main, per-CPU runqueue data structure.
200 * Locking rule: those places that want to lock multiple runqueues
201 * (such as the load balancing or the thread migration code), lock
202 * acquire operations must be ordered by ascending &runqueue.
208 * nr_running and cpu_load should be in the same cacheline because
209 * remote CPUs use both these fields when doing load calculation.
211 unsigned long nr_running
;
212 unsigned long raw_weighted_load
;
214 unsigned long cpu_load
[3];
216 unsigned long long nr_switches
;
219 * This is part of a global counter where only the total sum
220 * over all CPUs matters. A task can increase this counter on
221 * one CPU and if it got migrated afterwards it may decrease
222 * it on another CPU. Always updated under the runqueue lock:
224 unsigned long nr_uninterruptible
;
226 unsigned long expired_timestamp
;
227 unsigned long long timestamp_last_tick
;
228 struct task_struct
*curr
, *idle
;
229 struct mm_struct
*prev_mm
;
230 struct prio_array
*active
, *expired
, arrays
[2];
231 int best_expired_prio
;
235 struct sched_domain
*sd
;
237 /* For active balancing */
241 struct task_struct
*migration_thread
;
242 struct list_head migration_queue
;
245 #ifdef CONFIG_SCHEDSTATS
247 struct sched_info rq_sched_info
;
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty
;
251 unsigned long yld_act_empty
;
252 unsigned long yld_both_empty
;
253 unsigned long yld_cnt
;
255 /* schedule() stats */
256 unsigned long sched_switch
;
257 unsigned long sched_cnt
;
258 unsigned long sched_goidle
;
260 /* try_to_wake_up() stats */
261 unsigned long ttwu_cnt
;
262 unsigned long ttwu_local
;
264 struct lock_class_key rq_lock_key
;
267 static DEFINE_PER_CPU(struct rq
, runqueues
);
270 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
271 * See detach_destroy_domains: synchronize_sched for details.
273 * The domain tree of any CPU may only be accessed from within
274 * preempt-disabled sections.
276 #define for_each_domain(cpu, __sd) \
277 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
279 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
280 #define this_rq() (&__get_cpu_var(runqueues))
281 #define task_rq(p) cpu_rq(task_cpu(p))
282 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
284 #ifndef prepare_arch_switch
285 # define prepare_arch_switch(next) do { } while (0)
287 #ifndef finish_arch_switch
288 # define finish_arch_switch(prev) do { } while (0)
291 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
292 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
294 return rq
->curr
== p
;
297 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
301 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
303 #ifdef CONFIG_DEBUG_SPINLOCK
304 /* this is a valid case when another task releases the spinlock */
305 rq
->lock
.owner
= current
;
308 * If we are tracking spinlock dependencies then we have to
309 * fix up the runqueue lock - which gets 'carried over' from
312 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
314 spin_unlock_irq(&rq
->lock
);
317 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
318 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
323 return rq
->curr
== p
;
327 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
331 * We can optimise this out completely for !SMP, because the
332 * SMP rebalancing from interrupt is the only thing that cares
337 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
338 spin_unlock_irq(&rq
->lock
);
340 spin_unlock(&rq
->lock
);
344 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
348 * After ->oncpu is cleared, the task can be moved to a different CPU.
349 * We must ensure this doesn't happen until the switch is completely
355 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
359 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
362 * __task_rq_lock - lock the runqueue a given task resides on.
363 * Must be called interrupts disabled.
365 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
372 spin_lock(&rq
->lock
);
373 if (unlikely(rq
!= task_rq(p
))) {
374 spin_unlock(&rq
->lock
);
375 goto repeat_lock_task
;
381 * task_rq_lock - lock the runqueue a given task resides on and disable
382 * interrupts. Note the ordering: we can safely lookup the task_rq without
383 * explicitly disabling preemption.
385 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
391 local_irq_save(*flags
);
393 spin_lock(&rq
->lock
);
394 if (unlikely(rq
!= task_rq(p
))) {
395 spin_unlock_irqrestore(&rq
->lock
, *flags
);
396 goto repeat_lock_task
;
401 static inline void __task_rq_unlock(struct rq
*rq
)
404 spin_unlock(&rq
->lock
);
407 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
410 spin_unlock_irqrestore(&rq
->lock
, *flags
);
413 #ifdef CONFIG_SCHEDSTATS
415 * bump this up when changing the output format or the meaning of an existing
416 * format, so that tools can adapt (or abort)
418 #define SCHEDSTAT_VERSION 12
420 static int show_schedstat(struct seq_file
*seq
, void *v
)
424 seq_printf(seq
, "version %d\n", SCHEDSTAT_VERSION
);
425 seq_printf(seq
, "timestamp %lu\n", jiffies
);
426 for_each_online_cpu(cpu
) {
427 struct rq
*rq
= cpu_rq(cpu
);
429 struct sched_domain
*sd
;
433 /* runqueue-specific stats */
435 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
436 cpu
, rq
->yld_both_empty
,
437 rq
->yld_act_empty
, rq
->yld_exp_empty
, rq
->yld_cnt
,
438 rq
->sched_switch
, rq
->sched_cnt
, rq
->sched_goidle
,
439 rq
->ttwu_cnt
, rq
->ttwu_local
,
440 rq
->rq_sched_info
.cpu_time
,
441 rq
->rq_sched_info
.run_delay
, rq
->rq_sched_info
.pcnt
);
443 seq_printf(seq
, "\n");
446 /* domain-specific stats */
448 for_each_domain(cpu
, sd
) {
449 enum idle_type itype
;
450 char mask_str
[NR_CPUS
];
452 cpumask_scnprintf(mask_str
, NR_CPUS
, sd
->span
);
453 seq_printf(seq
, "domain%d %s", dcnt
++, mask_str
);
454 for (itype
= SCHED_IDLE
; itype
< MAX_IDLE_TYPES
;
456 seq_printf(seq
, " %lu %lu %lu %lu %lu %lu %lu %lu",
458 sd
->lb_balanced
[itype
],
459 sd
->lb_failed
[itype
],
460 sd
->lb_imbalance
[itype
],
461 sd
->lb_gained
[itype
],
462 sd
->lb_hot_gained
[itype
],
463 sd
->lb_nobusyq
[itype
],
464 sd
->lb_nobusyg
[itype
]);
466 seq_printf(seq
, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
467 sd
->alb_cnt
, sd
->alb_failed
, sd
->alb_pushed
,
468 sd
->sbe_cnt
, sd
->sbe_balanced
, sd
->sbe_pushed
,
469 sd
->sbf_cnt
, sd
->sbf_balanced
, sd
->sbf_pushed
,
470 sd
->ttwu_wake_remote
, sd
->ttwu_move_affine
, sd
->ttwu_move_balance
);
478 static int schedstat_open(struct inode
*inode
, struct file
*file
)
480 unsigned int size
= PAGE_SIZE
* (1 + num_online_cpus() / 32);
481 char *buf
= kmalloc(size
, GFP_KERNEL
);
487 res
= single_open(file
, show_schedstat
, NULL
);
489 m
= file
->private_data
;
497 struct file_operations proc_schedstat_operations
= {
498 .open
= schedstat_open
,
501 .release
= single_release
,
504 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
505 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
506 #else /* !CONFIG_SCHEDSTATS */
507 # define schedstat_inc(rq, field) do { } while (0)
508 # define schedstat_add(rq, field, amt) do { } while (0)
512 * rq_lock - lock a given runqueue and disable interrupts.
514 static inline struct rq
*this_rq_lock(void)
521 spin_lock(&rq
->lock
);
526 #ifdef CONFIG_SCHEDSTATS
528 * Called when a process is dequeued from the active array and given
529 * the cpu. We should note that with the exception of interactive
530 * tasks, the expired queue will become the active queue after the active
531 * queue is empty, without explicitly dequeuing and requeuing tasks in the
532 * expired queue. (Interactive tasks may be requeued directly to the
533 * active queue, thus delaying tasks in the expired queue from running;
534 * see scheduler_tick()).
536 * This function is only called from sched_info_arrive(), rather than
537 * dequeue_task(). Even though a task may be queued and dequeued multiple
538 * times as it is shuffled about, we're really interested in knowing how
539 * long it was from the *first* time it was queued to the time that it
542 static inline void sched_info_dequeued(struct task_struct
*t
)
544 t
->sched_info
.last_queued
= 0;
548 * Called when a task finally hits the cpu. We can now calculate how
549 * long it was waiting to run. We also note when it began so that we
550 * can keep stats on how long its timeslice is.
552 static void sched_info_arrive(struct task_struct
*t
)
554 unsigned long now
= jiffies
, diff
= 0;
555 struct rq
*rq
= task_rq(t
);
557 if (t
->sched_info
.last_queued
)
558 diff
= now
- t
->sched_info
.last_queued
;
559 sched_info_dequeued(t
);
560 t
->sched_info
.run_delay
+= diff
;
561 t
->sched_info
.last_arrival
= now
;
562 t
->sched_info
.pcnt
++;
567 rq
->rq_sched_info
.run_delay
+= diff
;
568 rq
->rq_sched_info
.pcnt
++;
572 * Called when a process is queued into either the active or expired
573 * array. The time is noted and later used to determine how long we
574 * had to wait for us to reach the cpu. Since the expired queue will
575 * become the active queue after active queue is empty, without dequeuing
576 * and requeuing any tasks, we are interested in queuing to either. It
577 * is unusual but not impossible for tasks to be dequeued and immediately
578 * requeued in the same or another array: this can happen in sched_yield(),
579 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
582 * This function is only called from enqueue_task(), but also only updates
583 * the timestamp if it is already not set. It's assumed that
584 * sched_info_dequeued() will clear that stamp when appropriate.
586 static inline void sched_info_queued(struct task_struct
*t
)
588 if (!t
->sched_info
.last_queued
)
589 t
->sched_info
.last_queued
= jiffies
;
593 * Called when a process ceases being the active-running process, either
594 * voluntarily or involuntarily. Now we can calculate how long we ran.
596 static inline void sched_info_depart(struct task_struct
*t
)
598 struct rq
*rq
= task_rq(t
);
599 unsigned long diff
= jiffies
- t
->sched_info
.last_arrival
;
601 t
->sched_info
.cpu_time
+= diff
;
604 rq
->rq_sched_info
.cpu_time
+= diff
;
608 * Called when tasks are switched involuntarily due, typically, to expiring
609 * their time slice. (This may also be called when switching to or from
610 * the idle task.) We are only called when prev != next.
613 sched_info_switch(struct task_struct
*prev
, struct task_struct
*next
)
615 struct rq
*rq
= task_rq(prev
);
618 * prev now departs the cpu. It's not interesting to record
619 * stats about how efficient we were at scheduling the idle
622 if (prev
!= rq
->idle
)
623 sched_info_depart(prev
);
625 if (next
!= rq
->idle
)
626 sched_info_arrive(next
);
629 #define sched_info_queued(t) do { } while (0)
630 #define sched_info_switch(t, next) do { } while (0)
631 #endif /* CONFIG_SCHEDSTATS */
634 * Adding/removing a task to/from a priority array:
636 static void dequeue_task(struct task_struct
*p
, struct prio_array
*array
)
639 list_del(&p
->run_list
);
640 if (list_empty(array
->queue
+ p
->prio
))
641 __clear_bit(p
->prio
, array
->bitmap
);
644 static void enqueue_task(struct task_struct
*p
, struct prio_array
*array
)
646 sched_info_queued(p
);
647 list_add_tail(&p
->run_list
, array
->queue
+ p
->prio
);
648 __set_bit(p
->prio
, array
->bitmap
);
654 * Put task to the end of the run list without the overhead of dequeue
655 * followed by enqueue.
657 static void requeue_task(struct task_struct
*p
, struct prio_array
*array
)
659 list_move_tail(&p
->run_list
, array
->queue
+ p
->prio
);
663 enqueue_task_head(struct task_struct
*p
, struct prio_array
*array
)
665 list_add(&p
->run_list
, array
->queue
+ p
->prio
);
666 __set_bit(p
->prio
, array
->bitmap
);
672 * __normal_prio - return the priority that is based on the static
673 * priority but is modified by bonuses/penalties.
675 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
676 * into the -5 ... 0 ... +5 bonus/penalty range.
678 * We use 25% of the full 0...39 priority range so that:
680 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
681 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
683 * Both properties are important to certain workloads.
686 static inline int __normal_prio(struct task_struct
*p
)
690 bonus
= CURRENT_BONUS(p
) - MAX_BONUS
/ 2;
692 prio
= p
->static_prio
- bonus
;
693 if (prio
< MAX_RT_PRIO
)
695 if (prio
> MAX_PRIO
-1)
701 * To aid in avoiding the subversion of "niceness" due to uneven distribution
702 * of tasks with abnormal "nice" values across CPUs the contribution that
703 * each task makes to its run queue's load is weighted according to its
704 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
705 * scaled version of the new time slice allocation that they receive on time
710 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
711 * If static_prio_timeslice() is ever changed to break this assumption then
712 * this code will need modification
714 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
715 #define LOAD_WEIGHT(lp) \
716 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
717 #define PRIO_TO_LOAD_WEIGHT(prio) \
718 LOAD_WEIGHT(static_prio_timeslice(prio))
719 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
720 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
722 static void set_load_weight(struct task_struct
*p
)
724 if (has_rt_policy(p
)) {
726 if (p
== task_rq(p
)->migration_thread
)
728 * The migration thread does the actual balancing.
729 * Giving its load any weight will skew balancing
735 p
->load_weight
= RTPRIO_TO_LOAD_WEIGHT(p
->rt_priority
);
737 p
->load_weight
= PRIO_TO_LOAD_WEIGHT(p
->static_prio
);
741 inc_raw_weighted_load(struct rq
*rq
, const struct task_struct
*p
)
743 rq
->raw_weighted_load
+= p
->load_weight
;
747 dec_raw_weighted_load(struct rq
*rq
, const struct task_struct
*p
)
749 rq
->raw_weighted_load
-= p
->load_weight
;
752 static inline void inc_nr_running(struct task_struct
*p
, struct rq
*rq
)
755 inc_raw_weighted_load(rq
, p
);
758 static inline void dec_nr_running(struct task_struct
*p
, struct rq
*rq
)
761 dec_raw_weighted_load(rq
, p
);
765 * Calculate the expected normal priority: i.e. priority
766 * without taking RT-inheritance into account. Might be
767 * boosted by interactivity modifiers. Changes upon fork,
768 * setprio syscalls, and whenever the interactivity
769 * estimator recalculates.
771 static inline int normal_prio(struct task_struct
*p
)
775 if (has_rt_policy(p
))
776 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
778 prio
= __normal_prio(p
);
783 * Calculate the current priority, i.e. the priority
784 * taken into account by the scheduler. This value might
785 * be boosted by RT tasks, or might be boosted by
786 * interactivity modifiers. Will be RT if the task got
787 * RT-boosted. If not then it returns p->normal_prio.
789 static int effective_prio(struct task_struct
*p
)
791 p
->normal_prio
= normal_prio(p
);
793 * If we are RT tasks or we were boosted to RT priority,
794 * keep the priority unchanged. Otherwise, update priority
795 * to the normal priority:
797 if (!rt_prio(p
->prio
))
798 return p
->normal_prio
;
803 * __activate_task - move a task to the runqueue.
805 static void __activate_task(struct task_struct
*p
, struct rq
*rq
)
807 struct prio_array
*target
= rq
->active
;
810 target
= rq
->expired
;
811 enqueue_task(p
, target
);
812 inc_nr_running(p
, rq
);
816 * __activate_idle_task - move idle task to the _front_ of runqueue.
818 static inline void __activate_idle_task(struct task_struct
*p
, struct rq
*rq
)
820 enqueue_task_head(p
, rq
->active
);
821 inc_nr_running(p
, rq
);
825 * Recalculate p->normal_prio and p->prio after having slept,
826 * updating the sleep-average too:
828 static int recalc_task_prio(struct task_struct
*p
, unsigned long long now
)
830 /* Caller must always ensure 'now >= p->timestamp' */
831 unsigned long sleep_time
= now
- p
->timestamp
;
836 if (likely(sleep_time
> 0)) {
838 * This ceiling is set to the lowest priority that would allow
839 * a task to be reinserted into the active array on timeslice
842 unsigned long ceiling
= INTERACTIVE_SLEEP(p
);
844 if (p
->mm
&& sleep_time
> ceiling
&& p
->sleep_avg
< ceiling
) {
846 * Prevents user tasks from achieving best priority
847 * with one single large enough sleep.
849 p
->sleep_avg
= ceiling
;
851 * Using INTERACTIVE_SLEEP() as a ceiling places a
852 * nice(0) task 1ms sleep away from promotion, and
853 * gives it 700ms to round-robin with no chance of
854 * being demoted. This is more than generous, so
855 * mark this sleep as non-interactive to prevent the
856 * on-runqueue bonus logic from intervening should
857 * this task not receive cpu immediately.
859 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
862 * Tasks waking from uninterruptible sleep are
863 * limited in their sleep_avg rise as they
864 * are likely to be waiting on I/O
866 if (p
->sleep_type
== SLEEP_NONINTERACTIVE
&& p
->mm
) {
867 if (p
->sleep_avg
>= ceiling
)
869 else if (p
->sleep_avg
+ sleep_time
>=
871 p
->sleep_avg
= ceiling
;
877 * This code gives a bonus to interactive tasks.
879 * The boost works by updating the 'average sleep time'
880 * value here, based on ->timestamp. The more time a
881 * task spends sleeping, the higher the average gets -
882 * and the higher the priority boost gets as well.
884 p
->sleep_avg
+= sleep_time
;
887 if (p
->sleep_avg
> NS_MAX_SLEEP_AVG
)
888 p
->sleep_avg
= NS_MAX_SLEEP_AVG
;
891 return effective_prio(p
);
895 * activate_task - move a task to the runqueue and do priority recalculation
897 * Update all the scheduling statistics stuff. (sleep average
898 * calculation, priority modifiers, etc.)
900 static void activate_task(struct task_struct
*p
, struct rq
*rq
, int local
)
902 unsigned long long now
;
907 /* Compensate for drifting sched_clock */
908 struct rq
*this_rq
= this_rq();
909 now
= (now
- this_rq
->timestamp_last_tick
)
910 + rq
->timestamp_last_tick
;
915 p
->prio
= recalc_task_prio(p
, now
);
918 * This checks to make sure it's not an uninterruptible task
919 * that is now waking up.
921 if (p
->sleep_type
== SLEEP_NORMAL
) {
923 * Tasks which were woken up by interrupts (ie. hw events)
924 * are most likely of interactive nature. So we give them
925 * the credit of extending their sleep time to the period
926 * of time they spend on the runqueue, waiting for execution
927 * on a CPU, first time around:
930 p
->sleep_type
= SLEEP_INTERRUPTED
;
933 * Normal first-time wakeups get a credit too for
934 * on-runqueue time, but it will be weighted down:
936 p
->sleep_type
= SLEEP_INTERACTIVE
;
941 __activate_task(p
, rq
);
945 * deactivate_task - remove a task from the runqueue.
947 static void deactivate_task(struct task_struct
*p
, struct rq
*rq
)
949 dec_nr_running(p
, rq
);
950 dequeue_task(p
, p
->array
);
955 * resched_task - mark a task 'to be rescheduled now'.
957 * On UP this means the setting of the need_resched flag, on SMP it
958 * might also involve a cross-CPU call to trigger the scheduler on
963 #ifndef tsk_is_polling
964 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
967 static void resched_task(struct task_struct
*p
)
971 assert_spin_locked(&task_rq(p
)->lock
);
973 if (unlikely(test_tsk_thread_flag(p
, TIF_NEED_RESCHED
)))
976 set_tsk_thread_flag(p
, TIF_NEED_RESCHED
);
979 if (cpu
== smp_processor_id())
982 /* NEED_RESCHED must be visible before we test polling */
984 if (!tsk_is_polling(p
))
985 smp_send_reschedule(cpu
);
988 static inline void resched_task(struct task_struct
*p
)
990 assert_spin_locked(&task_rq(p
)->lock
);
991 set_tsk_need_resched(p
);
996 * task_curr - is this task currently executing on a CPU?
997 * @p: the task in question.
999 inline int task_curr(const struct task_struct
*p
)
1001 return cpu_curr(task_cpu(p
)) == p
;
1004 /* Used instead of source_load when we know the type == 0 */
1005 unsigned long weighted_cpuload(const int cpu
)
1007 return cpu_rq(cpu
)->raw_weighted_load
;
1011 struct migration_req
{
1012 struct list_head list
;
1014 struct task_struct
*task
;
1017 struct completion done
;
1021 * The task's runqueue lock must be held.
1022 * Returns true if you have to wait for migration thread.
1025 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1027 struct rq
*rq
= task_rq(p
);
1030 * If the task is not on a runqueue (and not running), then
1031 * it is sufficient to simply update the task's cpu field.
1033 if (!p
->array
&& !task_running(rq
, p
)) {
1034 set_task_cpu(p
, dest_cpu
);
1038 init_completion(&req
->done
);
1040 req
->dest_cpu
= dest_cpu
;
1041 list_add(&req
->list
, &rq
->migration_queue
);
1047 * wait_task_inactive - wait for a thread to unschedule.
1049 * The caller must ensure that the task *will* unschedule sometime soon,
1050 * else this function might spin for a *long* time. This function can't
1051 * be called with interrupts off, or it may introduce deadlock with
1052 * smp_call_function() if an IPI is sent by the same process we are
1053 * waiting to become inactive.
1055 void wait_task_inactive(struct task_struct
*p
)
1057 unsigned long flags
;
1062 rq
= task_rq_lock(p
, &flags
);
1063 /* Must be off runqueue entirely, not preempted. */
1064 if (unlikely(p
->array
|| task_running(rq
, p
))) {
1065 /* If it's preempted, we yield. It could be a while. */
1066 preempted
= !task_running(rq
, p
);
1067 task_rq_unlock(rq
, &flags
);
1073 task_rq_unlock(rq
, &flags
);
1077 * kick_process - kick a running thread to enter/exit the kernel
1078 * @p: the to-be-kicked thread
1080 * Cause a process which is running on another CPU to enter
1081 * kernel-mode, without any delay. (to get signals handled.)
1083 * NOTE: this function doesnt have to take the runqueue lock,
1084 * because all it wants to ensure is that the remote task enters
1085 * the kernel. If the IPI races and the task has been migrated
1086 * to another CPU then no harm is done and the purpose has been
1089 void kick_process(struct task_struct
*p
)
1095 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1096 smp_send_reschedule(cpu
);
1101 * Return a low guess at the load of a migration-source cpu weighted
1102 * according to the scheduling class and "nice" value.
1104 * We want to under-estimate the load of migration sources, to
1105 * balance conservatively.
1107 static inline unsigned long source_load(int cpu
, int type
)
1109 struct rq
*rq
= cpu_rq(cpu
);
1112 return rq
->raw_weighted_load
;
1114 return min(rq
->cpu_load
[type
-1], rq
->raw_weighted_load
);
1118 * Return a high guess at the load of a migration-target cpu weighted
1119 * according to the scheduling class and "nice" value.
1121 static inline unsigned long target_load(int cpu
, int type
)
1123 struct rq
*rq
= cpu_rq(cpu
);
1126 return rq
->raw_weighted_load
;
1128 return max(rq
->cpu_load
[type
-1], rq
->raw_weighted_load
);
1132 * Return the average load per task on the cpu's run queue
1134 static inline unsigned long cpu_avg_load_per_task(int cpu
)
1136 struct rq
*rq
= cpu_rq(cpu
);
1137 unsigned long n
= rq
->nr_running
;
1139 return n
? rq
->raw_weighted_load
/ n
: SCHED_LOAD_SCALE
;
1143 * find_idlest_group finds and returns the least busy CPU group within the
1146 static struct sched_group
*
1147 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1149 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1150 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1151 int load_idx
= sd
->forkexec_idx
;
1152 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1155 unsigned long load
, avg_load
;
1159 /* Skip over this group if it has no CPUs allowed */
1160 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1163 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1165 /* Tally up the load of all CPUs in the group */
1168 for_each_cpu_mask(i
, group
->cpumask
) {
1169 /* Bias balancing toward cpus of our domain */
1171 load
= source_load(i
, load_idx
);
1173 load
= target_load(i
, load_idx
);
1178 /* Adjust by relative CPU power of the group */
1179 avg_load
= (avg_load
* SCHED_LOAD_SCALE
) / group
->cpu_power
;
1182 this_load
= avg_load
;
1184 } else if (avg_load
< min_load
) {
1185 min_load
= avg_load
;
1189 group
= group
->next
;
1190 } while (group
!= sd
->groups
);
1192 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1198 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1201 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1204 unsigned long load
, min_load
= ULONG_MAX
;
1208 /* Traverse only the allowed CPUs */
1209 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1211 for_each_cpu_mask(i
, tmp
) {
1212 load
= weighted_cpuload(i
);
1214 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1224 * sched_balance_self: balance the current task (running on cpu) in domains
1225 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1228 * Balance, ie. select the least loaded group.
1230 * Returns the target CPU number, or the same CPU if no balancing is needed.
1232 * preempt must be disabled.
1234 static int sched_balance_self(int cpu
, int flag
)
1236 struct task_struct
*t
= current
;
1237 struct sched_domain
*tmp
, *sd
= NULL
;
1239 for_each_domain(cpu
, tmp
) {
1241 * If power savings logic is enabled for a domain, stop there.
1243 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1245 if (tmp
->flags
& flag
)
1251 struct sched_group
*group
;
1256 group
= find_idlest_group(sd
, t
, cpu
);
1260 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1261 if (new_cpu
== -1 || new_cpu
== cpu
)
1264 /* Now try balancing at a lower domain level */
1268 weight
= cpus_weight(span
);
1269 for_each_domain(cpu
, tmp
) {
1270 if (weight
<= cpus_weight(tmp
->span
))
1272 if (tmp
->flags
& flag
)
1275 /* while loop will break here if sd == NULL */
1281 #endif /* CONFIG_SMP */
1284 * wake_idle() will wake a task on an idle cpu if task->cpu is
1285 * not idle and an idle cpu is available. The span of cpus to
1286 * search starts with cpus closest then further out as needed,
1287 * so we always favor a closer, idle cpu.
1289 * Returns the CPU we should wake onto.
1291 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1292 static int wake_idle(int cpu
, struct task_struct
*p
)
1295 struct sched_domain
*sd
;
1301 for_each_domain(cpu
, sd
) {
1302 if (sd
->flags
& SD_WAKE_IDLE
) {
1303 cpus_and(tmp
, sd
->span
, p
->cpus_allowed
);
1304 for_each_cpu_mask(i
, tmp
) {
1315 static inline int wake_idle(int cpu
, struct task_struct
*p
)
1322 * try_to_wake_up - wake up a thread
1323 * @p: the to-be-woken-up thread
1324 * @state: the mask of task states that can be woken
1325 * @sync: do a synchronous wakeup?
1327 * Put it on the run-queue if it's not already there. The "current"
1328 * thread is always on the run-queue (except when the actual
1329 * re-schedule is in progress), and as such you're allowed to do
1330 * the simpler "current->state = TASK_RUNNING" to mark yourself
1331 * runnable without the overhead of this.
1333 * returns failure only if the task is already active.
1335 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1337 int cpu
, this_cpu
, success
= 0;
1338 unsigned long flags
;
1342 struct sched_domain
*sd
, *this_sd
= NULL
;
1343 unsigned long load
, this_load
;
1347 rq
= task_rq_lock(p
, &flags
);
1348 old_state
= p
->state
;
1349 if (!(old_state
& state
))
1356 this_cpu
= smp_processor_id();
1359 if (unlikely(task_running(rq
, p
)))
1364 schedstat_inc(rq
, ttwu_cnt
);
1365 if (cpu
== this_cpu
) {
1366 schedstat_inc(rq
, ttwu_local
);
1370 for_each_domain(this_cpu
, sd
) {
1371 if (cpu_isset(cpu
, sd
->span
)) {
1372 schedstat_inc(sd
, ttwu_wake_remote
);
1378 if (unlikely(!cpu_isset(this_cpu
, p
->cpus_allowed
)))
1382 * Check for affine wakeup and passive balancing possibilities.
1385 int idx
= this_sd
->wake_idx
;
1386 unsigned int imbalance
;
1388 imbalance
= 100 + (this_sd
->imbalance_pct
- 100) / 2;
1390 load
= source_load(cpu
, idx
);
1391 this_load
= target_load(this_cpu
, idx
);
1393 new_cpu
= this_cpu
; /* Wake to this CPU if we can */
1395 if (this_sd
->flags
& SD_WAKE_AFFINE
) {
1396 unsigned long tl
= this_load
;
1397 unsigned long tl_per_task
= cpu_avg_load_per_task(this_cpu
);
1400 * If sync wakeup then subtract the (maximum possible)
1401 * effect of the currently running task from the load
1402 * of the current CPU:
1405 tl
-= current
->load_weight
;
1408 tl
+ target_load(cpu
, idx
) <= tl_per_task
) ||
1409 100*(tl
+ p
->load_weight
) <= imbalance
*load
) {
1411 * This domain has SD_WAKE_AFFINE and
1412 * p is cache cold in this domain, and
1413 * there is no bad imbalance.
1415 schedstat_inc(this_sd
, ttwu_move_affine
);
1421 * Start passive balancing when half the imbalance_pct
1424 if (this_sd
->flags
& SD_WAKE_BALANCE
) {
1425 if (imbalance
*this_load
<= 100*load
) {
1426 schedstat_inc(this_sd
, ttwu_move_balance
);
1432 new_cpu
= cpu
; /* Could not wake to this_cpu. Wake to cpu instead */
1434 new_cpu
= wake_idle(new_cpu
, p
);
1435 if (new_cpu
!= cpu
) {
1436 set_task_cpu(p
, new_cpu
);
1437 task_rq_unlock(rq
, &flags
);
1438 /* might preempt at this point */
1439 rq
= task_rq_lock(p
, &flags
);
1440 old_state
= p
->state
;
1441 if (!(old_state
& state
))
1446 this_cpu
= smp_processor_id();
1451 #endif /* CONFIG_SMP */
1452 if (old_state
== TASK_UNINTERRUPTIBLE
) {
1453 rq
->nr_uninterruptible
--;
1455 * Tasks on involuntary sleep don't earn
1456 * sleep_avg beyond just interactive state.
1458 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
1462 * Tasks that have marked their sleep as noninteractive get
1463 * woken up with their sleep average not weighted in an
1466 if (old_state
& TASK_NONINTERACTIVE
)
1467 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
1470 activate_task(p
, rq
, cpu
== this_cpu
);
1472 * Sync wakeups (i.e. those types of wakeups where the waker
1473 * has indicated that it will leave the CPU in short order)
1474 * don't trigger a preemption, if the woken up task will run on
1475 * this cpu. (in this case the 'I will reschedule' promise of
1476 * the waker guarantees that the freshly woken up task is going
1477 * to be considered on this CPU.)
1479 if (!sync
|| cpu
!= this_cpu
) {
1480 if (TASK_PREEMPTS_CURR(p
, rq
))
1481 resched_task(rq
->curr
);
1486 p
->state
= TASK_RUNNING
;
1488 task_rq_unlock(rq
, &flags
);
1493 int fastcall
wake_up_process(struct task_struct
*p
)
1495 return try_to_wake_up(p
, TASK_STOPPED
| TASK_TRACED
|
1496 TASK_INTERRUPTIBLE
| TASK_UNINTERRUPTIBLE
, 0);
1498 EXPORT_SYMBOL(wake_up_process
);
1500 int fastcall
wake_up_state(struct task_struct
*p
, unsigned int state
)
1502 return try_to_wake_up(p
, state
, 0);
1506 * Perform scheduler related setup for a newly forked process p.
1507 * p is forked by current.
1509 void fastcall
sched_fork(struct task_struct
*p
, int clone_flags
)
1511 int cpu
= get_cpu();
1514 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
1516 set_task_cpu(p
, cpu
);
1519 * We mark the process as running here, but have not actually
1520 * inserted it onto the runqueue yet. This guarantees that
1521 * nobody will actually run it, and a signal or other external
1522 * event cannot wake it up and insert it on the runqueue either.
1524 p
->state
= TASK_RUNNING
;
1527 * Make sure we do not leak PI boosting priority to the child:
1529 p
->prio
= current
->normal_prio
;
1531 INIT_LIST_HEAD(&p
->run_list
);
1533 #ifdef CONFIG_SCHEDSTATS
1534 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1536 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1539 #ifdef CONFIG_PREEMPT
1540 /* Want to start with kernel preemption disabled. */
1541 task_thread_info(p
)->preempt_count
= 1;
1544 * Share the timeslice between parent and child, thus the
1545 * total amount of pending timeslices in the system doesn't change,
1546 * resulting in more scheduling fairness.
1548 local_irq_disable();
1549 p
->time_slice
= (current
->time_slice
+ 1) >> 1;
1551 * The remainder of the first timeslice might be recovered by
1552 * the parent if the child exits early enough.
1554 p
->first_time_slice
= 1;
1555 current
->time_slice
>>= 1;
1556 p
->timestamp
= sched_clock();
1557 if (unlikely(!current
->time_slice
)) {
1559 * This case is rare, it happens when the parent has only
1560 * a single jiffy left from its timeslice. Taking the
1561 * runqueue lock is not a problem.
1563 current
->time_slice
= 1;
1571 * wake_up_new_task - wake up a newly created task for the first time.
1573 * This function will do some initial scheduler statistics housekeeping
1574 * that must be done for every newly created context, then puts the task
1575 * on the runqueue and wakes it.
1577 void fastcall
wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
1579 struct rq
*rq
, *this_rq
;
1580 unsigned long flags
;
1583 rq
= task_rq_lock(p
, &flags
);
1584 BUG_ON(p
->state
!= TASK_RUNNING
);
1585 this_cpu
= smp_processor_id();
1589 * We decrease the sleep average of forking parents
1590 * and children as well, to keep max-interactive tasks
1591 * from forking tasks that are max-interactive. The parent
1592 * (current) is done further down, under its lock.
1594 p
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(p
) *
1595 CHILD_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1597 p
->prio
= effective_prio(p
);
1599 if (likely(cpu
== this_cpu
)) {
1600 if (!(clone_flags
& CLONE_VM
)) {
1602 * The VM isn't cloned, so we're in a good position to
1603 * do child-runs-first in anticipation of an exec. This
1604 * usually avoids a lot of COW overhead.
1606 if (unlikely(!current
->array
))
1607 __activate_task(p
, rq
);
1609 p
->prio
= current
->prio
;
1610 p
->normal_prio
= current
->normal_prio
;
1611 list_add_tail(&p
->run_list
, ¤t
->run_list
);
1612 p
->array
= current
->array
;
1613 p
->array
->nr_active
++;
1614 inc_nr_running(p
, rq
);
1618 /* Run child last */
1619 __activate_task(p
, rq
);
1621 * We skip the following code due to cpu == this_cpu
1623 * task_rq_unlock(rq, &flags);
1624 * this_rq = task_rq_lock(current, &flags);
1628 this_rq
= cpu_rq(this_cpu
);
1631 * Not the local CPU - must adjust timestamp. This should
1632 * get optimised away in the !CONFIG_SMP case.
1634 p
->timestamp
= (p
->timestamp
- this_rq
->timestamp_last_tick
)
1635 + rq
->timestamp_last_tick
;
1636 __activate_task(p
, rq
);
1637 if (TASK_PREEMPTS_CURR(p
, rq
))
1638 resched_task(rq
->curr
);
1641 * Parent and child are on different CPUs, now get the
1642 * parent runqueue to update the parent's ->sleep_avg:
1644 task_rq_unlock(rq
, &flags
);
1645 this_rq
= task_rq_lock(current
, &flags
);
1647 current
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(current
) *
1648 PARENT_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1649 task_rq_unlock(this_rq
, &flags
);
1653 * Potentially available exiting-child timeslices are
1654 * retrieved here - this way the parent does not get
1655 * penalized for creating too many threads.
1657 * (this cannot be used to 'generate' timeslices
1658 * artificially, because any timeslice recovered here
1659 * was given away by the parent in the first place.)
1661 void fastcall
sched_exit(struct task_struct
*p
)
1663 unsigned long flags
;
1667 * If the child was a (relative-) CPU hog then decrease
1668 * the sleep_avg of the parent as well.
1670 rq
= task_rq_lock(p
->parent
, &flags
);
1671 if (p
->first_time_slice
&& task_cpu(p
) == task_cpu(p
->parent
)) {
1672 p
->parent
->time_slice
+= p
->time_slice
;
1673 if (unlikely(p
->parent
->time_slice
> task_timeslice(p
)))
1674 p
->parent
->time_slice
= task_timeslice(p
);
1676 if (p
->sleep_avg
< p
->parent
->sleep_avg
)
1677 p
->parent
->sleep_avg
= p
->parent
->sleep_avg
/
1678 (EXIT_WEIGHT
+ 1) * EXIT_WEIGHT
+ p
->sleep_avg
/
1680 task_rq_unlock(rq
, &flags
);
1684 * prepare_task_switch - prepare to switch tasks
1685 * @rq: the runqueue preparing to switch
1686 * @next: the task we are going to switch to.
1688 * This is called with the rq lock held and interrupts off. It must
1689 * be paired with a subsequent finish_task_switch after the context
1692 * prepare_task_switch sets up locking and calls architecture specific
1695 static inline void prepare_task_switch(struct rq
*rq
, struct task_struct
*next
)
1697 prepare_lock_switch(rq
, next
);
1698 prepare_arch_switch(next
);
1702 * finish_task_switch - clean up after a task-switch
1703 * @rq: runqueue associated with task-switch
1704 * @prev: the thread we just switched away from.
1706 * finish_task_switch must be called after the context switch, paired
1707 * with a prepare_task_switch call before the context switch.
1708 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1709 * and do any other architecture-specific cleanup actions.
1711 * Note that we may have delayed dropping an mm in context_switch(). If
1712 * so, we finish that here outside of the runqueue lock. (Doing it
1713 * with the lock held can cause deadlocks; see schedule() for
1716 static inline void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
1717 __releases(rq
->lock
)
1719 struct mm_struct
*mm
= rq
->prev_mm
;
1720 unsigned long prev_task_flags
;
1725 * A task struct has one reference for the use as "current".
1726 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1727 * calls schedule one last time. The schedule call will never return,
1728 * and the scheduled task must drop that reference.
1729 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1730 * still held, otherwise prev could be scheduled on another cpu, die
1731 * there before we look at prev->state, and then the reference would
1733 * Manfred Spraul <manfred@colorfullife.com>
1735 prev_task_flags
= prev
->flags
;
1736 finish_arch_switch(prev
);
1737 finish_lock_switch(rq
, prev
);
1740 if (unlikely(prev_task_flags
& PF_DEAD
)) {
1742 * Remove function-return probe instances associated with this
1743 * task and put them back on the free list.
1745 kprobe_flush_task(prev
);
1746 put_task_struct(prev
);
1751 * schedule_tail - first thing a freshly forked thread must call.
1752 * @prev: the thread we just switched away from.
1754 asmlinkage
void schedule_tail(struct task_struct
*prev
)
1755 __releases(rq
->lock
)
1757 struct rq
*rq
= this_rq();
1759 finish_task_switch(rq
, prev
);
1760 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1761 /* In this case, finish_task_switch does not reenable preemption */
1764 if (current
->set_child_tid
)
1765 put_user(current
->pid
, current
->set_child_tid
);
1769 * context_switch - switch to the new MM and the new
1770 * thread's register state.
1772 static inline struct task_struct
*
1773 context_switch(struct rq
*rq
, struct task_struct
*prev
,
1774 struct task_struct
*next
)
1776 struct mm_struct
*mm
= next
->mm
;
1777 struct mm_struct
*oldmm
= prev
->active_mm
;
1779 if (unlikely(!mm
)) {
1780 next
->active_mm
= oldmm
;
1781 atomic_inc(&oldmm
->mm_count
);
1782 enter_lazy_tlb(oldmm
, next
);
1784 switch_mm(oldmm
, mm
, next
);
1786 if (unlikely(!prev
->mm
)) {
1787 prev
->active_mm
= NULL
;
1788 WARN_ON(rq
->prev_mm
);
1789 rq
->prev_mm
= oldmm
;
1791 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
1793 /* Here we just switch the register state and the stack. */
1794 switch_to(prev
, next
, prev
);
1800 * nr_running, nr_uninterruptible and nr_context_switches:
1802 * externally visible scheduler statistics: current number of runnable
1803 * threads, current number of uninterruptible-sleeping threads, total
1804 * number of context switches performed since bootup.
1806 unsigned long nr_running(void)
1808 unsigned long i
, sum
= 0;
1810 for_each_online_cpu(i
)
1811 sum
+= cpu_rq(i
)->nr_running
;
1816 unsigned long nr_uninterruptible(void)
1818 unsigned long i
, sum
= 0;
1820 for_each_possible_cpu(i
)
1821 sum
+= cpu_rq(i
)->nr_uninterruptible
;
1824 * Since we read the counters lockless, it might be slightly
1825 * inaccurate. Do not allow it to go below zero though:
1827 if (unlikely((long)sum
< 0))
1833 unsigned long long nr_context_switches(void)
1836 unsigned long long sum
= 0;
1838 for_each_possible_cpu(i
)
1839 sum
+= cpu_rq(i
)->nr_switches
;
1844 unsigned long nr_iowait(void)
1846 unsigned long i
, sum
= 0;
1848 for_each_possible_cpu(i
)
1849 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
1854 unsigned long nr_active(void)
1856 unsigned long i
, running
= 0, uninterruptible
= 0;
1858 for_each_online_cpu(i
) {
1859 running
+= cpu_rq(i
)->nr_running
;
1860 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
1863 if (unlikely((long)uninterruptible
< 0))
1864 uninterruptible
= 0;
1866 return running
+ uninterruptible
;
1872 * Is this task likely cache-hot:
1875 task_hot(struct task_struct
*p
, unsigned long long now
, struct sched_domain
*sd
)
1877 return (long long)(now
- p
->last_ran
) < (long long)sd
->cache_hot_time
;
1881 * double_rq_lock - safely lock two runqueues
1883 * Note this does not disable interrupts like task_rq_lock,
1884 * you need to do so manually before calling.
1886 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
1887 __acquires(rq1
->lock
)
1888 __acquires(rq2
->lock
)
1891 spin_lock(&rq1
->lock
);
1892 __acquire(rq2
->lock
); /* Fake it out ;) */
1895 spin_lock(&rq1
->lock
);
1896 spin_lock(&rq2
->lock
);
1898 spin_lock(&rq2
->lock
);
1899 spin_lock(&rq1
->lock
);
1905 * double_rq_unlock - safely unlock two runqueues
1907 * Note this does not restore interrupts like task_rq_unlock,
1908 * you need to do so manually after calling.
1910 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
1911 __releases(rq1
->lock
)
1912 __releases(rq2
->lock
)
1914 spin_unlock(&rq1
->lock
);
1916 spin_unlock(&rq2
->lock
);
1918 __release(rq2
->lock
);
1922 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1924 static void double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
1925 __releases(this_rq
->lock
)
1926 __acquires(busiest
->lock
)
1927 __acquires(this_rq
->lock
)
1929 if (unlikely(!spin_trylock(&busiest
->lock
))) {
1930 if (busiest
< this_rq
) {
1931 spin_unlock(&this_rq
->lock
);
1932 spin_lock(&busiest
->lock
);
1933 spin_lock(&this_rq
->lock
);
1935 spin_lock(&busiest
->lock
);
1940 * If dest_cpu is allowed for this process, migrate the task to it.
1941 * This is accomplished by forcing the cpu_allowed mask to only
1942 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1943 * the cpu_allowed mask is restored.
1945 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
1947 struct migration_req req
;
1948 unsigned long flags
;
1951 rq
= task_rq_lock(p
, &flags
);
1952 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
1953 || unlikely(cpu_is_offline(dest_cpu
)))
1956 /* force the process onto the specified CPU */
1957 if (migrate_task(p
, dest_cpu
, &req
)) {
1958 /* Need to wait for migration thread (might exit: take ref). */
1959 struct task_struct
*mt
= rq
->migration_thread
;
1961 get_task_struct(mt
);
1962 task_rq_unlock(rq
, &flags
);
1963 wake_up_process(mt
);
1964 put_task_struct(mt
);
1965 wait_for_completion(&req
.done
);
1970 task_rq_unlock(rq
, &flags
);
1974 * sched_exec - execve() is a valuable balancing opportunity, because at
1975 * this point the task has the smallest effective memory and cache footprint.
1977 void sched_exec(void)
1979 int new_cpu
, this_cpu
= get_cpu();
1980 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
1982 if (new_cpu
!= this_cpu
)
1983 sched_migrate_task(current
, new_cpu
);
1987 * pull_task - move a task from a remote runqueue to the local runqueue.
1988 * Both runqueues must be locked.
1990 static void pull_task(struct rq
*src_rq
, struct prio_array
*src_array
,
1991 struct task_struct
*p
, struct rq
*this_rq
,
1992 struct prio_array
*this_array
, int this_cpu
)
1994 dequeue_task(p
, src_array
);
1995 dec_nr_running(p
, src_rq
);
1996 set_task_cpu(p
, this_cpu
);
1997 inc_nr_running(p
, this_rq
);
1998 enqueue_task(p
, this_array
);
1999 p
->timestamp
= (p
->timestamp
- src_rq
->timestamp_last_tick
)
2000 + this_rq
->timestamp_last_tick
;
2002 * Note that idle threads have a prio of MAX_PRIO, for this test
2003 * to be always true for them.
2005 if (TASK_PREEMPTS_CURR(p
, this_rq
))
2006 resched_task(this_rq
->curr
);
2010 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2013 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2014 struct sched_domain
*sd
, enum idle_type idle
,
2018 * We do not migrate tasks that are:
2019 * 1) running (obviously), or
2020 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2021 * 3) are cache-hot on their current CPU.
2023 if (!cpu_isset(this_cpu
, p
->cpus_allowed
))
2027 if (task_running(rq
, p
))
2031 * Aggressive migration if:
2032 * 1) task is cache cold, or
2033 * 2) too many balance attempts have failed.
2036 if (sd
->nr_balance_failed
> sd
->cache_nice_tries
)
2039 if (task_hot(p
, rq
->timestamp_last_tick
, sd
))
2044 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2047 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2048 * load from busiest to this_rq, as part of a balancing operation within
2049 * "domain". Returns the number of tasks moved.
2051 * Called with both runqueues locked.
2053 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2054 unsigned long max_nr_move
, unsigned long max_load_move
,
2055 struct sched_domain
*sd
, enum idle_type idle
,
2058 int idx
, pulled
= 0, pinned
= 0, this_best_prio
, best_prio
,
2059 best_prio_seen
, skip_for_load
;
2060 struct prio_array
*array
, *dst_array
;
2061 struct list_head
*head
, *curr
;
2062 struct task_struct
*tmp
;
2065 if (max_nr_move
== 0 || max_load_move
== 0)
2068 rem_load_move
= max_load_move
;
2070 this_best_prio
= rq_best_prio(this_rq
);
2071 best_prio
= rq_best_prio(busiest
);
2073 * Enable handling of the case where there is more than one task
2074 * with the best priority. If the current running task is one
2075 * of those with prio==best_prio we know it won't be moved
2076 * and therefore it's safe to override the skip (based on load) of
2077 * any task we find with that prio.
2079 best_prio_seen
= best_prio
== busiest
->curr
->prio
;
2082 * We first consider expired tasks. Those will likely not be
2083 * executed in the near future, and they are most likely to
2084 * be cache-cold, thus switching CPUs has the least effect
2087 if (busiest
->expired
->nr_active
) {
2088 array
= busiest
->expired
;
2089 dst_array
= this_rq
->expired
;
2091 array
= busiest
->active
;
2092 dst_array
= this_rq
->active
;
2096 /* Start searching at priority 0: */
2100 idx
= sched_find_first_bit(array
->bitmap
);
2102 idx
= find_next_bit(array
->bitmap
, MAX_PRIO
, idx
);
2103 if (idx
>= MAX_PRIO
) {
2104 if (array
== busiest
->expired
&& busiest
->active
->nr_active
) {
2105 array
= busiest
->active
;
2106 dst_array
= this_rq
->active
;
2112 head
= array
->queue
+ idx
;
2115 tmp
= list_entry(curr
, struct task_struct
, run_list
);
2120 * To help distribute high priority tasks accross CPUs we don't
2121 * skip a task if it will be the highest priority task (i.e. smallest
2122 * prio value) on its new queue regardless of its load weight
2124 skip_for_load
= tmp
->load_weight
> rem_load_move
;
2125 if (skip_for_load
&& idx
< this_best_prio
)
2126 skip_for_load
= !best_prio_seen
&& idx
== best_prio
;
2127 if (skip_for_load
||
2128 !can_migrate_task(tmp
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2130 best_prio_seen
|= idx
== best_prio
;
2137 #ifdef CONFIG_SCHEDSTATS
2138 if (task_hot(tmp
, busiest
->timestamp_last_tick
, sd
))
2139 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2142 pull_task(busiest
, array
, tmp
, this_rq
, dst_array
, this_cpu
);
2144 rem_load_move
-= tmp
->load_weight
;
2147 * We only want to steal up to the prescribed number of tasks
2148 * and the prescribed amount of weighted load.
2150 if (pulled
< max_nr_move
&& rem_load_move
> 0) {
2151 if (idx
< this_best_prio
)
2152 this_best_prio
= idx
;
2160 * Right now, this is the only place pull_task() is called,
2161 * so we can safely collect pull_task() stats here rather than
2162 * inside pull_task().
2164 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2167 *all_pinned
= pinned
;
2172 * find_busiest_group finds and returns the busiest CPU group within the
2173 * domain. It calculates and returns the amount of weighted load which
2174 * should be moved to restore balance via the imbalance parameter.
2176 static struct sched_group
*
2177 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2178 unsigned long *imbalance
, enum idle_type idle
, int *sd_idle
)
2180 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2181 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2182 unsigned long max_pull
;
2183 unsigned long busiest_load_per_task
, busiest_nr_running
;
2184 unsigned long this_load_per_task
, this_nr_running
;
2186 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2187 int power_savings_balance
= 1;
2188 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2189 unsigned long min_nr_running
= ULONG_MAX
;
2190 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2193 max_load
= this_load
= total_load
= total_pwr
= 0;
2194 busiest_load_per_task
= busiest_nr_running
= 0;
2195 this_load_per_task
= this_nr_running
= 0;
2196 if (idle
== NOT_IDLE
)
2197 load_idx
= sd
->busy_idx
;
2198 else if (idle
== NEWLY_IDLE
)
2199 load_idx
= sd
->newidle_idx
;
2201 load_idx
= sd
->idle_idx
;
2204 unsigned long load
, group_capacity
;
2207 unsigned long sum_nr_running
, sum_weighted_load
;
2209 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2211 /* Tally up the load of all CPUs in the group */
2212 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2214 for_each_cpu_mask(i
, group
->cpumask
) {
2215 struct rq
*rq
= cpu_rq(i
);
2217 if (*sd_idle
&& !idle_cpu(i
))
2220 /* Bias balancing toward cpus of our domain */
2222 load
= target_load(i
, load_idx
);
2224 load
= source_load(i
, load_idx
);
2227 sum_nr_running
+= rq
->nr_running
;
2228 sum_weighted_load
+= rq
->raw_weighted_load
;
2231 total_load
+= avg_load
;
2232 total_pwr
+= group
->cpu_power
;
2234 /* Adjust by relative CPU power of the group */
2235 avg_load
= (avg_load
* SCHED_LOAD_SCALE
) / group
->cpu_power
;
2237 group_capacity
= group
->cpu_power
/ SCHED_LOAD_SCALE
;
2240 this_load
= avg_load
;
2242 this_nr_running
= sum_nr_running
;
2243 this_load_per_task
= sum_weighted_load
;
2244 } else if (avg_load
> max_load
&&
2245 sum_nr_running
> group_capacity
) {
2246 max_load
= avg_load
;
2248 busiest_nr_running
= sum_nr_running
;
2249 busiest_load_per_task
= sum_weighted_load
;
2252 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2254 * Busy processors will not participate in power savings
2257 if (idle
== NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2261 * If the local group is idle or completely loaded
2262 * no need to do power savings balance at this domain
2264 if (local_group
&& (this_nr_running
>= group_capacity
||
2266 power_savings_balance
= 0;
2269 * If a group is already running at full capacity or idle,
2270 * don't include that group in power savings calculations
2272 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2277 * Calculate the group which has the least non-idle load.
2278 * This is the group from where we need to pick up the load
2281 if ((sum_nr_running
< min_nr_running
) ||
2282 (sum_nr_running
== min_nr_running
&&
2283 first_cpu(group
->cpumask
) <
2284 first_cpu(group_min
->cpumask
))) {
2286 min_nr_running
= sum_nr_running
;
2287 min_load_per_task
= sum_weighted_load
/
2292 * Calculate the group which is almost near its
2293 * capacity but still has some space to pick up some load
2294 * from other group and save more power
2296 if (sum_nr_running
<= group_capacity
- 1) {
2297 if (sum_nr_running
> leader_nr_running
||
2298 (sum_nr_running
== leader_nr_running
&&
2299 first_cpu(group
->cpumask
) >
2300 first_cpu(group_leader
->cpumask
))) {
2301 group_leader
= group
;
2302 leader_nr_running
= sum_nr_running
;
2307 group
= group
->next
;
2308 } while (group
!= sd
->groups
);
2310 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2313 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2315 if (this_load
>= avg_load
||
2316 100*max_load
<= sd
->imbalance_pct
*this_load
)
2319 busiest_load_per_task
/= busiest_nr_running
;
2321 * We're trying to get all the cpus to the average_load, so we don't
2322 * want to push ourselves above the average load, nor do we wish to
2323 * reduce the max loaded cpu below the average load, as either of these
2324 * actions would just result in more rebalancing later, and ping-pong
2325 * tasks around. Thus we look for the minimum possible imbalance.
2326 * Negative imbalances (*we* are more loaded than anyone else) will
2327 * be counted as no imbalance for these purposes -- we can't fix that
2328 * by pulling tasks to us. Be careful of negative numbers as they'll
2329 * appear as very large values with unsigned longs.
2331 if (max_load
<= busiest_load_per_task
)
2335 * In the presence of smp nice balancing, certain scenarios can have
2336 * max load less than avg load(as we skip the groups at or below
2337 * its cpu_power, while calculating max_load..)
2339 if (max_load
< avg_load
) {
2341 goto small_imbalance
;
2344 /* Don't want to pull so many tasks that a group would go idle */
2345 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2347 /* How much load to actually move to equalise the imbalance */
2348 *imbalance
= min(max_pull
* busiest
->cpu_power
,
2349 (avg_load
- this_load
) * this->cpu_power
)
2353 * if *imbalance is less than the average load per runnable task
2354 * there is no gaurantee that any tasks will be moved so we'll have
2355 * a think about bumping its value to force at least one task to be
2358 if (*imbalance
< busiest_load_per_task
) {
2359 unsigned long tmp
, pwr_now
, pwr_move
;
2363 pwr_move
= pwr_now
= 0;
2365 if (this_nr_running
) {
2366 this_load_per_task
/= this_nr_running
;
2367 if (busiest_load_per_task
> this_load_per_task
)
2370 this_load_per_task
= SCHED_LOAD_SCALE
;
2372 if (max_load
- this_load
>= busiest_load_per_task
* imbn
) {
2373 *imbalance
= busiest_load_per_task
;
2378 * OK, we don't have enough imbalance to justify moving tasks,
2379 * however we may be able to increase total CPU power used by
2383 pwr_now
+= busiest
->cpu_power
*
2384 min(busiest_load_per_task
, max_load
);
2385 pwr_now
+= this->cpu_power
*
2386 min(this_load_per_task
, this_load
);
2387 pwr_now
/= SCHED_LOAD_SCALE
;
2389 /* Amount of load we'd subtract */
2390 tmp
= busiest_load_per_task
*SCHED_LOAD_SCALE
/busiest
->cpu_power
;
2392 pwr_move
+= busiest
->cpu_power
*
2393 min(busiest_load_per_task
, max_load
- tmp
);
2395 /* Amount of load we'd add */
2396 if (max_load
*busiest
->cpu_power
<
2397 busiest_load_per_task
*SCHED_LOAD_SCALE
)
2398 tmp
= max_load
*busiest
->cpu_power
/this->cpu_power
;
2400 tmp
= busiest_load_per_task
*SCHED_LOAD_SCALE
/this->cpu_power
;
2401 pwr_move
+= this->cpu_power
*min(this_load_per_task
, this_load
+ tmp
);
2402 pwr_move
/= SCHED_LOAD_SCALE
;
2404 /* Move if we gain throughput */
2405 if (pwr_move
<= pwr_now
)
2408 *imbalance
= busiest_load_per_task
;
2414 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2415 if (idle
== NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2418 if (this == group_leader
&& group_leader
!= group_min
) {
2419 *imbalance
= min_load_per_task
;
2429 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2432 find_busiest_queue(struct sched_group
*group
, enum idle_type idle
,
2433 unsigned long imbalance
)
2435 struct rq
*busiest
= NULL
, *rq
;
2436 unsigned long max_load
= 0;
2439 for_each_cpu_mask(i
, group
->cpumask
) {
2442 if (rq
->nr_running
== 1 && rq
->raw_weighted_load
> imbalance
)
2445 if (rq
->raw_weighted_load
> max_load
) {
2446 max_load
= rq
->raw_weighted_load
;
2455 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2456 * so long as it is large enough.
2458 #define MAX_PINNED_INTERVAL 512
2460 static inline unsigned long minus_1_or_zero(unsigned long n
)
2462 return n
> 0 ? n
- 1 : 0;
2466 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2467 * tasks if there is an imbalance.
2469 * Called with this_rq unlocked.
2471 static int load_balance(int this_cpu
, struct rq
*this_rq
,
2472 struct sched_domain
*sd
, enum idle_type idle
)
2474 int nr_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
2475 struct sched_group
*group
;
2476 unsigned long imbalance
;
2479 if (idle
!= NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2480 !sched_smt_power_savings
)
2483 schedstat_inc(sd
, lb_cnt
[idle
]);
2485 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
);
2487 schedstat_inc(sd
, lb_nobusyg
[idle
]);
2491 busiest
= find_busiest_queue(group
, idle
, imbalance
);
2493 schedstat_inc(sd
, lb_nobusyq
[idle
]);
2497 BUG_ON(busiest
== this_rq
);
2499 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
2502 if (busiest
->nr_running
> 1) {
2504 * Attempt to move tasks. If find_busiest_group has found
2505 * an imbalance but busiest->nr_running <= 1, the group is
2506 * still unbalanced. nr_moved simply stays zero, so it is
2507 * correctly treated as an imbalance.
2509 double_rq_lock(this_rq
, busiest
);
2510 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2511 minus_1_or_zero(busiest
->nr_running
),
2512 imbalance
, sd
, idle
, &all_pinned
);
2513 double_rq_unlock(this_rq
, busiest
);
2515 /* All tasks on this runqueue were pinned by CPU affinity */
2516 if (unlikely(all_pinned
))
2521 schedstat_inc(sd
, lb_failed
[idle
]);
2522 sd
->nr_balance_failed
++;
2524 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
2526 spin_lock(&busiest
->lock
);
2528 /* don't kick the migration_thread, if the curr
2529 * task on busiest cpu can't be moved to this_cpu
2531 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
2532 spin_unlock(&busiest
->lock
);
2534 goto out_one_pinned
;
2537 if (!busiest
->active_balance
) {
2538 busiest
->active_balance
= 1;
2539 busiest
->push_cpu
= this_cpu
;
2542 spin_unlock(&busiest
->lock
);
2544 wake_up_process(busiest
->migration_thread
);
2547 * We've kicked active balancing, reset the failure
2550 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
2553 sd
->nr_balance_failed
= 0;
2555 if (likely(!active_balance
)) {
2556 /* We were unbalanced, so reset the balancing interval */
2557 sd
->balance_interval
= sd
->min_interval
;
2560 * If we've begun active balancing, start to back off. This
2561 * case may not be covered by the all_pinned logic if there
2562 * is only 1 task on the busy runqueue (because we don't call
2565 if (sd
->balance_interval
< sd
->max_interval
)
2566 sd
->balance_interval
*= 2;
2569 if (!nr_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2570 !sched_smt_power_savings
)
2575 schedstat_inc(sd
, lb_balanced
[idle
]);
2577 sd
->nr_balance_failed
= 0;
2580 /* tune up the balancing interval */
2581 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
2582 (sd
->balance_interval
< sd
->max_interval
))
2583 sd
->balance_interval
*= 2;
2585 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2586 !sched_smt_power_savings
)
2592 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2593 * tasks if there is an imbalance.
2595 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2596 * this_rq is locked.
2599 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
2601 struct sched_group
*group
;
2602 struct rq
*busiest
= NULL
;
2603 unsigned long imbalance
;
2607 if (sd
->flags
& SD_SHARE_CPUPOWER
&& !sched_smt_power_savings
)
2610 schedstat_inc(sd
, lb_cnt
[NEWLY_IDLE
]);
2611 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, NEWLY_IDLE
, &sd_idle
);
2613 schedstat_inc(sd
, lb_nobusyg
[NEWLY_IDLE
]);
2617 busiest
= find_busiest_queue(group
, NEWLY_IDLE
, imbalance
);
2619 schedstat_inc(sd
, lb_nobusyq
[NEWLY_IDLE
]);
2623 BUG_ON(busiest
== this_rq
);
2625 schedstat_add(sd
, lb_imbalance
[NEWLY_IDLE
], imbalance
);
2628 if (busiest
->nr_running
> 1) {
2629 /* Attempt to move tasks */
2630 double_lock_balance(this_rq
, busiest
);
2631 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2632 minus_1_or_zero(busiest
->nr_running
),
2633 imbalance
, sd
, NEWLY_IDLE
, NULL
);
2634 spin_unlock(&busiest
->lock
);
2638 schedstat_inc(sd
, lb_failed
[NEWLY_IDLE
]);
2639 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
)
2642 sd
->nr_balance_failed
= 0;
2647 schedstat_inc(sd
, lb_balanced
[NEWLY_IDLE
]);
2648 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2649 !sched_smt_power_savings
)
2651 sd
->nr_balance_failed
= 0;
2657 * idle_balance is called by schedule() if this_cpu is about to become
2658 * idle. Attempts to pull tasks from other CPUs.
2660 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
2662 struct sched_domain
*sd
;
2664 for_each_domain(this_cpu
, sd
) {
2665 if (sd
->flags
& SD_BALANCE_NEWIDLE
) {
2666 /* If we've pulled tasks over stop searching: */
2667 if (load_balance_newidle(this_cpu
, this_rq
, sd
))
2674 * active_load_balance is run by migration threads. It pushes running tasks
2675 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2676 * running on each physical CPU where possible, and avoids physical /
2677 * logical imbalances.
2679 * Called with busiest_rq locked.
2681 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
2683 int target_cpu
= busiest_rq
->push_cpu
;
2684 struct sched_domain
*sd
;
2685 struct rq
*target_rq
;
2687 /* Is there any task to move? */
2688 if (busiest_rq
->nr_running
<= 1)
2691 target_rq
= cpu_rq(target_cpu
);
2694 * This condition is "impossible", if it occurs
2695 * we need to fix it. Originally reported by
2696 * Bjorn Helgaas on a 128-cpu setup.
2698 BUG_ON(busiest_rq
== target_rq
);
2700 /* move a task from busiest_rq to target_rq */
2701 double_lock_balance(busiest_rq
, target_rq
);
2703 /* Search for an sd spanning us and the target CPU. */
2704 for_each_domain(target_cpu
, sd
) {
2705 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
2706 cpu_isset(busiest_cpu
, sd
->span
))
2711 schedstat_inc(sd
, alb_cnt
);
2713 if (move_tasks(target_rq
, target_cpu
, busiest_rq
, 1,
2714 RTPRIO_TO_LOAD_WEIGHT(100), sd
, SCHED_IDLE
,
2716 schedstat_inc(sd
, alb_pushed
);
2718 schedstat_inc(sd
, alb_failed
);
2720 spin_unlock(&target_rq
->lock
);
2724 * rebalance_tick will get called every timer tick, on every CPU.
2726 * It checks each scheduling domain to see if it is due to be balanced,
2727 * and initiates a balancing operation if so.
2729 * Balancing parameters are set up in arch_init_sched_domains.
2732 /* Don't have all balancing operations going off at once: */
2733 static inline unsigned long cpu_offset(int cpu
)
2735 return jiffies
+ cpu
* HZ
/ NR_CPUS
;
2739 rebalance_tick(int this_cpu
, struct rq
*this_rq
, enum idle_type idle
)
2741 unsigned long this_load
, interval
, j
= cpu_offset(this_cpu
);
2742 struct sched_domain
*sd
;
2745 this_load
= this_rq
->raw_weighted_load
;
2747 /* Update our load: */
2748 for (i
= 0, scale
= 1; i
< 3; i
++, scale
<<= 1) {
2749 unsigned long old_load
, new_load
;
2751 old_load
= this_rq
->cpu_load
[i
];
2752 new_load
= this_load
;
2754 * Round up the averaging division if load is increasing. This
2755 * prevents us from getting stuck on 9 if the load is 10, for
2758 if (new_load
> old_load
)
2759 new_load
+= scale
-1;
2760 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) / scale
;
2763 for_each_domain(this_cpu
, sd
) {
2764 if (!(sd
->flags
& SD_LOAD_BALANCE
))
2767 interval
= sd
->balance_interval
;
2768 if (idle
!= SCHED_IDLE
)
2769 interval
*= sd
->busy_factor
;
2771 /* scale ms to jiffies */
2772 interval
= msecs_to_jiffies(interval
);
2773 if (unlikely(!interval
))
2776 if (j
- sd
->last_balance
>= interval
) {
2777 if (load_balance(this_cpu
, this_rq
, sd
, idle
)) {
2779 * We've pulled tasks over so either we're no
2780 * longer idle, or one of our SMT siblings is
2785 sd
->last_balance
+= interval
;
2791 * on UP we do not need to balance between CPUs:
2793 static inline void rebalance_tick(int cpu
, struct rq
*rq
, enum idle_type idle
)
2796 static inline void idle_balance(int cpu
, struct rq
*rq
)
2801 static inline int wake_priority_sleeper(struct rq
*rq
)
2805 #ifdef CONFIG_SCHED_SMT
2806 spin_lock(&rq
->lock
);
2808 * If an SMT sibling task has been put to sleep for priority
2809 * reasons reschedule the idle task to see if it can now run.
2811 if (rq
->nr_running
) {
2812 resched_task(rq
->idle
);
2815 spin_unlock(&rq
->lock
);
2820 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
2822 EXPORT_PER_CPU_SYMBOL(kstat
);
2825 * This is called on clock ticks and on context switches.
2826 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2829 update_cpu_clock(struct task_struct
*p
, struct rq
*rq
, unsigned long long now
)
2831 p
->sched_time
+= now
- max(p
->timestamp
, rq
->timestamp_last_tick
);
2835 * Return current->sched_time plus any more ns on the sched_clock
2836 * that have not yet been banked.
2838 unsigned long long current_sched_time(const struct task_struct
*p
)
2840 unsigned long long ns
;
2841 unsigned long flags
;
2843 local_irq_save(flags
);
2844 ns
= max(p
->timestamp
, task_rq(p
)->timestamp_last_tick
);
2845 ns
= p
->sched_time
+ sched_clock() - ns
;
2846 local_irq_restore(flags
);
2852 * We place interactive tasks back into the active array, if possible.
2854 * To guarantee that this does not starve expired tasks we ignore the
2855 * interactivity of a task if the first expired task had to wait more
2856 * than a 'reasonable' amount of time. This deadline timeout is
2857 * load-dependent, as the frequency of array switched decreases with
2858 * increasing number of running tasks. We also ignore the interactivity
2859 * if a better static_prio task has expired:
2861 static inline int expired_starving(struct rq
*rq
)
2863 if (rq
->curr
->static_prio
> rq
->best_expired_prio
)
2865 if (!STARVATION_LIMIT
|| !rq
->expired_timestamp
)
2867 if (jiffies
- rq
->expired_timestamp
> STARVATION_LIMIT
* rq
->nr_running
)
2873 * Account user cpu time to a process.
2874 * @p: the process that the cpu time gets accounted to
2875 * @hardirq_offset: the offset to subtract from hardirq_count()
2876 * @cputime: the cpu time spent in user space since the last update
2878 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
2880 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2883 p
->utime
= cputime_add(p
->utime
, cputime
);
2885 /* Add user time to cpustat. */
2886 tmp
= cputime_to_cputime64(cputime
);
2887 if (TASK_NICE(p
) > 0)
2888 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
2890 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
2894 * Account system cpu time to a process.
2895 * @p: the process that the cpu time gets accounted to
2896 * @hardirq_offset: the offset to subtract from hardirq_count()
2897 * @cputime: the cpu time spent in kernel space since the last update
2899 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
2902 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2903 struct rq
*rq
= this_rq();
2906 p
->stime
= cputime_add(p
->stime
, cputime
);
2908 /* Add system time to cpustat. */
2909 tmp
= cputime_to_cputime64(cputime
);
2910 if (hardirq_count() - hardirq_offset
)
2911 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
2912 else if (softirq_count())
2913 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
2914 else if (p
!= rq
->idle
)
2915 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
2916 else if (atomic_read(&rq
->nr_iowait
) > 0)
2917 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
2919 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
2920 /* Account for system time used */
2921 acct_update_integrals(p
);
2925 * Account for involuntary wait time.
2926 * @p: the process from which the cpu time has been stolen
2927 * @steal: the cpu time spent in involuntary wait
2929 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
2931 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2932 cputime64_t tmp
= cputime_to_cputime64(steal
);
2933 struct rq
*rq
= this_rq();
2935 if (p
== rq
->idle
) {
2936 p
->stime
= cputime_add(p
->stime
, steal
);
2937 if (atomic_read(&rq
->nr_iowait
) > 0)
2938 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
2940 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
2942 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
2946 * This function gets called by the timer code, with HZ frequency.
2947 * We call it with interrupts disabled.
2949 * It also gets called by the fork code, when changing the parent's
2952 void scheduler_tick(void)
2954 unsigned long long now
= sched_clock();
2955 struct task_struct
*p
= current
;
2956 int cpu
= smp_processor_id();
2957 struct rq
*rq
= cpu_rq(cpu
);
2959 update_cpu_clock(p
, rq
, now
);
2961 rq
->timestamp_last_tick
= now
;
2963 if (p
== rq
->idle
) {
2964 if (wake_priority_sleeper(rq
))
2966 rebalance_tick(cpu
, rq
, SCHED_IDLE
);
2970 /* Task might have expired already, but not scheduled off yet */
2971 if (p
->array
!= rq
->active
) {
2972 set_tsk_need_resched(p
);
2975 spin_lock(&rq
->lock
);
2977 * The task was running during this tick - update the
2978 * time slice counter. Note: we do not update a thread's
2979 * priority until it either goes to sleep or uses up its
2980 * timeslice. This makes it possible for interactive tasks
2981 * to use up their timeslices at their highest priority levels.
2985 * RR tasks need a special form of timeslice management.
2986 * FIFO tasks have no timeslices.
2988 if ((p
->policy
== SCHED_RR
) && !--p
->time_slice
) {
2989 p
->time_slice
= task_timeslice(p
);
2990 p
->first_time_slice
= 0;
2991 set_tsk_need_resched(p
);
2993 /* put it at the end of the queue: */
2994 requeue_task(p
, rq
->active
);
2998 if (!--p
->time_slice
) {
2999 dequeue_task(p
, rq
->active
);
3000 set_tsk_need_resched(p
);
3001 p
->prio
= effective_prio(p
);
3002 p
->time_slice
= task_timeslice(p
);
3003 p
->first_time_slice
= 0;
3005 if (!rq
->expired_timestamp
)
3006 rq
->expired_timestamp
= jiffies
;
3007 if (!TASK_INTERACTIVE(p
) || expired_starving(rq
)) {
3008 enqueue_task(p
, rq
->expired
);
3009 if (p
->static_prio
< rq
->best_expired_prio
)
3010 rq
->best_expired_prio
= p
->static_prio
;
3012 enqueue_task(p
, rq
->active
);
3015 * Prevent a too long timeslice allowing a task to monopolize
3016 * the CPU. We do this by splitting up the timeslice into
3019 * Note: this does not mean the task's timeslices expire or
3020 * get lost in any way, they just might be preempted by
3021 * another task of equal priority. (one with higher
3022 * priority would have preempted this task already.) We
3023 * requeue this task to the end of the list on this priority
3024 * level, which is in essence a round-robin of tasks with
3027 * This only applies to tasks in the interactive
3028 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3030 if (TASK_INTERACTIVE(p
) && !((task_timeslice(p
) -
3031 p
->time_slice
) % TIMESLICE_GRANULARITY(p
)) &&
3032 (p
->time_slice
>= TIMESLICE_GRANULARITY(p
)) &&
3033 (p
->array
== rq
->active
)) {
3035 requeue_task(p
, rq
->active
);
3036 set_tsk_need_resched(p
);
3040 spin_unlock(&rq
->lock
);
3042 rebalance_tick(cpu
, rq
, NOT_IDLE
);
3045 #ifdef CONFIG_SCHED_SMT
3046 static inline void wakeup_busy_runqueue(struct rq
*rq
)
3048 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3049 if (rq
->curr
== rq
->idle
&& rq
->nr_running
)
3050 resched_task(rq
->idle
);
3054 * Called with interrupt disabled and this_rq's runqueue locked.
3056 static void wake_sleeping_dependent(int this_cpu
)
3058 struct sched_domain
*tmp
, *sd
= NULL
;
3061 for_each_domain(this_cpu
, tmp
) {
3062 if (tmp
->flags
& SD_SHARE_CPUPOWER
) {
3071 for_each_cpu_mask(i
, sd
->span
) {
3072 struct rq
*smt_rq
= cpu_rq(i
);
3076 if (unlikely(!spin_trylock(&smt_rq
->lock
)))
3079 wakeup_busy_runqueue(smt_rq
);
3080 spin_unlock(&smt_rq
->lock
);
3085 * number of 'lost' timeslices this task wont be able to fully
3086 * utilize, if another task runs on a sibling. This models the
3087 * slowdown effect of other tasks running on siblings:
3089 static inline unsigned long
3090 smt_slice(struct task_struct
*p
, struct sched_domain
*sd
)
3092 return p
->time_slice
* (100 - sd
->per_cpu_gain
) / 100;
3096 * To minimise lock contention and not have to drop this_rq's runlock we only
3097 * trylock the sibling runqueues and bypass those runqueues if we fail to
3098 * acquire their lock. As we only trylock the normal locking order does not
3099 * need to be obeyed.
3102 dependent_sleeper(int this_cpu
, struct rq
*this_rq
, struct task_struct
*p
)
3104 struct sched_domain
*tmp
, *sd
= NULL
;
3107 /* kernel/rt threads do not participate in dependent sleeping */
3108 if (!p
->mm
|| rt_task(p
))
3111 for_each_domain(this_cpu
, tmp
) {
3112 if (tmp
->flags
& SD_SHARE_CPUPOWER
) {
3121 for_each_cpu_mask(i
, sd
->span
) {
3122 struct task_struct
*smt_curr
;
3129 if (unlikely(!spin_trylock(&smt_rq
->lock
)))
3132 smt_curr
= smt_rq
->curr
;
3138 * If a user task with lower static priority than the
3139 * running task on the SMT sibling is trying to schedule,
3140 * delay it till there is proportionately less timeslice
3141 * left of the sibling task to prevent a lower priority
3142 * task from using an unfair proportion of the
3143 * physical cpu's resources. -ck
3145 if (rt_task(smt_curr
)) {
3147 * With real time tasks we run non-rt tasks only
3148 * per_cpu_gain% of the time.
3150 if ((jiffies
% DEF_TIMESLICE
) >
3151 (sd
->per_cpu_gain
* DEF_TIMESLICE
/ 100))
3154 if (smt_curr
->static_prio
< p
->static_prio
&&
3155 !TASK_PREEMPTS_CURR(p
, smt_rq
) &&
3156 smt_slice(smt_curr
, sd
) > task_timeslice(p
))
3160 spin_unlock(&smt_rq
->lock
);
3165 static inline void wake_sleeping_dependent(int this_cpu
)
3169 dependent_sleeper(int this_cpu
, struct rq
*this_rq
, struct task_struct
*p
)
3175 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3177 void fastcall
add_preempt_count(int val
)
3182 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3184 preempt_count() += val
;
3186 * Spinlock count overflowing soon?
3188 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >= PREEMPT_MASK
-10);
3190 EXPORT_SYMBOL(add_preempt_count
);
3192 void fastcall
sub_preempt_count(int val
)
3197 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3200 * Is the spinlock portion underflowing?
3202 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3203 !(preempt_count() & PREEMPT_MASK
)))
3206 preempt_count() -= val
;
3208 EXPORT_SYMBOL(sub_preempt_count
);
3212 static inline int interactive_sleep(enum sleep_type sleep_type
)
3214 return (sleep_type
== SLEEP_INTERACTIVE
||
3215 sleep_type
== SLEEP_INTERRUPTED
);
3219 * schedule() is the main scheduler function.
3221 asmlinkage
void __sched
schedule(void)
3223 struct task_struct
*prev
, *next
;
3224 struct prio_array
*array
;
3225 struct list_head
*queue
;
3226 unsigned long long now
;
3227 unsigned long run_time
;
3228 int cpu
, idx
, new_prio
;
3233 * Test if we are atomic. Since do_exit() needs to call into
3234 * schedule() atomically, we ignore that path for now.
3235 * Otherwise, whine if we are scheduling when we should not be.
3237 if (unlikely(in_atomic() && !current
->exit_state
)) {
3238 printk(KERN_ERR
"BUG: scheduling while atomic: "
3240 current
->comm
, preempt_count(), current
->pid
);
3243 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3248 release_kernel_lock(prev
);
3249 need_resched_nonpreemptible
:
3253 * The idle thread is not allowed to schedule!
3254 * Remove this check after it has been exercised a bit.
3256 if (unlikely(prev
== rq
->idle
) && prev
->state
!= TASK_RUNNING
) {
3257 printk(KERN_ERR
"bad: scheduling from the idle thread!\n");
3261 schedstat_inc(rq
, sched_cnt
);
3262 now
= sched_clock();
3263 if (likely((long long)(now
- prev
->timestamp
) < NS_MAX_SLEEP_AVG
)) {
3264 run_time
= now
- prev
->timestamp
;
3265 if (unlikely((long long)(now
- prev
->timestamp
) < 0))
3268 run_time
= NS_MAX_SLEEP_AVG
;
3271 * Tasks charged proportionately less run_time at high sleep_avg to
3272 * delay them losing their interactive status
3274 run_time
/= (CURRENT_BONUS(prev
) ? : 1);
3276 spin_lock_irq(&rq
->lock
);
3278 if (unlikely(prev
->flags
& PF_DEAD
))
3279 prev
->state
= EXIT_DEAD
;
3281 switch_count
= &prev
->nivcsw
;
3282 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3283 switch_count
= &prev
->nvcsw
;
3284 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3285 unlikely(signal_pending(prev
))))
3286 prev
->state
= TASK_RUNNING
;
3288 if (prev
->state
== TASK_UNINTERRUPTIBLE
)
3289 rq
->nr_uninterruptible
++;
3290 deactivate_task(prev
, rq
);
3294 cpu
= smp_processor_id();
3295 if (unlikely(!rq
->nr_running
)) {
3296 idle_balance(cpu
, rq
);
3297 if (!rq
->nr_running
) {
3299 rq
->expired_timestamp
= 0;
3300 wake_sleeping_dependent(cpu
);
3306 if (unlikely(!array
->nr_active
)) {
3308 * Switch the active and expired arrays.
3310 schedstat_inc(rq
, sched_switch
);
3311 rq
->active
= rq
->expired
;
3312 rq
->expired
= array
;
3314 rq
->expired_timestamp
= 0;
3315 rq
->best_expired_prio
= MAX_PRIO
;
3318 idx
= sched_find_first_bit(array
->bitmap
);
3319 queue
= array
->queue
+ idx
;
3320 next
= list_entry(queue
->next
, struct task_struct
, run_list
);
3322 if (!rt_task(next
) && interactive_sleep(next
->sleep_type
)) {
3323 unsigned long long delta
= now
- next
->timestamp
;
3324 if (unlikely((long long)(now
- next
->timestamp
) < 0))
3327 if (next
->sleep_type
== SLEEP_INTERACTIVE
)
3328 delta
= delta
* (ON_RUNQUEUE_WEIGHT
* 128 / 100) / 128;
3330 array
= next
->array
;
3331 new_prio
= recalc_task_prio(next
, next
->timestamp
+ delta
);
3333 if (unlikely(next
->prio
!= new_prio
)) {
3334 dequeue_task(next
, array
);
3335 next
->prio
= new_prio
;
3336 enqueue_task(next
, array
);
3339 next
->sleep_type
= SLEEP_NORMAL
;
3340 if (dependent_sleeper(cpu
, rq
, next
))
3343 if (next
== rq
->idle
)
3344 schedstat_inc(rq
, sched_goidle
);
3346 prefetch_stack(next
);
3347 clear_tsk_need_resched(prev
);
3348 rcu_qsctr_inc(task_cpu(prev
));
3350 update_cpu_clock(prev
, rq
, now
);
3352 prev
->sleep_avg
-= run_time
;
3353 if ((long)prev
->sleep_avg
<= 0)
3354 prev
->sleep_avg
= 0;
3355 prev
->timestamp
= prev
->last_ran
= now
;
3357 sched_info_switch(prev
, next
);
3358 if (likely(prev
!= next
)) {
3359 next
->timestamp
= now
;
3364 prepare_task_switch(rq
, next
);
3365 prev
= context_switch(rq
, prev
, next
);
3368 * this_rq must be evaluated again because prev may have moved
3369 * CPUs since it called schedule(), thus the 'rq' on its stack
3370 * frame will be invalid.
3372 finish_task_switch(this_rq(), prev
);
3374 spin_unlock_irq(&rq
->lock
);
3377 if (unlikely(reacquire_kernel_lock(prev
) < 0))
3378 goto need_resched_nonpreemptible
;
3379 preempt_enable_no_resched();
3380 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3383 EXPORT_SYMBOL(schedule
);
3385 #ifdef CONFIG_PREEMPT
3387 * this is the entry point to schedule() from in-kernel preemption
3388 * off of preempt_enable. Kernel preemptions off return from interrupt
3389 * occur there and call schedule directly.
3391 asmlinkage
void __sched
preempt_schedule(void)
3393 struct thread_info
*ti
= current_thread_info();
3394 #ifdef CONFIG_PREEMPT_BKL
3395 struct task_struct
*task
= current
;
3396 int saved_lock_depth
;
3399 * If there is a non-zero preempt_count or interrupts are disabled,
3400 * we do not want to preempt the current task. Just return..
3402 if (unlikely(ti
->preempt_count
|| irqs_disabled()))
3406 add_preempt_count(PREEMPT_ACTIVE
);
3408 * We keep the big kernel semaphore locked, but we
3409 * clear ->lock_depth so that schedule() doesnt
3410 * auto-release the semaphore:
3412 #ifdef CONFIG_PREEMPT_BKL
3413 saved_lock_depth
= task
->lock_depth
;
3414 task
->lock_depth
= -1;
3417 #ifdef CONFIG_PREEMPT_BKL
3418 task
->lock_depth
= saved_lock_depth
;
3420 sub_preempt_count(PREEMPT_ACTIVE
);
3422 /* we could miss a preemption opportunity between schedule and now */
3424 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3427 EXPORT_SYMBOL(preempt_schedule
);
3430 * this is the entry point to schedule() from kernel preemption
3431 * off of irq context.
3432 * Note, that this is called and return with irqs disabled. This will
3433 * protect us against recursive calling from irq.
3435 asmlinkage
void __sched
preempt_schedule_irq(void)
3437 struct thread_info
*ti
= current_thread_info();
3438 #ifdef CONFIG_PREEMPT_BKL
3439 struct task_struct
*task
= current
;
3440 int saved_lock_depth
;
3442 /* Catch callers which need to be fixed */
3443 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
3446 add_preempt_count(PREEMPT_ACTIVE
);
3448 * We keep the big kernel semaphore locked, but we
3449 * clear ->lock_depth so that schedule() doesnt
3450 * auto-release the semaphore:
3452 #ifdef CONFIG_PREEMPT_BKL
3453 saved_lock_depth
= task
->lock_depth
;
3454 task
->lock_depth
= -1;
3458 local_irq_disable();
3459 #ifdef CONFIG_PREEMPT_BKL
3460 task
->lock_depth
= saved_lock_depth
;
3462 sub_preempt_count(PREEMPT_ACTIVE
);
3464 /* we could miss a preemption opportunity between schedule and now */
3466 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3470 #endif /* CONFIG_PREEMPT */
3472 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
3475 return try_to_wake_up(curr
->private, mode
, sync
);
3477 EXPORT_SYMBOL(default_wake_function
);
3480 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3481 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3482 * number) then we wake all the non-exclusive tasks and one exclusive task.
3484 * There are circumstances in which we can try to wake a task which has already
3485 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3486 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3488 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
3489 int nr_exclusive
, int sync
, void *key
)
3491 struct list_head
*tmp
, *next
;
3493 list_for_each_safe(tmp
, next
, &q
->task_list
) {
3494 wait_queue_t
*curr
= list_entry(tmp
, wait_queue_t
, task_list
);
3495 unsigned flags
= curr
->flags
;
3497 if (curr
->func(curr
, mode
, sync
, key
) &&
3498 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
3504 * __wake_up - wake up threads blocked on a waitqueue.
3506 * @mode: which threads
3507 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3508 * @key: is directly passed to the wakeup function
3510 void fastcall
__wake_up(wait_queue_head_t
*q
, unsigned int mode
,
3511 int nr_exclusive
, void *key
)
3513 unsigned long flags
;
3515 spin_lock_irqsave(&q
->lock
, flags
);
3516 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
3517 spin_unlock_irqrestore(&q
->lock
, flags
);
3519 EXPORT_SYMBOL(__wake_up
);
3522 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3524 void fastcall
__wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
3526 __wake_up_common(q
, mode
, 1, 0, NULL
);
3530 * __wake_up_sync - wake up threads blocked on a waitqueue.
3532 * @mode: which threads
3533 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3535 * The sync wakeup differs that the waker knows that it will schedule
3536 * away soon, so while the target thread will be woken up, it will not
3537 * be migrated to another CPU - ie. the two threads are 'synchronized'
3538 * with each other. This can prevent needless bouncing between CPUs.
3540 * On UP it can prevent extra preemption.
3543 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
3545 unsigned long flags
;
3551 if (unlikely(!nr_exclusive
))
3554 spin_lock_irqsave(&q
->lock
, flags
);
3555 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
3556 spin_unlock_irqrestore(&q
->lock
, flags
);
3558 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
3560 void fastcall
complete(struct completion
*x
)
3562 unsigned long flags
;
3564 spin_lock_irqsave(&x
->wait
.lock
, flags
);
3566 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
3568 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
3570 EXPORT_SYMBOL(complete
);
3572 void fastcall
complete_all(struct completion
*x
)
3574 unsigned long flags
;
3576 spin_lock_irqsave(&x
->wait
.lock
, flags
);
3577 x
->done
+= UINT_MAX
/2;
3578 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
3580 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
3582 EXPORT_SYMBOL(complete_all
);
3584 void fastcall __sched
wait_for_completion(struct completion
*x
)
3588 spin_lock_irq(&x
->wait
.lock
);
3590 DECLARE_WAITQUEUE(wait
, current
);
3592 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3593 __add_wait_queue_tail(&x
->wait
, &wait
);
3595 __set_current_state(TASK_UNINTERRUPTIBLE
);
3596 spin_unlock_irq(&x
->wait
.lock
);
3598 spin_lock_irq(&x
->wait
.lock
);
3600 __remove_wait_queue(&x
->wait
, &wait
);
3603 spin_unlock_irq(&x
->wait
.lock
);
3605 EXPORT_SYMBOL(wait_for_completion
);
3607 unsigned long fastcall __sched
3608 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
3612 spin_lock_irq(&x
->wait
.lock
);
3614 DECLARE_WAITQUEUE(wait
, current
);
3616 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3617 __add_wait_queue_tail(&x
->wait
, &wait
);
3619 __set_current_state(TASK_UNINTERRUPTIBLE
);
3620 spin_unlock_irq(&x
->wait
.lock
);
3621 timeout
= schedule_timeout(timeout
);
3622 spin_lock_irq(&x
->wait
.lock
);
3624 __remove_wait_queue(&x
->wait
, &wait
);
3628 __remove_wait_queue(&x
->wait
, &wait
);
3632 spin_unlock_irq(&x
->wait
.lock
);
3635 EXPORT_SYMBOL(wait_for_completion_timeout
);
3637 int fastcall __sched
wait_for_completion_interruptible(struct completion
*x
)
3643 spin_lock_irq(&x
->wait
.lock
);
3645 DECLARE_WAITQUEUE(wait
, current
);
3647 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3648 __add_wait_queue_tail(&x
->wait
, &wait
);
3650 if (signal_pending(current
)) {
3652 __remove_wait_queue(&x
->wait
, &wait
);
3655 __set_current_state(TASK_INTERRUPTIBLE
);
3656 spin_unlock_irq(&x
->wait
.lock
);
3658 spin_lock_irq(&x
->wait
.lock
);
3660 __remove_wait_queue(&x
->wait
, &wait
);
3664 spin_unlock_irq(&x
->wait
.lock
);
3668 EXPORT_SYMBOL(wait_for_completion_interruptible
);
3670 unsigned long fastcall __sched
3671 wait_for_completion_interruptible_timeout(struct completion
*x
,
3672 unsigned long timeout
)
3676 spin_lock_irq(&x
->wait
.lock
);
3678 DECLARE_WAITQUEUE(wait
, current
);
3680 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3681 __add_wait_queue_tail(&x
->wait
, &wait
);
3683 if (signal_pending(current
)) {
3684 timeout
= -ERESTARTSYS
;
3685 __remove_wait_queue(&x
->wait
, &wait
);
3688 __set_current_state(TASK_INTERRUPTIBLE
);
3689 spin_unlock_irq(&x
->wait
.lock
);
3690 timeout
= schedule_timeout(timeout
);
3691 spin_lock_irq(&x
->wait
.lock
);
3693 __remove_wait_queue(&x
->wait
, &wait
);
3697 __remove_wait_queue(&x
->wait
, &wait
);
3701 spin_unlock_irq(&x
->wait
.lock
);
3704 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
3707 #define SLEEP_ON_VAR \
3708 unsigned long flags; \
3709 wait_queue_t wait; \
3710 init_waitqueue_entry(&wait, current);
3712 #define SLEEP_ON_HEAD \
3713 spin_lock_irqsave(&q->lock,flags); \
3714 __add_wait_queue(q, &wait); \
3715 spin_unlock(&q->lock);
3717 #define SLEEP_ON_TAIL \
3718 spin_lock_irq(&q->lock); \
3719 __remove_wait_queue(q, &wait); \
3720 spin_unlock_irqrestore(&q->lock, flags);
3722 void fastcall __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
3726 current
->state
= TASK_INTERRUPTIBLE
;
3732 EXPORT_SYMBOL(interruptible_sleep_on
);
3734 long fastcall __sched
3735 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3739 current
->state
= TASK_INTERRUPTIBLE
;
3742 timeout
= schedule_timeout(timeout
);
3747 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
3749 void fastcall __sched
sleep_on(wait_queue_head_t
*q
)
3753 current
->state
= TASK_UNINTERRUPTIBLE
;
3759 EXPORT_SYMBOL(sleep_on
);
3761 long fastcall __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3765 current
->state
= TASK_UNINTERRUPTIBLE
;
3768 timeout
= schedule_timeout(timeout
);
3774 EXPORT_SYMBOL(sleep_on_timeout
);
3776 #ifdef CONFIG_RT_MUTEXES
3779 * rt_mutex_setprio - set the current priority of a task
3781 * @prio: prio value (kernel-internal form)
3783 * This function changes the 'effective' priority of a task. It does
3784 * not touch ->normal_prio like __setscheduler().
3786 * Used by the rt_mutex code to implement priority inheritance logic.
3788 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
3790 struct prio_array
*array
;
3791 unsigned long flags
;
3795 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
3797 rq
= task_rq_lock(p
, &flags
);
3802 dequeue_task(p
, array
);
3807 * If changing to an RT priority then queue it
3808 * in the active array!
3812 enqueue_task(p
, array
);
3814 * Reschedule if we are currently running on this runqueue and
3815 * our priority decreased, or if we are not currently running on
3816 * this runqueue and our priority is higher than the current's
3818 if (task_running(rq
, p
)) {
3819 if (p
->prio
> oldprio
)
3820 resched_task(rq
->curr
);
3821 } else if (TASK_PREEMPTS_CURR(p
, rq
))
3822 resched_task(rq
->curr
);
3824 task_rq_unlock(rq
, &flags
);
3829 void set_user_nice(struct task_struct
*p
, long nice
)
3831 struct prio_array
*array
;
3832 int old_prio
, delta
;
3833 unsigned long flags
;
3836 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
3839 * We have to be careful, if called from sys_setpriority(),
3840 * the task might be in the middle of scheduling on another CPU.
3842 rq
= task_rq_lock(p
, &flags
);
3844 * The RT priorities are set via sched_setscheduler(), but we still
3845 * allow the 'normal' nice value to be set - but as expected
3846 * it wont have any effect on scheduling until the task is
3847 * not SCHED_NORMAL/SCHED_BATCH:
3849 if (has_rt_policy(p
)) {
3850 p
->static_prio
= NICE_TO_PRIO(nice
);
3855 dequeue_task(p
, array
);
3856 dec_raw_weighted_load(rq
, p
);
3859 p
->static_prio
= NICE_TO_PRIO(nice
);
3862 p
->prio
= effective_prio(p
);
3863 delta
= p
->prio
- old_prio
;
3866 enqueue_task(p
, array
);
3867 inc_raw_weighted_load(rq
, p
);
3869 * If the task increased its priority or is running and
3870 * lowered its priority, then reschedule its CPU:
3872 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
3873 resched_task(rq
->curr
);
3876 task_rq_unlock(rq
, &flags
);
3878 EXPORT_SYMBOL(set_user_nice
);
3881 * can_nice - check if a task can reduce its nice value
3885 int can_nice(const struct task_struct
*p
, const int nice
)
3887 /* convert nice value [19,-20] to rlimit style value [1,40] */
3888 int nice_rlim
= 20 - nice
;
3890 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
3891 capable(CAP_SYS_NICE
));
3894 #ifdef __ARCH_WANT_SYS_NICE
3897 * sys_nice - change the priority of the current process.
3898 * @increment: priority increment
3900 * sys_setpriority is a more generic, but much slower function that
3901 * does similar things.
3903 asmlinkage
long sys_nice(int increment
)
3908 * Setpriority might change our priority at the same moment.
3909 * We don't have to worry. Conceptually one call occurs first
3910 * and we have a single winner.
3912 if (increment
< -40)
3917 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
3923 if (increment
< 0 && !can_nice(current
, nice
))
3926 retval
= security_task_setnice(current
, nice
);
3930 set_user_nice(current
, nice
);
3937 * task_prio - return the priority value of a given task.
3938 * @p: the task in question.
3940 * This is the priority value as seen by users in /proc.
3941 * RT tasks are offset by -200. Normal tasks are centered
3942 * around 0, value goes from -16 to +15.
3944 int task_prio(const struct task_struct
*p
)
3946 return p
->prio
- MAX_RT_PRIO
;
3950 * task_nice - return the nice value of a given task.
3951 * @p: the task in question.
3953 int task_nice(const struct task_struct
*p
)
3955 return TASK_NICE(p
);
3957 EXPORT_SYMBOL_GPL(task_nice
);
3960 * idle_cpu - is a given cpu idle currently?
3961 * @cpu: the processor in question.
3963 int idle_cpu(int cpu
)
3965 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
3969 * idle_task - return the idle task for a given cpu.
3970 * @cpu: the processor in question.
3972 struct task_struct
*idle_task(int cpu
)
3974 return cpu_rq(cpu
)->idle
;
3978 * find_process_by_pid - find a process with a matching PID value.
3979 * @pid: the pid in question.
3981 static inline struct task_struct
*find_process_by_pid(pid_t pid
)
3983 return pid
? find_task_by_pid(pid
) : current
;
3986 /* Actually do priority change: must hold rq lock. */
3987 static void __setscheduler(struct task_struct
*p
, int policy
, int prio
)
3992 p
->rt_priority
= prio
;
3993 p
->normal_prio
= normal_prio(p
);
3994 /* we are holding p->pi_lock already */
3995 p
->prio
= rt_mutex_getprio(p
);
3997 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3999 if (policy
== SCHED_BATCH
)
4005 * sched_setscheduler - change the scheduling policy and/or RT priority of
4007 * @p: the task in question.
4008 * @policy: new policy.
4009 * @param: structure containing the new RT priority.
4011 int sched_setscheduler(struct task_struct
*p
, int policy
,
4012 struct sched_param
*param
)
4014 int retval
, oldprio
, oldpolicy
= -1;
4015 struct prio_array
*array
;
4016 unsigned long flags
;
4019 /* may grab non-irq protected spin_locks */
4020 BUG_ON(in_interrupt());
4022 /* double check policy once rq lock held */
4024 policy
= oldpolicy
= p
->policy
;
4025 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4026 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
)
4029 * Valid priorities for SCHED_FIFO and SCHED_RR are
4030 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4033 if (param
->sched_priority
< 0 ||
4034 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4035 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4037 if ((policy
== SCHED_NORMAL
|| policy
== SCHED_BATCH
)
4038 != (param
->sched_priority
== 0))
4042 * Allow unprivileged RT tasks to decrease priority:
4044 if (!capable(CAP_SYS_NICE
)) {
4046 * can't change policy, except between SCHED_NORMAL
4049 if (((policy
!= SCHED_NORMAL
&& p
->policy
!= SCHED_BATCH
) &&
4050 (policy
!= SCHED_BATCH
&& p
->policy
!= SCHED_NORMAL
)) &&
4051 !p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
)
4053 /* can't increase priority */
4054 if ((policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
) &&
4055 param
->sched_priority
> p
->rt_priority
&&
4056 param
->sched_priority
>
4057 p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
)
4059 /* can't change other user's priorities */
4060 if ((current
->euid
!= p
->euid
) &&
4061 (current
->euid
!= p
->uid
))
4065 retval
= security_task_setscheduler(p
, policy
, param
);
4069 * make sure no PI-waiters arrive (or leave) while we are
4070 * changing the priority of the task:
4072 spin_lock_irqsave(&p
->pi_lock
, flags
);
4074 * To be able to change p->policy safely, the apropriate
4075 * runqueue lock must be held.
4077 rq
= __task_rq_lock(p
);
4078 /* recheck policy now with rq lock held */
4079 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4080 policy
= oldpolicy
= -1;
4081 __task_rq_unlock(rq
);
4082 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4087 deactivate_task(p
, rq
);
4089 __setscheduler(p
, policy
, param
->sched_priority
);
4091 __activate_task(p
, rq
);
4093 * Reschedule if we are currently running on this runqueue and
4094 * our priority decreased, or if we are not currently running on
4095 * this runqueue and our priority is higher than the current's
4097 if (task_running(rq
, p
)) {
4098 if (p
->prio
> oldprio
)
4099 resched_task(rq
->curr
);
4100 } else if (TASK_PREEMPTS_CURR(p
, rq
))
4101 resched_task(rq
->curr
);
4103 __task_rq_unlock(rq
);
4104 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4106 rt_mutex_adjust_pi(p
);
4110 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4113 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4115 struct sched_param lparam
;
4116 struct task_struct
*p
;
4119 if (!param
|| pid
< 0)
4121 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4123 read_lock_irq(&tasklist_lock
);
4124 p
= find_process_by_pid(pid
);
4126 read_unlock_irq(&tasklist_lock
);
4130 read_unlock_irq(&tasklist_lock
);
4131 retval
= sched_setscheduler(p
, policy
, &lparam
);
4138 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4139 * @pid: the pid in question.
4140 * @policy: new policy.
4141 * @param: structure containing the new RT priority.
4143 asmlinkage
long sys_sched_setscheduler(pid_t pid
, int policy
,
4144 struct sched_param __user
*param
)
4146 /* negative values for policy are not valid */
4150 return do_sched_setscheduler(pid
, policy
, param
);
4154 * sys_sched_setparam - set/change the RT priority of a thread
4155 * @pid: the pid in question.
4156 * @param: structure containing the new RT priority.
4158 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4160 return do_sched_setscheduler(pid
, -1, param
);
4164 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4165 * @pid: the pid in question.
4167 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4169 struct task_struct
*p
;
4170 int retval
= -EINVAL
;
4176 read_lock(&tasklist_lock
);
4177 p
= find_process_by_pid(pid
);
4179 retval
= security_task_getscheduler(p
);
4183 read_unlock(&tasklist_lock
);
4190 * sys_sched_getscheduler - get the RT priority of a thread
4191 * @pid: the pid in question.
4192 * @param: structure containing the RT priority.
4194 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4196 struct sched_param lp
;
4197 struct task_struct
*p
;
4198 int retval
= -EINVAL
;
4200 if (!param
|| pid
< 0)
4203 read_lock(&tasklist_lock
);
4204 p
= find_process_by_pid(pid
);
4209 retval
= security_task_getscheduler(p
);
4213 lp
.sched_priority
= p
->rt_priority
;
4214 read_unlock(&tasklist_lock
);
4217 * This one might sleep, we cannot do it with a spinlock held ...
4219 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4225 read_unlock(&tasklist_lock
);
4229 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4231 cpumask_t cpus_allowed
;
4232 struct task_struct
*p
;
4236 read_lock(&tasklist_lock
);
4238 p
= find_process_by_pid(pid
);
4240 read_unlock(&tasklist_lock
);
4241 unlock_cpu_hotplug();
4246 * It is not safe to call set_cpus_allowed with the
4247 * tasklist_lock held. We will bump the task_struct's
4248 * usage count and then drop tasklist_lock.
4251 read_unlock(&tasklist_lock
);
4254 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4255 !capable(CAP_SYS_NICE
))
4258 retval
= security_task_setscheduler(p
, 0, NULL
);
4262 cpus_allowed
= cpuset_cpus_allowed(p
);
4263 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4264 retval
= set_cpus_allowed(p
, new_mask
);
4268 unlock_cpu_hotplug();
4272 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4273 cpumask_t
*new_mask
)
4275 if (len
< sizeof(cpumask_t
)) {
4276 memset(new_mask
, 0, sizeof(cpumask_t
));
4277 } else if (len
> sizeof(cpumask_t
)) {
4278 len
= sizeof(cpumask_t
);
4280 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4284 * sys_sched_setaffinity - set the cpu affinity of a process
4285 * @pid: pid of the process
4286 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4287 * @user_mask_ptr: user-space pointer to the new cpu mask
4289 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4290 unsigned long __user
*user_mask_ptr
)
4295 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4299 return sched_setaffinity(pid
, new_mask
);
4303 * Represents all cpu's present in the system
4304 * In systems capable of hotplug, this map could dynamically grow
4305 * as new cpu's are detected in the system via any platform specific
4306 * method, such as ACPI for e.g.
4309 cpumask_t cpu_present_map __read_mostly
;
4310 EXPORT_SYMBOL(cpu_present_map
);
4313 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4314 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4317 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4319 struct task_struct
*p
;
4323 read_lock(&tasklist_lock
);
4326 p
= find_process_by_pid(pid
);
4330 retval
= security_task_getscheduler(p
);
4334 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4337 read_unlock(&tasklist_lock
);
4338 unlock_cpu_hotplug();
4346 * sys_sched_getaffinity - get the cpu affinity of a process
4347 * @pid: pid of the process
4348 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4349 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4351 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4352 unsigned long __user
*user_mask_ptr
)
4357 if (len
< sizeof(cpumask_t
))
4360 ret
= sched_getaffinity(pid
, &mask
);
4364 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4367 return sizeof(cpumask_t
);
4371 * sys_sched_yield - yield the current processor to other threads.
4373 * this function yields the current CPU by moving the calling thread
4374 * to the expired array. If there are no other threads running on this
4375 * CPU then this function will return.
4377 asmlinkage
long sys_sched_yield(void)
4379 struct rq
*rq
= this_rq_lock();
4380 struct prio_array
*array
= current
->array
, *target
= rq
->expired
;
4382 schedstat_inc(rq
, yld_cnt
);
4384 * We implement yielding by moving the task into the expired
4387 * (special rule: RT tasks will just roundrobin in the active
4390 if (rt_task(current
))
4391 target
= rq
->active
;
4393 if (array
->nr_active
== 1) {
4394 schedstat_inc(rq
, yld_act_empty
);
4395 if (!rq
->expired
->nr_active
)
4396 schedstat_inc(rq
, yld_both_empty
);
4397 } else if (!rq
->expired
->nr_active
)
4398 schedstat_inc(rq
, yld_exp_empty
);
4400 if (array
!= target
) {
4401 dequeue_task(current
, array
);
4402 enqueue_task(current
, target
);
4405 * requeue_task is cheaper so perform that if possible.
4407 requeue_task(current
, array
);
4410 * Since we are going to call schedule() anyway, there's
4411 * no need to preempt or enable interrupts:
4413 __release(rq
->lock
);
4414 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4415 _raw_spin_unlock(&rq
->lock
);
4416 preempt_enable_no_resched();
4423 static inline int __resched_legal(void)
4425 if (unlikely(preempt_count()))
4427 if (unlikely(system_state
!= SYSTEM_RUNNING
))
4432 static void __cond_resched(void)
4434 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4435 __might_sleep(__FILE__
, __LINE__
);
4438 * The BKS might be reacquired before we have dropped
4439 * PREEMPT_ACTIVE, which could trigger a second
4440 * cond_resched() call.
4443 add_preempt_count(PREEMPT_ACTIVE
);
4445 sub_preempt_count(PREEMPT_ACTIVE
);
4446 } while (need_resched());
4449 int __sched
cond_resched(void)
4451 if (need_resched() && __resched_legal()) {
4457 EXPORT_SYMBOL(cond_resched
);
4460 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4461 * call schedule, and on return reacquire the lock.
4463 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4464 * operations here to prevent schedule() from being called twice (once via
4465 * spin_unlock(), once by hand).
4467 int cond_resched_lock(spinlock_t
*lock
)
4471 if (need_lockbreak(lock
)) {
4477 if (need_resched() && __resched_legal()) {
4478 spin_release(&lock
->dep_map
, 1, _THIS_IP_
);
4479 _raw_spin_unlock(lock
);
4480 preempt_enable_no_resched();
4487 EXPORT_SYMBOL(cond_resched_lock
);
4489 int __sched
cond_resched_softirq(void)
4491 BUG_ON(!in_softirq());
4493 if (need_resched() && __resched_legal()) {
4494 raw_local_irq_disable();
4496 raw_local_irq_enable();
4503 EXPORT_SYMBOL(cond_resched_softirq
);
4506 * yield - yield the current processor to other threads.
4508 * this is a shortcut for kernel-space yielding - it marks the
4509 * thread runnable and calls sys_sched_yield().
4511 void __sched
yield(void)
4513 set_current_state(TASK_RUNNING
);
4516 EXPORT_SYMBOL(yield
);
4519 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4520 * that process accounting knows that this is a task in IO wait state.
4522 * But don't do that if it is a deliberate, throttling IO wait (this task
4523 * has set its backing_dev_info: the queue against which it should throttle)
4525 void __sched
io_schedule(void)
4527 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
4529 atomic_inc(&rq
->nr_iowait
);
4531 atomic_dec(&rq
->nr_iowait
);
4533 EXPORT_SYMBOL(io_schedule
);
4535 long __sched
io_schedule_timeout(long timeout
)
4537 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
4540 atomic_inc(&rq
->nr_iowait
);
4541 ret
= schedule_timeout(timeout
);
4542 atomic_dec(&rq
->nr_iowait
);
4547 * sys_sched_get_priority_max - return maximum RT priority.
4548 * @policy: scheduling class.
4550 * this syscall returns the maximum rt_priority that can be used
4551 * by a given scheduling class.
4553 asmlinkage
long sys_sched_get_priority_max(int policy
)
4560 ret
= MAX_USER_RT_PRIO
-1;
4571 * sys_sched_get_priority_min - return minimum RT priority.
4572 * @policy: scheduling class.
4574 * this syscall returns the minimum rt_priority that can be used
4575 * by a given scheduling class.
4577 asmlinkage
long sys_sched_get_priority_min(int policy
)
4594 * sys_sched_rr_get_interval - return the default timeslice of a process.
4595 * @pid: pid of the process.
4596 * @interval: userspace pointer to the timeslice value.
4598 * this syscall writes the default timeslice value of a given process
4599 * into the user-space timespec buffer. A value of '0' means infinity.
4602 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
4604 struct task_struct
*p
;
4605 int retval
= -EINVAL
;
4612 read_lock(&tasklist_lock
);
4613 p
= find_process_by_pid(pid
);
4617 retval
= security_task_getscheduler(p
);
4621 jiffies_to_timespec(p
->policy
== SCHED_FIFO
?
4622 0 : task_timeslice(p
), &t
);
4623 read_unlock(&tasklist_lock
);
4624 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
4628 read_unlock(&tasklist_lock
);
4632 static inline struct task_struct
*eldest_child(struct task_struct
*p
)
4634 if (list_empty(&p
->children
))
4636 return list_entry(p
->children
.next
,struct task_struct
,sibling
);
4639 static inline struct task_struct
*older_sibling(struct task_struct
*p
)
4641 if (p
->sibling
.prev
==&p
->parent
->children
)
4643 return list_entry(p
->sibling
.prev
,struct task_struct
,sibling
);
4646 static inline struct task_struct
*younger_sibling(struct task_struct
*p
)
4648 if (p
->sibling
.next
==&p
->parent
->children
)
4650 return list_entry(p
->sibling
.next
,struct task_struct
,sibling
);
4653 static const char stat_nam
[] = "RSDTtZX";
4655 static void show_task(struct task_struct
*p
)
4657 struct task_struct
*relative
;
4658 unsigned long free
= 0;
4661 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
4662 printk("%-13.13s %c", p
->comm
,
4663 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
4664 #if (BITS_PER_LONG == 32)
4665 if (state
== TASK_RUNNING
)
4666 printk(" running ");
4668 printk(" %08lX ", thread_saved_pc(p
));
4670 if (state
== TASK_RUNNING
)
4671 printk(" running task ");
4673 printk(" %016lx ", thread_saved_pc(p
));
4675 #ifdef CONFIG_DEBUG_STACK_USAGE
4677 unsigned long *n
= end_of_stack(p
);
4680 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
4683 printk("%5lu %5d %6d ", free
, p
->pid
, p
->parent
->pid
);
4684 if ((relative
= eldest_child(p
)))
4685 printk("%5d ", relative
->pid
);
4688 if ((relative
= younger_sibling(p
)))
4689 printk("%7d", relative
->pid
);
4692 if ((relative
= older_sibling(p
)))
4693 printk(" %5d", relative
->pid
);
4697 printk(" (L-TLB)\n");
4699 printk(" (NOTLB)\n");
4701 if (state
!= TASK_RUNNING
)
4702 show_stack(p
, NULL
);
4705 void show_state(void)
4707 struct task_struct
*g
, *p
;
4709 #if (BITS_PER_LONG == 32)
4712 printk(" task PC pid father child younger older\n");
4716 printk(" task PC pid father child younger older\n");
4718 read_lock(&tasklist_lock
);
4719 do_each_thread(g
, p
) {
4721 * reset the NMI-timeout, listing all files on a slow
4722 * console might take alot of time:
4724 touch_nmi_watchdog();
4726 } while_each_thread(g
, p
);
4728 read_unlock(&tasklist_lock
);
4729 debug_show_all_locks();
4733 * init_idle - set up an idle thread for a given CPU
4734 * @idle: task in question
4735 * @cpu: cpu the idle task belongs to
4737 * NOTE: this function does not set the idle thread's NEED_RESCHED
4738 * flag, to make booting more robust.
4740 void __devinit
init_idle(struct task_struct
*idle
, int cpu
)
4742 struct rq
*rq
= cpu_rq(cpu
);
4743 unsigned long flags
;
4745 idle
->timestamp
= sched_clock();
4746 idle
->sleep_avg
= 0;
4748 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
4749 idle
->state
= TASK_RUNNING
;
4750 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
4751 set_task_cpu(idle
, cpu
);
4753 spin_lock_irqsave(&rq
->lock
, flags
);
4754 rq
->curr
= rq
->idle
= idle
;
4755 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4758 spin_unlock_irqrestore(&rq
->lock
, flags
);
4760 /* Set the preempt count _outside_ the spinlocks! */
4761 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4762 task_thread_info(idle
)->preempt_count
= (idle
->lock_depth
>= 0);
4764 task_thread_info(idle
)->preempt_count
= 0;
4769 * In a system that switches off the HZ timer nohz_cpu_mask
4770 * indicates which cpus entered this state. This is used
4771 * in the rcu update to wait only for active cpus. For system
4772 * which do not switch off the HZ timer nohz_cpu_mask should
4773 * always be CPU_MASK_NONE.
4775 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
4779 * This is how migration works:
4781 * 1) we queue a struct migration_req structure in the source CPU's
4782 * runqueue and wake up that CPU's migration thread.
4783 * 2) we down() the locked semaphore => thread blocks.
4784 * 3) migration thread wakes up (implicitly it forces the migrated
4785 * thread off the CPU)
4786 * 4) it gets the migration request and checks whether the migrated
4787 * task is still in the wrong runqueue.
4788 * 5) if it's in the wrong runqueue then the migration thread removes
4789 * it and puts it into the right queue.
4790 * 6) migration thread up()s the semaphore.
4791 * 7) we wake up and the migration is done.
4795 * Change a given task's CPU affinity. Migrate the thread to a
4796 * proper CPU and schedule it away if the CPU it's executing on
4797 * is removed from the allowed bitmask.
4799 * NOTE: the caller must have a valid reference to the task, the
4800 * task must not exit() & deallocate itself prematurely. The
4801 * call is not atomic; no spinlocks may be held.
4803 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
4805 struct migration_req req
;
4806 unsigned long flags
;
4810 rq
= task_rq_lock(p
, &flags
);
4811 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
4816 p
->cpus_allowed
= new_mask
;
4817 /* Can the task run on the task's current CPU? If so, we're done */
4818 if (cpu_isset(task_cpu(p
), new_mask
))
4821 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
4822 /* Need help from migration thread: drop lock and wait. */
4823 task_rq_unlock(rq
, &flags
);
4824 wake_up_process(rq
->migration_thread
);
4825 wait_for_completion(&req
.done
);
4826 tlb_migrate_finish(p
->mm
);
4830 task_rq_unlock(rq
, &flags
);
4834 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
4837 * Move (not current) task off this cpu, onto dest cpu. We're doing
4838 * this because either it can't run here any more (set_cpus_allowed()
4839 * away from this CPU, or CPU going down), or because we're
4840 * attempting to rebalance this task on exec (sched_exec).
4842 * So we race with normal scheduler movements, but that's OK, as long
4843 * as the task is no longer on this CPU.
4845 * Returns non-zero if task was successfully migrated.
4847 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
4849 struct rq
*rq_dest
, *rq_src
;
4852 if (unlikely(cpu_is_offline(dest_cpu
)))
4855 rq_src
= cpu_rq(src_cpu
);
4856 rq_dest
= cpu_rq(dest_cpu
);
4858 double_rq_lock(rq_src
, rq_dest
);
4859 /* Already moved. */
4860 if (task_cpu(p
) != src_cpu
)
4862 /* Affinity changed (again). */
4863 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
4866 set_task_cpu(p
, dest_cpu
);
4869 * Sync timestamp with rq_dest's before activating.
4870 * The same thing could be achieved by doing this step
4871 * afterwards, and pretending it was a local activate.
4872 * This way is cleaner and logically correct.
4874 p
->timestamp
= p
->timestamp
- rq_src
->timestamp_last_tick
4875 + rq_dest
->timestamp_last_tick
;
4876 deactivate_task(p
, rq_src
);
4877 __activate_task(p
, rq_dest
);
4878 if (TASK_PREEMPTS_CURR(p
, rq_dest
))
4879 resched_task(rq_dest
->curr
);
4883 double_rq_unlock(rq_src
, rq_dest
);
4888 * migration_thread - this is a highprio system thread that performs
4889 * thread migration by bumping thread off CPU then 'pushing' onto
4892 static int migration_thread(void *data
)
4894 int cpu
= (long)data
;
4898 BUG_ON(rq
->migration_thread
!= current
);
4900 set_current_state(TASK_INTERRUPTIBLE
);
4901 while (!kthread_should_stop()) {
4902 struct migration_req
*req
;
4903 struct list_head
*head
;
4907 spin_lock_irq(&rq
->lock
);
4909 if (cpu_is_offline(cpu
)) {
4910 spin_unlock_irq(&rq
->lock
);
4914 if (rq
->active_balance
) {
4915 active_load_balance(rq
, cpu
);
4916 rq
->active_balance
= 0;
4919 head
= &rq
->migration_queue
;
4921 if (list_empty(head
)) {
4922 spin_unlock_irq(&rq
->lock
);
4924 set_current_state(TASK_INTERRUPTIBLE
);
4927 req
= list_entry(head
->next
, struct migration_req
, list
);
4928 list_del_init(head
->next
);
4930 spin_unlock(&rq
->lock
);
4931 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
4934 complete(&req
->done
);
4936 __set_current_state(TASK_RUNNING
);
4940 /* Wait for kthread_stop */
4941 set_current_state(TASK_INTERRUPTIBLE
);
4942 while (!kthread_should_stop()) {
4944 set_current_state(TASK_INTERRUPTIBLE
);
4946 __set_current_state(TASK_RUNNING
);
4950 #ifdef CONFIG_HOTPLUG_CPU
4951 /* Figure out where task on dead CPU should go, use force if neccessary. */
4952 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
4954 unsigned long flags
;
4961 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
4962 cpus_and(mask
, mask
, p
->cpus_allowed
);
4963 dest_cpu
= any_online_cpu(mask
);
4965 /* On any allowed CPU? */
4966 if (dest_cpu
== NR_CPUS
)
4967 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
4969 /* No more Mr. Nice Guy. */
4970 if (dest_cpu
== NR_CPUS
) {
4971 rq
= task_rq_lock(p
, &flags
);
4972 cpus_setall(p
->cpus_allowed
);
4973 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
4974 task_rq_unlock(rq
, &flags
);
4977 * Don't tell them about moving exiting tasks or
4978 * kernel threads (both mm NULL), since they never
4981 if (p
->mm
&& printk_ratelimit())
4982 printk(KERN_INFO
"process %d (%s) no "
4983 "longer affine to cpu%d\n",
4984 p
->pid
, p
->comm
, dead_cpu
);
4986 if (!__migrate_task(p
, dead_cpu
, dest_cpu
))
4991 * While a dead CPU has no uninterruptible tasks queued at this point,
4992 * it might still have a nonzero ->nr_uninterruptible counter, because
4993 * for performance reasons the counter is not stricly tracking tasks to
4994 * their home CPUs. So we just add the counter to another CPU's counter,
4995 * to keep the global sum constant after CPU-down:
4997 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
4999 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5000 unsigned long flags
;
5002 local_irq_save(flags
);
5003 double_rq_lock(rq_src
, rq_dest
);
5004 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5005 rq_src
->nr_uninterruptible
= 0;
5006 double_rq_unlock(rq_src
, rq_dest
);
5007 local_irq_restore(flags
);
5010 /* Run through task list and migrate tasks from the dead cpu. */
5011 static void migrate_live_tasks(int src_cpu
)
5013 struct task_struct
*p
, *t
;
5015 write_lock_irq(&tasklist_lock
);
5017 do_each_thread(t
, p
) {
5021 if (task_cpu(p
) == src_cpu
)
5022 move_task_off_dead_cpu(src_cpu
, p
);
5023 } while_each_thread(t
, p
);
5025 write_unlock_irq(&tasklist_lock
);
5028 /* Schedules idle task to be the next runnable task on current CPU.
5029 * It does so by boosting its priority to highest possible and adding it to
5030 * the _front_ of the runqueue. Used by CPU offline code.
5032 void sched_idle_next(void)
5034 int this_cpu
= smp_processor_id();
5035 struct rq
*rq
= cpu_rq(this_cpu
);
5036 struct task_struct
*p
= rq
->idle
;
5037 unsigned long flags
;
5039 /* cpu has to be offline */
5040 BUG_ON(cpu_online(this_cpu
));
5043 * Strictly not necessary since rest of the CPUs are stopped by now
5044 * and interrupts disabled on the current cpu.
5046 spin_lock_irqsave(&rq
->lock
, flags
);
5048 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5050 /* Add idle task to the _front_ of its priority queue: */
5051 __activate_idle_task(p
, rq
);
5053 spin_unlock_irqrestore(&rq
->lock
, flags
);
5057 * Ensures that the idle task is using init_mm right before its cpu goes
5060 void idle_task_exit(void)
5062 struct mm_struct
*mm
= current
->active_mm
;
5064 BUG_ON(cpu_online(smp_processor_id()));
5067 switch_mm(mm
, &init_mm
, current
);
5071 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5073 struct rq
*rq
= cpu_rq(dead_cpu
);
5075 /* Must be exiting, otherwise would be on tasklist. */
5076 BUG_ON(p
->exit_state
!= EXIT_ZOMBIE
&& p
->exit_state
!= EXIT_DEAD
);
5078 /* Cannot have done final schedule yet: would have vanished. */
5079 BUG_ON(p
->flags
& PF_DEAD
);
5084 * Drop lock around migration; if someone else moves it,
5085 * that's OK. No task can be added to this CPU, so iteration is
5088 spin_unlock_irq(&rq
->lock
);
5089 move_task_off_dead_cpu(dead_cpu
, p
);
5090 spin_lock_irq(&rq
->lock
);
5095 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5096 static void migrate_dead_tasks(unsigned int dead_cpu
)
5098 struct rq
*rq
= cpu_rq(dead_cpu
);
5099 unsigned int arr
, i
;
5101 for (arr
= 0; arr
< 2; arr
++) {
5102 for (i
= 0; i
< MAX_PRIO
; i
++) {
5103 struct list_head
*list
= &rq
->arrays
[arr
].queue
[i
];
5105 while (!list_empty(list
))
5106 migrate_dead(dead_cpu
, list_entry(list
->next
,
5107 struct task_struct
, run_list
));
5111 #endif /* CONFIG_HOTPLUG_CPU */
5114 * migration_call - callback that gets triggered when a CPU is added.
5115 * Here we can start up the necessary migration thread for the new CPU.
5117 static int __cpuinit
5118 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5120 struct task_struct
*p
;
5121 int cpu
= (long)hcpu
;
5122 unsigned long flags
;
5126 case CPU_UP_PREPARE
:
5127 p
= kthread_create(migration_thread
, hcpu
, "migration/%d",cpu
);
5130 p
->flags
|= PF_NOFREEZE
;
5131 kthread_bind(p
, cpu
);
5132 /* Must be high prio: stop_machine expects to yield to it. */
5133 rq
= task_rq_lock(p
, &flags
);
5134 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5135 task_rq_unlock(rq
, &flags
);
5136 cpu_rq(cpu
)->migration_thread
= p
;
5140 /* Strictly unneccessary, as first user will wake it. */
5141 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5144 #ifdef CONFIG_HOTPLUG_CPU
5145 case CPU_UP_CANCELED
:
5146 if (!cpu_rq(cpu
)->migration_thread
)
5148 /* Unbind it from offline cpu so it can run. Fall thru. */
5149 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5150 any_online_cpu(cpu_online_map
));
5151 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5152 cpu_rq(cpu
)->migration_thread
= NULL
;
5156 migrate_live_tasks(cpu
);
5158 kthread_stop(rq
->migration_thread
);
5159 rq
->migration_thread
= NULL
;
5160 /* Idle task back to normal (off runqueue, low prio) */
5161 rq
= task_rq_lock(rq
->idle
, &flags
);
5162 deactivate_task(rq
->idle
, rq
);
5163 rq
->idle
->static_prio
= MAX_PRIO
;
5164 __setscheduler(rq
->idle
, SCHED_NORMAL
, 0);
5165 migrate_dead_tasks(cpu
);
5166 task_rq_unlock(rq
, &flags
);
5167 migrate_nr_uninterruptible(rq
);
5168 BUG_ON(rq
->nr_running
!= 0);
5170 /* No need to migrate the tasks: it was best-effort if
5171 * they didn't do lock_cpu_hotplug(). Just wake up
5172 * the requestors. */
5173 spin_lock_irq(&rq
->lock
);
5174 while (!list_empty(&rq
->migration_queue
)) {
5175 struct migration_req
*req
;
5177 req
= list_entry(rq
->migration_queue
.next
,
5178 struct migration_req
, list
);
5179 list_del_init(&req
->list
);
5180 complete(&req
->done
);
5182 spin_unlock_irq(&rq
->lock
);
5189 /* Register at highest priority so that task migration (migrate_all_tasks)
5190 * happens before everything else.
5192 static struct notifier_block __cpuinitdata migration_notifier
= {
5193 .notifier_call
= migration_call
,
5197 int __init
migration_init(void)
5199 void *cpu
= (void *)(long)smp_processor_id();
5201 /* Start one for the boot CPU: */
5202 migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5203 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5204 register_cpu_notifier(&migration_notifier
);
5211 #undef SCHED_DOMAIN_DEBUG
5212 #ifdef SCHED_DOMAIN_DEBUG
5213 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
5218 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
5222 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
5227 struct sched_group
*group
= sd
->groups
;
5228 cpumask_t groupmask
;
5230 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
5231 cpus_clear(groupmask
);
5234 for (i
= 0; i
< level
+ 1; i
++)
5236 printk("domain %d: ", level
);
5238 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5239 printk("does not load-balance\n");
5241 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain has parent");
5245 printk("span %s\n", str
);
5247 if (!cpu_isset(cpu
, sd
->span
))
5248 printk(KERN_ERR
"ERROR: domain->span does not contain CPU%d\n", cpu
);
5249 if (!cpu_isset(cpu
, group
->cpumask
))
5250 printk(KERN_ERR
"ERROR: domain->groups does not contain CPU%d\n", cpu
);
5253 for (i
= 0; i
< level
+ 2; i
++)
5259 printk(KERN_ERR
"ERROR: group is NULL\n");
5263 if (!group
->cpu_power
) {
5265 printk(KERN_ERR
"ERROR: domain->cpu_power not set\n");
5268 if (!cpus_weight(group
->cpumask
)) {
5270 printk(KERN_ERR
"ERROR: empty group\n");
5273 if (cpus_intersects(groupmask
, group
->cpumask
)) {
5275 printk(KERN_ERR
"ERROR: repeated CPUs\n");
5278 cpus_or(groupmask
, groupmask
, group
->cpumask
);
5280 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
5283 group
= group
->next
;
5284 } while (group
!= sd
->groups
);
5287 if (!cpus_equal(sd
->span
, groupmask
))
5288 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
5294 if (!cpus_subset(groupmask
, sd
->span
))
5295 printk(KERN_ERR
"ERROR: parent span is not a superset of domain->span\n");
5301 # define sched_domain_debug(sd, cpu) do { } while (0)
5304 static int sd_degenerate(struct sched_domain
*sd
)
5306 if (cpus_weight(sd
->span
) == 1)
5309 /* Following flags need at least 2 groups */
5310 if (sd
->flags
& (SD_LOAD_BALANCE
|
5311 SD_BALANCE_NEWIDLE
|
5314 if (sd
->groups
!= sd
->groups
->next
)
5318 /* Following flags don't use groups */
5319 if (sd
->flags
& (SD_WAKE_IDLE
|
5328 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
5330 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
5332 if (sd_degenerate(parent
))
5335 if (!cpus_equal(sd
->span
, parent
->span
))
5338 /* Does parent contain flags not in child? */
5339 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5340 if (cflags
& SD_WAKE_AFFINE
)
5341 pflags
&= ~SD_WAKE_BALANCE
;
5342 /* Flags needing groups don't count if only 1 group in parent */
5343 if (parent
->groups
== parent
->groups
->next
) {
5344 pflags
&= ~(SD_LOAD_BALANCE
|
5345 SD_BALANCE_NEWIDLE
|
5349 if (~cflags
& pflags
)
5356 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5357 * hold the hotplug lock.
5359 static void cpu_attach_domain(struct sched_domain
*sd
, int cpu
)
5361 struct rq
*rq
= cpu_rq(cpu
);
5362 struct sched_domain
*tmp
;
5364 /* Remove the sched domains which do not contribute to scheduling. */
5365 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
5366 struct sched_domain
*parent
= tmp
->parent
;
5369 if (sd_parent_degenerate(tmp
, parent
))
5370 tmp
->parent
= parent
->parent
;
5373 if (sd
&& sd_degenerate(sd
))
5376 sched_domain_debug(sd
, cpu
);
5378 rcu_assign_pointer(rq
->sd
, sd
);
5381 /* cpus with isolated domains */
5382 static cpumask_t __devinitdata cpu_isolated_map
= CPU_MASK_NONE
;
5384 /* Setup the mask of cpus configured for isolated domains */
5385 static int __init
isolated_cpu_setup(char *str
)
5387 int ints
[NR_CPUS
], i
;
5389 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
5390 cpus_clear(cpu_isolated_map
);
5391 for (i
= 1; i
<= ints
[0]; i
++)
5392 if (ints
[i
] < NR_CPUS
)
5393 cpu_set(ints
[i
], cpu_isolated_map
);
5397 __setup ("isolcpus=", isolated_cpu_setup
);
5400 * init_sched_build_groups takes an array of groups, the cpumask we wish
5401 * to span, and a pointer to a function which identifies what group a CPU
5402 * belongs to. The return value of group_fn must be a valid index into the
5403 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5404 * keep track of groups covered with a cpumask_t).
5406 * init_sched_build_groups will build a circular linked list of the groups
5407 * covered by the given span, and will set each group's ->cpumask correctly,
5408 * and ->cpu_power to 0.
5410 static void init_sched_build_groups(struct sched_group groups
[], cpumask_t span
,
5411 int (*group_fn
)(int cpu
))
5413 struct sched_group
*first
= NULL
, *last
= NULL
;
5414 cpumask_t covered
= CPU_MASK_NONE
;
5417 for_each_cpu_mask(i
, span
) {
5418 int group
= group_fn(i
);
5419 struct sched_group
*sg
= &groups
[group
];
5422 if (cpu_isset(i
, covered
))
5425 sg
->cpumask
= CPU_MASK_NONE
;
5428 for_each_cpu_mask(j
, span
) {
5429 if (group_fn(j
) != group
)
5432 cpu_set(j
, covered
);
5433 cpu_set(j
, sg
->cpumask
);
5444 #define SD_NODES_PER_DOMAIN 16
5447 * Self-tuning task migration cost measurement between source and target CPUs.
5449 * This is done by measuring the cost of manipulating buffers of varying
5450 * sizes. For a given buffer-size here are the steps that are taken:
5452 * 1) the source CPU reads+dirties a shared buffer
5453 * 2) the target CPU reads+dirties the same shared buffer
5455 * We measure how long they take, in the following 4 scenarios:
5457 * - source: CPU1, target: CPU2 | cost1
5458 * - source: CPU2, target: CPU1 | cost2
5459 * - source: CPU1, target: CPU1 | cost3
5460 * - source: CPU2, target: CPU2 | cost4
5462 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5463 * the cost of migration.
5465 * We then start off from a small buffer-size and iterate up to larger
5466 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5467 * doing a maximum search for the cost. (The maximum cost for a migration
5468 * normally occurs when the working set size is around the effective cache
5471 #define SEARCH_SCOPE 2
5472 #define MIN_CACHE_SIZE (64*1024U)
5473 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5474 #define ITERATIONS 1
5475 #define SIZE_THRESH 130
5476 #define COST_THRESH 130
5479 * The migration cost is a function of 'domain distance'. Domain
5480 * distance is the number of steps a CPU has to iterate down its
5481 * domain tree to share a domain with the other CPU. The farther
5482 * two CPUs are from each other, the larger the distance gets.
5484 * Note that we use the distance only to cache measurement results,
5485 * the distance value is not used numerically otherwise. When two
5486 * CPUs have the same distance it is assumed that the migration
5487 * cost is the same. (this is a simplification but quite practical)
5489 #define MAX_DOMAIN_DISTANCE 32
5491 static unsigned long long migration_cost
[MAX_DOMAIN_DISTANCE
] =
5492 { [ 0 ... MAX_DOMAIN_DISTANCE
-1 ] =
5494 * Architectures may override the migration cost and thus avoid
5495 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5496 * virtualized hardware:
5498 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5499 CONFIG_DEFAULT_MIGRATION_COST
5506 * Allow override of migration cost - in units of microseconds.
5507 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5508 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5510 static int __init
migration_cost_setup(char *str
)
5512 int ints
[MAX_DOMAIN_DISTANCE
+1], i
;
5514 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
5516 printk("#ints: %d\n", ints
[0]);
5517 for (i
= 1; i
<= ints
[0]; i
++) {
5518 migration_cost
[i
-1] = (unsigned long long)ints
[i
]*1000;
5519 printk("migration_cost[%d]: %Ld\n", i
-1, migration_cost
[i
-1]);
5524 __setup ("migration_cost=", migration_cost_setup
);
5527 * Global multiplier (divisor) for migration-cutoff values,
5528 * in percentiles. E.g. use a value of 150 to get 1.5 times
5529 * longer cache-hot cutoff times.
5531 * (We scale it from 100 to 128 to long long handling easier.)
5534 #define MIGRATION_FACTOR_SCALE 128
5536 static unsigned int migration_factor
= MIGRATION_FACTOR_SCALE
;
5538 static int __init
setup_migration_factor(char *str
)
5540 get_option(&str
, &migration_factor
);
5541 migration_factor
= migration_factor
* MIGRATION_FACTOR_SCALE
/ 100;
5545 __setup("migration_factor=", setup_migration_factor
);
5548 * Estimated distance of two CPUs, measured via the number of domains
5549 * we have to pass for the two CPUs to be in the same span:
5551 static unsigned long domain_distance(int cpu1
, int cpu2
)
5553 unsigned long distance
= 0;
5554 struct sched_domain
*sd
;
5556 for_each_domain(cpu1
, sd
) {
5557 WARN_ON(!cpu_isset(cpu1
, sd
->span
));
5558 if (cpu_isset(cpu2
, sd
->span
))
5562 if (distance
>= MAX_DOMAIN_DISTANCE
) {
5564 distance
= MAX_DOMAIN_DISTANCE
-1;
5570 static unsigned int migration_debug
;
5572 static int __init
setup_migration_debug(char *str
)
5574 get_option(&str
, &migration_debug
);
5578 __setup("migration_debug=", setup_migration_debug
);
5581 * Maximum cache-size that the scheduler should try to measure.
5582 * Architectures with larger caches should tune this up during
5583 * bootup. Gets used in the domain-setup code (i.e. during SMP
5586 unsigned int max_cache_size
;
5588 static int __init
setup_max_cache_size(char *str
)
5590 get_option(&str
, &max_cache_size
);
5594 __setup("max_cache_size=", setup_max_cache_size
);
5597 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5598 * is the operation that is timed, so we try to generate unpredictable
5599 * cachemisses that still end up filling the L2 cache:
5601 static void touch_cache(void *__cache
, unsigned long __size
)
5603 unsigned long size
= __size
/sizeof(long), chunk1
= size
/3,
5605 unsigned long *cache
= __cache
;
5608 for (i
= 0; i
< size
/6; i
+= 8) {
5611 case 1: cache
[size
-1-i
]++;
5612 case 2: cache
[chunk1
-i
]++;
5613 case 3: cache
[chunk1
+i
]++;
5614 case 4: cache
[chunk2
-i
]++;
5615 case 5: cache
[chunk2
+i
]++;
5621 * Measure the cache-cost of one task migration. Returns in units of nsec.
5623 static unsigned long long
5624 measure_one(void *cache
, unsigned long size
, int source
, int target
)
5626 cpumask_t mask
, saved_mask
;
5627 unsigned long long t0
, t1
, t2
, t3
, cost
;
5629 saved_mask
= current
->cpus_allowed
;
5632 * Flush source caches to RAM and invalidate them:
5637 * Migrate to the source CPU:
5639 mask
= cpumask_of_cpu(source
);
5640 set_cpus_allowed(current
, mask
);
5641 WARN_ON(smp_processor_id() != source
);
5644 * Dirty the working set:
5647 touch_cache(cache
, size
);
5651 * Migrate to the target CPU, dirty the L2 cache and access
5652 * the shared buffer. (which represents the working set
5653 * of a migrated task.)
5655 mask
= cpumask_of_cpu(target
);
5656 set_cpus_allowed(current
, mask
);
5657 WARN_ON(smp_processor_id() != target
);
5660 touch_cache(cache
, size
);
5663 cost
= t1
-t0
+ t3
-t2
;
5665 if (migration_debug
>= 2)
5666 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5667 source
, target
, t1
-t0
, t1
-t0
, t3
-t2
, cost
);
5669 * Flush target caches to RAM and invalidate them:
5673 set_cpus_allowed(current
, saved_mask
);
5679 * Measure a series of task migrations and return the average
5680 * result. Since this code runs early during bootup the system
5681 * is 'undisturbed' and the average latency makes sense.
5683 * The algorithm in essence auto-detects the relevant cache-size,
5684 * so it will properly detect different cachesizes for different
5685 * cache-hierarchies, depending on how the CPUs are connected.
5687 * Architectures can prime the upper limit of the search range via
5688 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5690 static unsigned long long
5691 measure_cost(int cpu1
, int cpu2
, void *cache
, unsigned int size
)
5693 unsigned long long cost1
, cost2
;
5697 * Measure the migration cost of 'size' bytes, over an
5698 * average of 10 runs:
5700 * (We perturb the cache size by a small (0..4k)
5701 * value to compensate size/alignment related artifacts.
5702 * We also subtract the cost of the operation done on
5708 * dry run, to make sure we start off cache-cold on cpu1,
5709 * and to get any vmalloc pagefaults in advance:
5711 measure_one(cache
, size
, cpu1
, cpu2
);
5712 for (i
= 0; i
< ITERATIONS
; i
++)
5713 cost1
+= measure_one(cache
, size
- i
*1024, cpu1
, cpu2
);
5715 measure_one(cache
, size
, cpu2
, cpu1
);
5716 for (i
= 0; i
< ITERATIONS
; i
++)
5717 cost1
+= measure_one(cache
, size
- i
*1024, cpu2
, cpu1
);
5720 * (We measure the non-migrating [cached] cost on both
5721 * cpu1 and cpu2, to handle CPUs with different speeds)
5725 measure_one(cache
, size
, cpu1
, cpu1
);
5726 for (i
= 0; i
< ITERATIONS
; i
++)
5727 cost2
+= measure_one(cache
, size
- i
*1024, cpu1
, cpu1
);
5729 measure_one(cache
, size
, cpu2
, cpu2
);
5730 for (i
= 0; i
< ITERATIONS
; i
++)
5731 cost2
+= measure_one(cache
, size
- i
*1024, cpu2
, cpu2
);
5734 * Get the per-iteration migration cost:
5736 do_div(cost1
, 2*ITERATIONS
);
5737 do_div(cost2
, 2*ITERATIONS
);
5739 return cost1
- cost2
;
5742 static unsigned long long measure_migration_cost(int cpu1
, int cpu2
)
5744 unsigned long long max_cost
= 0, fluct
= 0, avg_fluct
= 0;
5745 unsigned int max_size
, size
, size_found
= 0;
5746 long long cost
= 0, prev_cost
;
5750 * Search from max_cache_size*5 down to 64K - the real relevant
5751 * cachesize has to lie somewhere inbetween.
5753 if (max_cache_size
) {
5754 max_size
= max(max_cache_size
* SEARCH_SCOPE
, MIN_CACHE_SIZE
);
5755 size
= max(max_cache_size
/ SEARCH_SCOPE
, MIN_CACHE_SIZE
);
5758 * Since we have no estimation about the relevant
5761 max_size
= DEFAULT_CACHE_SIZE
* SEARCH_SCOPE
;
5762 size
= MIN_CACHE_SIZE
;
5765 if (!cpu_online(cpu1
) || !cpu_online(cpu2
)) {
5766 printk("cpu %d and %d not both online!\n", cpu1
, cpu2
);
5771 * Allocate the working set:
5773 cache
= vmalloc(max_size
);
5775 printk("could not vmalloc %d bytes for cache!\n", 2*max_size
);
5776 return 1000000; /* return 1 msec on very small boxen */
5779 while (size
<= max_size
) {
5781 cost
= measure_cost(cpu1
, cpu2
, cache
, size
);
5787 if (max_cost
< cost
) {
5793 * Calculate average fluctuation, we use this to prevent
5794 * noise from triggering an early break out of the loop:
5796 fluct
= abs(cost
- prev_cost
);
5797 avg_fluct
= (avg_fluct
+ fluct
)/2;
5799 if (migration_debug
)
5800 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5802 (long)cost
/ 1000000,
5803 ((long)cost
/ 100000) % 10,
5804 (long)max_cost
/ 1000000,
5805 ((long)max_cost
/ 100000) % 10,
5806 domain_distance(cpu1
, cpu2
),
5810 * If we iterated at least 20% past the previous maximum,
5811 * and the cost has dropped by more than 20% already,
5812 * (taking fluctuations into account) then we assume to
5813 * have found the maximum and break out of the loop early:
5815 if (size_found
&& (size
*100 > size_found
*SIZE_THRESH
))
5816 if (cost
+avg_fluct
<= 0 ||
5817 max_cost
*100 > (cost
+avg_fluct
)*COST_THRESH
) {
5819 if (migration_debug
)
5820 printk("-> found max.\n");
5824 * Increase the cachesize in 10% steps:
5826 size
= size
* 10 / 9;
5829 if (migration_debug
)
5830 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5831 cpu1
, cpu2
, size_found
, max_cost
);
5836 * A task is considered 'cache cold' if at least 2 times
5837 * the worst-case cost of migration has passed.
5839 * (this limit is only listened to if the load-balancing
5840 * situation is 'nice' - if there is a large imbalance we
5841 * ignore it for the sake of CPU utilization and
5842 * processing fairness.)
5844 return 2 * max_cost
* migration_factor
/ MIGRATION_FACTOR_SCALE
;
5847 static void calibrate_migration_costs(const cpumask_t
*cpu_map
)
5849 int cpu1
= -1, cpu2
= -1, cpu
, orig_cpu
= raw_smp_processor_id();
5850 unsigned long j0
, j1
, distance
, max_distance
= 0;
5851 struct sched_domain
*sd
;
5856 * First pass - calculate the cacheflush times:
5858 for_each_cpu_mask(cpu1
, *cpu_map
) {
5859 for_each_cpu_mask(cpu2
, *cpu_map
) {
5862 distance
= domain_distance(cpu1
, cpu2
);
5863 max_distance
= max(max_distance
, distance
);
5865 * No result cached yet?
5867 if (migration_cost
[distance
] == -1LL)
5868 migration_cost
[distance
] =
5869 measure_migration_cost(cpu1
, cpu2
);
5873 * Second pass - update the sched domain hierarchy with
5874 * the new cache-hot-time estimations:
5876 for_each_cpu_mask(cpu
, *cpu_map
) {
5878 for_each_domain(cpu
, sd
) {
5879 sd
->cache_hot_time
= migration_cost
[distance
];
5886 if (migration_debug
)
5887 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5895 if (system_state
== SYSTEM_BOOTING
) {
5896 printk("migration_cost=");
5897 for (distance
= 0; distance
<= max_distance
; distance
++) {
5900 printk("%ld", (long)migration_cost
[distance
] / 1000);
5905 if (migration_debug
)
5906 printk("migration: %ld seconds\n", (j1
-j0
)/HZ
);
5909 * Move back to the original CPU. NUMA-Q gets confused
5910 * if we migrate to another quad during bootup.
5912 if (raw_smp_processor_id() != orig_cpu
) {
5913 cpumask_t mask
= cpumask_of_cpu(orig_cpu
),
5914 saved_mask
= current
->cpus_allowed
;
5916 set_cpus_allowed(current
, mask
);
5917 set_cpus_allowed(current
, saved_mask
);
5924 * find_next_best_node - find the next node to include in a sched_domain
5925 * @node: node whose sched_domain we're building
5926 * @used_nodes: nodes already in the sched_domain
5928 * Find the next node to include in a given scheduling domain. Simply
5929 * finds the closest node not already in the @used_nodes map.
5931 * Should use nodemask_t.
5933 static int find_next_best_node(int node
, unsigned long *used_nodes
)
5935 int i
, n
, val
, min_val
, best_node
= 0;
5939 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
5940 /* Start at @node */
5941 n
= (node
+ i
) % MAX_NUMNODES
;
5943 if (!nr_cpus_node(n
))
5946 /* Skip already used nodes */
5947 if (test_bit(n
, used_nodes
))
5950 /* Simple min distance search */
5951 val
= node_distance(node
, n
);
5953 if (val
< min_val
) {
5959 set_bit(best_node
, used_nodes
);
5964 * sched_domain_node_span - get a cpumask for a node's sched_domain
5965 * @node: node whose cpumask we're constructing
5966 * @size: number of nodes to include in this span
5968 * Given a node, construct a good cpumask for its sched_domain to span. It
5969 * should be one that prevents unnecessary balancing, but also spreads tasks
5972 static cpumask_t
sched_domain_node_span(int node
)
5974 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
5975 cpumask_t span
, nodemask
;
5979 bitmap_zero(used_nodes
, MAX_NUMNODES
);
5981 nodemask
= node_to_cpumask(node
);
5982 cpus_or(span
, span
, nodemask
);
5983 set_bit(node
, used_nodes
);
5985 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
5986 int next_node
= find_next_best_node(node
, used_nodes
);
5988 nodemask
= node_to_cpumask(next_node
);
5989 cpus_or(span
, span
, nodemask
);
5996 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
5999 * SMT sched-domains:
6001 #ifdef CONFIG_SCHED_SMT
6002 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6003 static struct sched_group sched_group_cpus
[NR_CPUS
];
6005 static int cpu_to_cpu_group(int cpu
)
6012 * multi-core sched-domains:
6014 #ifdef CONFIG_SCHED_MC
6015 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6016 static struct sched_group
*sched_group_core_bycpu
[NR_CPUS
];
6019 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6020 static int cpu_to_core_group(int cpu
)
6022 return first_cpu(cpu_sibling_map
[cpu
]);
6024 #elif defined(CONFIG_SCHED_MC)
6025 static int cpu_to_core_group(int cpu
)
6031 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6032 static struct sched_group
*sched_group_phys_bycpu
[NR_CPUS
];
6034 static int cpu_to_phys_group(int cpu
)
6036 #ifdef CONFIG_SCHED_MC
6037 cpumask_t mask
= cpu_coregroup_map(cpu
);
6038 return first_cpu(mask
);
6039 #elif defined(CONFIG_SCHED_SMT)
6040 return first_cpu(cpu_sibling_map
[cpu
]);
6048 * The init_sched_build_groups can't handle what we want to do with node
6049 * groups, so roll our own. Now each node has its own list of groups which
6050 * gets dynamically allocated.
6052 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6053 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6055 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6056 static struct sched_group
*sched_group_allnodes_bycpu
[NR_CPUS
];
6058 static int cpu_to_allnodes_group(int cpu
)
6060 return cpu_to_node(cpu
);
6062 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6064 struct sched_group
*sg
= group_head
;
6070 for_each_cpu_mask(j
, sg
->cpumask
) {
6071 struct sched_domain
*sd
;
6073 sd
= &per_cpu(phys_domains
, j
);
6074 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6076 * Only add "power" once for each
6082 sg
->cpu_power
+= sd
->groups
->cpu_power
;
6085 if (sg
!= group_head
)
6090 /* Free memory allocated for various sched_group structures */
6091 static void free_sched_groups(const cpumask_t
*cpu_map
)
6097 for_each_cpu_mask(cpu
, *cpu_map
) {
6098 struct sched_group
*sched_group_allnodes
6099 = sched_group_allnodes_bycpu
[cpu
];
6100 struct sched_group
**sched_group_nodes
6101 = sched_group_nodes_bycpu
[cpu
];
6103 if (sched_group_allnodes
) {
6104 kfree(sched_group_allnodes
);
6105 sched_group_allnodes_bycpu
[cpu
] = NULL
;
6108 if (!sched_group_nodes
)
6111 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6112 cpumask_t nodemask
= node_to_cpumask(i
);
6113 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6115 cpus_and(nodemask
, nodemask
, *cpu_map
);
6116 if (cpus_empty(nodemask
))
6126 if (oldsg
!= sched_group_nodes
[i
])
6129 kfree(sched_group_nodes
);
6130 sched_group_nodes_bycpu
[cpu
] = NULL
;
6133 for_each_cpu_mask(cpu
, *cpu_map
) {
6134 if (sched_group_phys_bycpu
[cpu
]) {
6135 kfree(sched_group_phys_bycpu
[cpu
]);
6136 sched_group_phys_bycpu
[cpu
] = NULL
;
6138 #ifdef CONFIG_SCHED_MC
6139 if (sched_group_core_bycpu
[cpu
]) {
6140 kfree(sched_group_core_bycpu
[cpu
]);
6141 sched_group_core_bycpu
[cpu
] = NULL
;
6148 * Build sched domains for a given set of cpus and attach the sched domains
6149 * to the individual cpus
6151 static int build_sched_domains(const cpumask_t
*cpu_map
)
6154 struct sched_group
*sched_group_phys
= NULL
;
6155 #ifdef CONFIG_SCHED_MC
6156 struct sched_group
*sched_group_core
= NULL
;
6159 struct sched_group
**sched_group_nodes
= NULL
;
6160 struct sched_group
*sched_group_allnodes
= NULL
;
6163 * Allocate the per-node list of sched groups
6165 sched_group_nodes
= kzalloc(sizeof(struct sched_group
*)*MAX_NUMNODES
,
6167 if (!sched_group_nodes
) {
6168 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6171 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6175 * Set up domains for cpus specified by the cpu_map.
6177 for_each_cpu_mask(i
, *cpu_map
) {
6179 struct sched_domain
*sd
= NULL
, *p
;
6180 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6182 cpus_and(nodemask
, nodemask
, *cpu_map
);
6185 if (cpus_weight(*cpu_map
)
6186 > SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6187 if (!sched_group_allnodes
) {
6188 sched_group_allnodes
6189 = kmalloc(sizeof(struct sched_group
)
6192 if (!sched_group_allnodes
) {
6194 "Can not alloc allnodes sched group\n");
6197 sched_group_allnodes_bycpu
[i
]
6198 = sched_group_allnodes
;
6200 sd
= &per_cpu(allnodes_domains
, i
);
6201 *sd
= SD_ALLNODES_INIT
;
6202 sd
->span
= *cpu_map
;
6203 group
= cpu_to_allnodes_group(i
);
6204 sd
->groups
= &sched_group_allnodes
[group
];
6209 sd
= &per_cpu(node_domains
, i
);
6211 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6213 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6216 if (!sched_group_phys
) {
6218 = kmalloc(sizeof(struct sched_group
) * NR_CPUS
,
6220 if (!sched_group_phys
) {
6221 printk (KERN_WARNING
"Can not alloc phys sched"
6225 sched_group_phys_bycpu
[i
] = sched_group_phys
;
6229 sd
= &per_cpu(phys_domains
, i
);
6230 group
= cpu_to_phys_group(i
);
6232 sd
->span
= nodemask
;
6234 sd
->groups
= &sched_group_phys
[group
];
6236 #ifdef CONFIG_SCHED_MC
6237 if (!sched_group_core
) {
6239 = kmalloc(sizeof(struct sched_group
) * NR_CPUS
,
6241 if (!sched_group_core
) {
6242 printk (KERN_WARNING
"Can not alloc core sched"
6246 sched_group_core_bycpu
[i
] = sched_group_core
;
6250 sd
= &per_cpu(core_domains
, i
);
6251 group
= cpu_to_core_group(i
);
6253 sd
->span
= cpu_coregroup_map(i
);
6254 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6256 sd
->groups
= &sched_group_core
[group
];
6259 #ifdef CONFIG_SCHED_SMT
6261 sd
= &per_cpu(cpu_domains
, i
);
6262 group
= cpu_to_cpu_group(i
);
6263 *sd
= SD_SIBLING_INIT
;
6264 sd
->span
= cpu_sibling_map
[i
];
6265 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6267 sd
->groups
= &sched_group_cpus
[group
];
6271 #ifdef CONFIG_SCHED_SMT
6272 /* Set up CPU (sibling) groups */
6273 for_each_cpu_mask(i
, *cpu_map
) {
6274 cpumask_t this_sibling_map
= cpu_sibling_map
[i
];
6275 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6276 if (i
!= first_cpu(this_sibling_map
))
6279 init_sched_build_groups(sched_group_cpus
, this_sibling_map
,
6284 #ifdef CONFIG_SCHED_MC
6285 /* Set up multi-core groups */
6286 for_each_cpu_mask(i
, *cpu_map
) {
6287 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6288 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6289 if (i
!= first_cpu(this_core_map
))
6291 init_sched_build_groups(sched_group_core
, this_core_map
,
6292 &cpu_to_core_group
);
6297 /* Set up physical groups */
6298 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6299 cpumask_t nodemask
= node_to_cpumask(i
);
6301 cpus_and(nodemask
, nodemask
, *cpu_map
);
6302 if (cpus_empty(nodemask
))
6305 init_sched_build_groups(sched_group_phys
, nodemask
,
6306 &cpu_to_phys_group
);
6310 /* Set up node groups */
6311 if (sched_group_allnodes
)
6312 init_sched_build_groups(sched_group_allnodes
, *cpu_map
,
6313 &cpu_to_allnodes_group
);
6315 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6316 /* Set up node groups */
6317 struct sched_group
*sg
, *prev
;
6318 cpumask_t nodemask
= node_to_cpumask(i
);
6319 cpumask_t domainspan
;
6320 cpumask_t covered
= CPU_MASK_NONE
;
6323 cpus_and(nodemask
, nodemask
, *cpu_map
);
6324 if (cpus_empty(nodemask
)) {
6325 sched_group_nodes
[i
] = NULL
;
6329 domainspan
= sched_domain_node_span(i
);
6330 cpus_and(domainspan
, domainspan
, *cpu_map
);
6332 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6334 printk(KERN_WARNING
"Can not alloc domain group for "
6338 sched_group_nodes
[i
] = sg
;
6339 for_each_cpu_mask(j
, nodemask
) {
6340 struct sched_domain
*sd
;
6341 sd
= &per_cpu(node_domains
, j
);
6345 sg
->cpumask
= nodemask
;
6347 cpus_or(covered
, covered
, nodemask
);
6350 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6351 cpumask_t tmp
, notcovered
;
6352 int n
= (i
+ j
) % MAX_NUMNODES
;
6354 cpus_complement(notcovered
, covered
);
6355 cpus_and(tmp
, notcovered
, *cpu_map
);
6356 cpus_and(tmp
, tmp
, domainspan
);
6357 if (cpus_empty(tmp
))
6360 nodemask
= node_to_cpumask(n
);
6361 cpus_and(tmp
, tmp
, nodemask
);
6362 if (cpus_empty(tmp
))
6365 sg
= kmalloc_node(sizeof(struct sched_group
),
6369 "Can not alloc domain group for node %d\n", j
);
6374 sg
->next
= prev
->next
;
6375 cpus_or(covered
, covered
, tmp
);
6382 /* Calculate CPU power for physical packages and nodes */
6383 #ifdef CONFIG_SCHED_SMT
6384 for_each_cpu_mask(i
, *cpu_map
) {
6385 struct sched_domain
*sd
;
6386 sd
= &per_cpu(cpu_domains
, i
);
6387 sd
->groups
->cpu_power
= SCHED_LOAD_SCALE
;
6390 #ifdef CONFIG_SCHED_MC
6391 for_each_cpu_mask(i
, *cpu_map
) {
6393 struct sched_domain
*sd
;
6394 sd
= &per_cpu(core_domains
, i
);
6395 if (sched_smt_power_savings
)
6396 power
= SCHED_LOAD_SCALE
* cpus_weight(sd
->groups
->cpumask
);
6398 power
= SCHED_LOAD_SCALE
+ (cpus_weight(sd
->groups
->cpumask
)-1)
6399 * SCHED_LOAD_SCALE
/ 10;
6400 sd
->groups
->cpu_power
= power
;
6404 for_each_cpu_mask(i
, *cpu_map
) {
6405 struct sched_domain
*sd
;
6406 #ifdef CONFIG_SCHED_MC
6407 sd
= &per_cpu(phys_domains
, i
);
6408 if (i
!= first_cpu(sd
->groups
->cpumask
))
6411 sd
->groups
->cpu_power
= 0;
6412 if (sched_mc_power_savings
|| sched_smt_power_savings
) {
6415 for_each_cpu_mask(j
, sd
->groups
->cpumask
) {
6416 struct sched_domain
*sd1
;
6417 sd1
= &per_cpu(core_domains
, j
);
6419 * for each core we will add once
6420 * to the group in physical domain
6422 if (j
!= first_cpu(sd1
->groups
->cpumask
))
6425 if (sched_smt_power_savings
)
6426 sd
->groups
->cpu_power
+= sd1
->groups
->cpu_power
;
6428 sd
->groups
->cpu_power
+= SCHED_LOAD_SCALE
;
6432 * This has to be < 2 * SCHED_LOAD_SCALE
6433 * Lets keep it SCHED_LOAD_SCALE, so that
6434 * while calculating NUMA group's cpu_power
6436 * numa_group->cpu_power += phys_group->cpu_power;
6438 * See "only add power once for each physical pkg"
6441 sd
->groups
->cpu_power
= SCHED_LOAD_SCALE
;
6444 sd
= &per_cpu(phys_domains
, i
);
6445 if (sched_smt_power_savings
)
6446 power
= SCHED_LOAD_SCALE
* cpus_weight(sd
->groups
->cpumask
);
6448 power
= SCHED_LOAD_SCALE
;
6449 sd
->groups
->cpu_power
= power
;
6454 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6455 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6457 init_numa_sched_groups_power(sched_group_allnodes
);
6460 /* Attach the domains */
6461 for_each_cpu_mask(i
, *cpu_map
) {
6462 struct sched_domain
*sd
;
6463 #ifdef CONFIG_SCHED_SMT
6464 sd
= &per_cpu(cpu_domains
, i
);
6465 #elif defined(CONFIG_SCHED_MC)
6466 sd
= &per_cpu(core_domains
, i
);
6468 sd
= &per_cpu(phys_domains
, i
);
6470 cpu_attach_domain(sd
, i
);
6473 * Tune cache-hot values:
6475 calibrate_migration_costs(cpu_map
);
6480 free_sched_groups(cpu_map
);
6484 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6486 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6488 cpumask_t cpu_default_map
;
6492 * Setup mask for cpus without special case scheduling requirements.
6493 * For now this just excludes isolated cpus, but could be used to
6494 * exclude other special cases in the future.
6496 cpus_andnot(cpu_default_map
, *cpu_map
, cpu_isolated_map
);
6498 err
= build_sched_domains(&cpu_default_map
);
6503 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6505 free_sched_groups(cpu_map
);
6509 * Detach sched domains from a group of cpus specified in cpu_map
6510 * These cpus will now be attached to the NULL domain
6512 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6516 for_each_cpu_mask(i
, *cpu_map
)
6517 cpu_attach_domain(NULL
, i
);
6518 synchronize_sched();
6519 arch_destroy_sched_domains(cpu_map
);
6523 * Partition sched domains as specified by the cpumasks below.
6524 * This attaches all cpus from the cpumasks to the NULL domain,
6525 * waits for a RCU quiescent period, recalculates sched
6526 * domain information and then attaches them back to the
6527 * correct sched domains
6528 * Call with hotplug lock held
6530 int partition_sched_domains(cpumask_t
*partition1
, cpumask_t
*partition2
)
6532 cpumask_t change_map
;
6535 cpus_and(*partition1
, *partition1
, cpu_online_map
);
6536 cpus_and(*partition2
, *partition2
, cpu_online_map
);
6537 cpus_or(change_map
, *partition1
, *partition2
);
6539 /* Detach sched domains from all of the affected cpus */
6540 detach_destroy_domains(&change_map
);
6541 if (!cpus_empty(*partition1
))
6542 err
= build_sched_domains(partition1
);
6543 if (!err
&& !cpus_empty(*partition2
))
6544 err
= build_sched_domains(partition2
);
6549 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6550 int arch_reinit_sched_domains(void)
6555 detach_destroy_domains(&cpu_online_map
);
6556 err
= arch_init_sched_domains(&cpu_online_map
);
6557 unlock_cpu_hotplug();
6562 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
6566 if (buf
[0] != '0' && buf
[0] != '1')
6570 sched_smt_power_savings
= (buf
[0] == '1');
6572 sched_mc_power_savings
= (buf
[0] == '1');
6574 ret
= arch_reinit_sched_domains();
6576 return ret
? ret
: count
;
6579 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
6583 #ifdef CONFIG_SCHED_SMT
6585 err
= sysfs_create_file(&cls
->kset
.kobj
,
6586 &attr_sched_smt_power_savings
.attr
);
6588 #ifdef CONFIG_SCHED_MC
6589 if (!err
&& mc_capable())
6590 err
= sysfs_create_file(&cls
->kset
.kobj
,
6591 &attr_sched_mc_power_savings
.attr
);
6597 #ifdef CONFIG_SCHED_MC
6598 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
6600 return sprintf(page
, "%u\n", sched_mc_power_savings
);
6602 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
6603 const char *buf
, size_t count
)
6605 return sched_power_savings_store(buf
, count
, 0);
6607 SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
6608 sched_mc_power_savings_store
);
6611 #ifdef CONFIG_SCHED_SMT
6612 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
6614 return sprintf(page
, "%u\n", sched_smt_power_savings
);
6616 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
6617 const char *buf
, size_t count
)
6619 return sched_power_savings_store(buf
, count
, 1);
6621 SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
6622 sched_smt_power_savings_store
);
6626 #ifdef CONFIG_HOTPLUG_CPU
6628 * Force a reinitialization of the sched domains hierarchy. The domains
6629 * and groups cannot be updated in place without racing with the balancing
6630 * code, so we temporarily attach all running cpus to the NULL domain
6631 * which will prevent rebalancing while the sched domains are recalculated.
6633 static int update_sched_domains(struct notifier_block
*nfb
,
6634 unsigned long action
, void *hcpu
)
6637 case CPU_UP_PREPARE
:
6638 case CPU_DOWN_PREPARE
:
6639 detach_destroy_domains(&cpu_online_map
);
6642 case CPU_UP_CANCELED
:
6643 case CPU_DOWN_FAILED
:
6647 * Fall through and re-initialise the domains.
6654 /* The hotplug lock is already held by cpu_up/cpu_down */
6655 arch_init_sched_domains(&cpu_online_map
);
6661 void __init
sched_init_smp(void)
6664 arch_init_sched_domains(&cpu_online_map
);
6665 unlock_cpu_hotplug();
6666 /* XXX: Theoretical race here - CPU may be hotplugged now */
6667 hotcpu_notifier(update_sched_domains
, 0);
6670 void __init
sched_init_smp(void)
6673 #endif /* CONFIG_SMP */
6675 int in_sched_functions(unsigned long addr
)
6677 /* Linker adds these: start and end of __sched functions */
6678 extern char __sched_text_start
[], __sched_text_end
[];
6680 return in_lock_functions(addr
) ||
6681 (addr
>= (unsigned long)__sched_text_start
6682 && addr
< (unsigned long)__sched_text_end
);
6685 void __init
sched_init(void)
6689 for_each_possible_cpu(i
) {
6690 struct prio_array
*array
;
6694 spin_lock_init(&rq
->lock
);
6695 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
6697 rq
->active
= rq
->arrays
;
6698 rq
->expired
= rq
->arrays
+ 1;
6699 rq
->best_expired_prio
= MAX_PRIO
;
6703 for (j
= 1; j
< 3; j
++)
6704 rq
->cpu_load
[j
] = 0;
6705 rq
->active_balance
= 0;
6707 rq
->migration_thread
= NULL
;
6708 INIT_LIST_HEAD(&rq
->migration_queue
);
6710 atomic_set(&rq
->nr_iowait
, 0);
6712 for (j
= 0; j
< 2; j
++) {
6713 array
= rq
->arrays
+ j
;
6714 for (k
= 0; k
< MAX_PRIO
; k
++) {
6715 INIT_LIST_HEAD(array
->queue
+ k
);
6716 __clear_bit(k
, array
->bitmap
);
6718 // delimiter for bitsearch
6719 __set_bit(MAX_PRIO
, array
->bitmap
);
6723 set_load_weight(&init_task
);
6725 * The boot idle thread does lazy MMU switching as well:
6727 atomic_inc(&init_mm
.mm_count
);
6728 enter_lazy_tlb(&init_mm
, current
);
6731 * Make us the idle thread. Technically, schedule() should not be
6732 * called from this thread, however somewhere below it might be,
6733 * but because we are the idle thread, we just pick up running again
6734 * when this runqueue becomes "idle".
6736 init_idle(current
, smp_processor_id());
6739 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6740 void __might_sleep(char *file
, int line
)
6743 static unsigned long prev_jiffy
; /* ratelimiting */
6745 if ((in_atomic() || irqs_disabled()) &&
6746 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
6747 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
6749 prev_jiffy
= jiffies
;
6750 printk(KERN_ERR
"BUG: sleeping function called from invalid"
6751 " context at %s:%d\n", file
, line
);
6752 printk("in_atomic():%d, irqs_disabled():%d\n",
6753 in_atomic(), irqs_disabled());
6758 EXPORT_SYMBOL(__might_sleep
);
6761 #ifdef CONFIG_MAGIC_SYSRQ
6762 void normalize_rt_tasks(void)
6764 struct prio_array
*array
;
6765 struct task_struct
*p
;
6766 unsigned long flags
;
6769 read_lock_irq(&tasklist_lock
);
6770 for_each_process(p
) {
6774 spin_lock_irqsave(&p
->pi_lock
, flags
);
6775 rq
= __task_rq_lock(p
);
6779 deactivate_task(p
, task_rq(p
));
6780 __setscheduler(p
, SCHED_NORMAL
, 0);
6782 __activate_task(p
, task_rq(p
));
6783 resched_task(rq
->curr
);
6786 __task_rq_unlock(rq
);
6787 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
6789 read_unlock_irq(&tasklist_lock
);
6792 #endif /* CONFIG_MAGIC_SYSRQ */
6796 * These functions are only useful for the IA64 MCA handling.
6798 * They can only be called when the whole system has been
6799 * stopped - every CPU needs to be quiescent, and no scheduling
6800 * activity can take place. Using them for anything else would
6801 * be a serious bug, and as a result, they aren't even visible
6802 * under any other configuration.
6806 * curr_task - return the current task for a given cpu.
6807 * @cpu: the processor in question.
6809 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6811 struct task_struct
*curr_task(int cpu
)
6813 return cpu_curr(cpu
);
6817 * set_curr_task - set the current task for a given cpu.
6818 * @cpu: the processor in question.
6819 * @p: the task pointer to set.
6821 * Description: This function must only be used when non-maskable interrupts
6822 * are serviced on a separate stack. It allows the architecture to switch the
6823 * notion of the current task on a cpu in a non-blocking manner. This function
6824 * must be called with all CPU's synchronized, and interrupts disabled, the
6825 * and caller must save the original value of the current task (see
6826 * curr_task() above) and restore that value before reenabling interrupts and
6827 * re-starting the system.
6829 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6831 void set_curr_task(int cpu
, struct task_struct
*p
)