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(task_t
*p
)
184 return static_prio_timeslice(p
->static_prio
);
188 * These are the runqueue data structures:
191 typedef struct runqueue runqueue_t
;
194 unsigned int nr_active
;
195 DECLARE_BITMAP(bitmap
, MAX_PRIO
+1); /* include 1 bit for delimiter */
196 struct list_head queue
[MAX_PRIO
];
200 * This is the main, per-CPU runqueue data structure.
202 * Locking rule: those places that want to lock multiple runqueues
203 * (such as the load balancing or the thread migration code), lock
204 * acquire operations must be ordered by ascending &runqueue.
210 * nr_running and cpu_load should be in the same cacheline because
211 * remote CPUs use both these fields when doing load calculation.
213 unsigned long nr_running
;
214 unsigned long raw_weighted_load
;
216 unsigned long cpu_load
[3];
218 unsigned long long nr_switches
;
221 * This is part of a global counter where only the total sum
222 * over all CPUs matters. A task can increase this counter on
223 * one CPU and if it got migrated afterwards it may decrease
224 * it on another CPU. Always updated under the runqueue lock:
226 unsigned long nr_uninterruptible
;
228 unsigned long expired_timestamp
;
229 unsigned long long timestamp_last_tick
;
231 struct mm_struct
*prev_mm
;
232 prio_array_t
*active
, *expired
, arrays
[2];
233 int best_expired_prio
;
237 struct sched_domain
*sd
;
239 /* For active balancing */
243 task_t
*migration_thread
;
244 struct list_head migration_queue
;
247 #ifdef CONFIG_SCHEDSTATS
249 struct sched_info rq_sched_info
;
251 /* sys_sched_yield() stats */
252 unsigned long yld_exp_empty
;
253 unsigned long yld_act_empty
;
254 unsigned long yld_both_empty
;
255 unsigned long yld_cnt
;
257 /* schedule() stats */
258 unsigned long sched_switch
;
259 unsigned long sched_cnt
;
260 unsigned long sched_goidle
;
262 /* try_to_wake_up() stats */
263 unsigned long ttwu_cnt
;
264 unsigned long ttwu_local
;
266 struct lock_class_key rq_lock_key
;
269 static DEFINE_PER_CPU(struct runqueue
, runqueues
);
272 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
273 * See detach_destroy_domains: synchronize_sched for details.
275 * The domain tree of any CPU may only be accessed from within
276 * preempt-disabled sections.
278 #define for_each_domain(cpu, __sd) \
279 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
281 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
282 #define this_rq() (&__get_cpu_var(runqueues))
283 #define task_rq(p) cpu_rq(task_cpu(p))
284 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
286 #ifndef prepare_arch_switch
287 # define prepare_arch_switch(next) do { } while (0)
289 #ifndef finish_arch_switch
290 # define finish_arch_switch(prev) do { } while (0)
293 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
294 static inline int task_running(runqueue_t
*rq
, task_t
*p
)
296 return rq
->curr
== p
;
299 static inline void prepare_lock_switch(runqueue_t
*rq
, task_t
*next
)
303 static inline void finish_lock_switch(runqueue_t
*rq
, task_t
*prev
)
305 #ifdef CONFIG_DEBUG_SPINLOCK
306 /* this is a valid case when another task releases the spinlock */
307 rq
->lock
.owner
= current
;
310 * If we are tracking spinlock dependencies then we have to
311 * fix up the runqueue lock - which gets 'carried over' from
314 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
316 spin_unlock_irq(&rq
->lock
);
319 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
320 static inline int task_running(runqueue_t
*rq
, task_t
*p
)
325 return rq
->curr
== p
;
329 static inline void prepare_lock_switch(runqueue_t
*rq
, task_t
*next
)
333 * We can optimise this out completely for !SMP, because the
334 * SMP rebalancing from interrupt is the only thing that cares
339 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
340 spin_unlock_irq(&rq
->lock
);
342 spin_unlock(&rq
->lock
);
346 static inline void finish_lock_switch(runqueue_t
*rq
, task_t
*prev
)
350 * After ->oncpu is cleared, the task can be moved to a different CPU.
351 * We must ensure this doesn't happen until the switch is completely
357 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
361 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
364 * __task_rq_lock - lock the runqueue a given task resides on.
365 * Must be called interrupts disabled.
367 static inline runqueue_t
*__task_rq_lock(task_t
*p
)
374 spin_lock(&rq
->lock
);
375 if (unlikely(rq
!= task_rq(p
))) {
376 spin_unlock(&rq
->lock
);
377 goto repeat_lock_task
;
383 * task_rq_lock - lock the runqueue a given task resides on and disable
384 * interrupts. Note the ordering: we can safely lookup the task_rq without
385 * explicitly disabling preemption.
387 static runqueue_t
*task_rq_lock(task_t
*p
, unsigned long *flags
)
393 local_irq_save(*flags
);
395 spin_lock(&rq
->lock
);
396 if (unlikely(rq
!= task_rq(p
))) {
397 spin_unlock_irqrestore(&rq
->lock
, *flags
);
398 goto repeat_lock_task
;
403 static inline void __task_rq_unlock(runqueue_t
*rq
)
406 spin_unlock(&rq
->lock
);
409 static inline void task_rq_unlock(runqueue_t
*rq
, unsigned long *flags
)
412 spin_unlock_irqrestore(&rq
->lock
, *flags
);
415 #ifdef CONFIG_SCHEDSTATS
417 * bump this up when changing the output format or the meaning of an existing
418 * format, so that tools can adapt (or abort)
420 #define SCHEDSTAT_VERSION 12
422 static int show_schedstat(struct seq_file
*seq
, void *v
)
426 seq_printf(seq
, "version %d\n", SCHEDSTAT_VERSION
);
427 seq_printf(seq
, "timestamp %lu\n", jiffies
);
428 for_each_online_cpu(cpu
) {
429 runqueue_t
*rq
= cpu_rq(cpu
);
431 struct sched_domain
*sd
;
435 /* runqueue-specific stats */
437 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
438 cpu
, rq
->yld_both_empty
,
439 rq
->yld_act_empty
, rq
->yld_exp_empty
, rq
->yld_cnt
,
440 rq
->sched_switch
, rq
->sched_cnt
, rq
->sched_goidle
,
441 rq
->ttwu_cnt
, rq
->ttwu_local
,
442 rq
->rq_sched_info
.cpu_time
,
443 rq
->rq_sched_info
.run_delay
, rq
->rq_sched_info
.pcnt
);
445 seq_printf(seq
, "\n");
448 /* domain-specific stats */
450 for_each_domain(cpu
, sd
) {
451 enum idle_type itype
;
452 char mask_str
[NR_CPUS
];
454 cpumask_scnprintf(mask_str
, NR_CPUS
, sd
->span
);
455 seq_printf(seq
, "domain%d %s", dcnt
++, mask_str
);
456 for (itype
= SCHED_IDLE
; itype
< MAX_IDLE_TYPES
;
458 seq_printf(seq
, " %lu %lu %lu %lu %lu %lu %lu %lu",
460 sd
->lb_balanced
[itype
],
461 sd
->lb_failed
[itype
],
462 sd
->lb_imbalance
[itype
],
463 sd
->lb_gained
[itype
],
464 sd
->lb_hot_gained
[itype
],
465 sd
->lb_nobusyq
[itype
],
466 sd
->lb_nobusyg
[itype
]);
468 seq_printf(seq
, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
469 sd
->alb_cnt
, sd
->alb_failed
, sd
->alb_pushed
,
470 sd
->sbe_cnt
, sd
->sbe_balanced
, sd
->sbe_pushed
,
471 sd
->sbf_cnt
, sd
->sbf_balanced
, sd
->sbf_pushed
,
472 sd
->ttwu_wake_remote
, sd
->ttwu_move_affine
, sd
->ttwu_move_balance
);
480 static int schedstat_open(struct inode
*inode
, struct file
*file
)
482 unsigned int size
= PAGE_SIZE
* (1 + num_online_cpus() / 32);
483 char *buf
= kmalloc(size
, GFP_KERNEL
);
489 res
= single_open(file
, show_schedstat
, NULL
);
491 m
= file
->private_data
;
499 struct file_operations proc_schedstat_operations
= {
500 .open
= schedstat_open
,
503 .release
= single_release
,
506 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
507 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
508 #else /* !CONFIG_SCHEDSTATS */
509 # define schedstat_inc(rq, field) do { } while (0)
510 # define schedstat_add(rq, field, amt) do { } while (0)
514 * rq_lock - lock a given runqueue and disable interrupts.
516 static inline runqueue_t
*this_rq_lock(void)
523 spin_lock(&rq
->lock
);
528 #ifdef CONFIG_SCHEDSTATS
530 * Called when a process is dequeued from the active array and given
531 * the cpu. We should note that with the exception of interactive
532 * tasks, the expired queue will become the active queue after the active
533 * queue is empty, without explicitly dequeuing and requeuing tasks in the
534 * expired queue. (Interactive tasks may be requeued directly to the
535 * active queue, thus delaying tasks in the expired queue from running;
536 * see scheduler_tick()).
538 * This function is only called from sched_info_arrive(), rather than
539 * dequeue_task(). Even though a task may be queued and dequeued multiple
540 * times as it is shuffled about, we're really interested in knowing how
541 * long it was from the *first* time it was queued to the time that it
544 static inline void sched_info_dequeued(task_t
*t
)
546 t
->sched_info
.last_queued
= 0;
550 * Called when a task finally hits the cpu. We can now calculate how
551 * long it was waiting to run. We also note when it began so that we
552 * can keep stats on how long its timeslice is.
554 static void sched_info_arrive(task_t
*t
)
556 unsigned long now
= jiffies
, diff
= 0;
557 struct runqueue
*rq
= task_rq(t
);
559 if (t
->sched_info
.last_queued
)
560 diff
= now
- t
->sched_info
.last_queued
;
561 sched_info_dequeued(t
);
562 t
->sched_info
.run_delay
+= diff
;
563 t
->sched_info
.last_arrival
= now
;
564 t
->sched_info
.pcnt
++;
569 rq
->rq_sched_info
.run_delay
+= diff
;
570 rq
->rq_sched_info
.pcnt
++;
574 * Called when a process is queued into either the active or expired
575 * array. The time is noted and later used to determine how long we
576 * had to wait for us to reach the cpu. Since the expired queue will
577 * become the active queue after active queue is empty, without dequeuing
578 * and requeuing any tasks, we are interested in queuing to either. It
579 * is unusual but not impossible for tasks to be dequeued and immediately
580 * requeued in the same or another array: this can happen in sched_yield(),
581 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
584 * This function is only called from enqueue_task(), but also only updates
585 * the timestamp if it is already not set. It's assumed that
586 * sched_info_dequeued() will clear that stamp when appropriate.
588 static inline void sched_info_queued(task_t
*t
)
590 if (!t
->sched_info
.last_queued
)
591 t
->sched_info
.last_queued
= jiffies
;
595 * Called when a process ceases being the active-running process, either
596 * voluntarily or involuntarily. Now we can calculate how long we ran.
598 static inline void sched_info_depart(task_t
*t
)
600 struct runqueue
*rq
= task_rq(t
);
601 unsigned long diff
= jiffies
- t
->sched_info
.last_arrival
;
603 t
->sched_info
.cpu_time
+= diff
;
606 rq
->rq_sched_info
.cpu_time
+= diff
;
610 * Called when tasks are switched involuntarily due, typically, to expiring
611 * their time slice. (This may also be called when switching to or from
612 * the idle task.) We are only called when prev != next.
614 static inline void sched_info_switch(task_t
*prev
, task_t
*next
)
616 struct runqueue
*rq
= task_rq(prev
);
619 * prev now departs the cpu. It's not interesting to record
620 * stats about how efficient we were at scheduling the idle
623 if (prev
!= rq
->idle
)
624 sched_info_depart(prev
);
626 if (next
!= rq
->idle
)
627 sched_info_arrive(next
);
630 #define sched_info_queued(t) do { } while (0)
631 #define sched_info_switch(t, next) do { } while (0)
632 #endif /* CONFIG_SCHEDSTATS */
635 * Adding/removing a task to/from a priority array:
637 static void dequeue_task(struct task_struct
*p
, prio_array_t
*array
)
640 list_del(&p
->run_list
);
641 if (list_empty(array
->queue
+ p
->prio
))
642 __clear_bit(p
->prio
, array
->bitmap
);
645 static void enqueue_task(struct task_struct
*p
, prio_array_t
*array
)
647 sched_info_queued(p
);
648 list_add_tail(&p
->run_list
, array
->queue
+ p
->prio
);
649 __set_bit(p
->prio
, array
->bitmap
);
655 * Put task to the end of the run list without the overhead of dequeue
656 * followed by enqueue.
658 static void requeue_task(struct task_struct
*p
, prio_array_t
*array
)
660 list_move_tail(&p
->run_list
, array
->queue
+ p
->prio
);
663 static inline void enqueue_task_head(struct task_struct
*p
, prio_array_t
*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(task_t
*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(task_t
*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
);
740 static inline void inc_raw_weighted_load(runqueue_t
*rq
, const task_t
*p
)
742 rq
->raw_weighted_load
+= p
->load_weight
;
745 static inline void dec_raw_weighted_load(runqueue_t
*rq
, const task_t
*p
)
747 rq
->raw_weighted_load
-= p
->load_weight
;
750 static inline void inc_nr_running(task_t
*p
, runqueue_t
*rq
)
753 inc_raw_weighted_load(rq
, p
);
756 static inline void dec_nr_running(task_t
*p
, runqueue_t
*rq
)
759 dec_raw_weighted_load(rq
, p
);
763 * Calculate the expected normal priority: i.e. priority
764 * without taking RT-inheritance into account. Might be
765 * boosted by interactivity modifiers. Changes upon fork,
766 * setprio syscalls, and whenever the interactivity
767 * estimator recalculates.
769 static inline int normal_prio(task_t
*p
)
773 if (has_rt_policy(p
))
774 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
776 prio
= __normal_prio(p
);
781 * Calculate the current priority, i.e. the priority
782 * taken into account by the scheduler. This value might
783 * be boosted by RT tasks, or might be boosted by
784 * interactivity modifiers. Will be RT if the task got
785 * RT-boosted. If not then it returns p->normal_prio.
787 static int effective_prio(task_t
*p
)
789 p
->normal_prio
= normal_prio(p
);
791 * If we are RT tasks or we were boosted to RT priority,
792 * keep the priority unchanged. Otherwise, update priority
793 * to the normal priority:
795 if (!rt_prio(p
->prio
))
796 return p
->normal_prio
;
801 * __activate_task - move a task to the runqueue.
803 static void __activate_task(task_t
*p
, runqueue_t
*rq
)
805 prio_array_t
*target
= rq
->active
;
808 target
= rq
->expired
;
809 enqueue_task(p
, target
);
810 inc_nr_running(p
, rq
);
814 * __activate_idle_task - move idle task to the _front_ of runqueue.
816 static inline void __activate_idle_task(task_t
*p
, runqueue_t
*rq
)
818 enqueue_task_head(p
, rq
->active
);
819 inc_nr_running(p
, rq
);
823 * Recalculate p->normal_prio and p->prio after having slept,
824 * updating the sleep-average too:
826 static int recalc_task_prio(task_t
*p
, unsigned long long now
)
828 /* Caller must always ensure 'now >= p->timestamp' */
829 unsigned long sleep_time
= now
- p
->timestamp
;
834 if (likely(sleep_time
> 0)) {
836 * This ceiling is set to the lowest priority that would allow
837 * a task to be reinserted into the active array on timeslice
840 unsigned long ceiling
= INTERACTIVE_SLEEP(p
);
842 if (p
->mm
&& sleep_time
> ceiling
&& p
->sleep_avg
< ceiling
) {
844 * Prevents user tasks from achieving best priority
845 * with one single large enough sleep.
847 p
->sleep_avg
= ceiling
;
849 * Using INTERACTIVE_SLEEP() as a ceiling places a
850 * nice(0) task 1ms sleep away from promotion, and
851 * gives it 700ms to round-robin with no chance of
852 * being demoted. This is more than generous, so
853 * mark this sleep as non-interactive to prevent the
854 * on-runqueue bonus logic from intervening should
855 * this task not receive cpu immediately.
857 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
860 * Tasks waking from uninterruptible sleep are
861 * limited in their sleep_avg rise as they
862 * are likely to be waiting on I/O
864 if (p
->sleep_type
== SLEEP_NONINTERACTIVE
&& p
->mm
) {
865 if (p
->sleep_avg
>= ceiling
)
867 else if (p
->sleep_avg
+ sleep_time
>=
869 p
->sleep_avg
= ceiling
;
875 * This code gives a bonus to interactive tasks.
877 * The boost works by updating the 'average sleep time'
878 * value here, based on ->timestamp. The more time a
879 * task spends sleeping, the higher the average gets -
880 * and the higher the priority boost gets as well.
882 p
->sleep_avg
+= sleep_time
;
885 if (p
->sleep_avg
> NS_MAX_SLEEP_AVG
)
886 p
->sleep_avg
= NS_MAX_SLEEP_AVG
;
889 return effective_prio(p
);
893 * activate_task - move a task to the runqueue and do priority recalculation
895 * Update all the scheduling statistics stuff. (sleep average
896 * calculation, priority modifiers, etc.)
898 static void activate_task(task_t
*p
, runqueue_t
*rq
, int local
)
900 unsigned long long now
;
905 /* Compensate for drifting sched_clock */
906 runqueue_t
*this_rq
= this_rq();
907 now
= (now
- this_rq
->timestamp_last_tick
)
908 + rq
->timestamp_last_tick
;
913 p
->prio
= recalc_task_prio(p
, now
);
916 * This checks to make sure it's not an uninterruptible task
917 * that is now waking up.
919 if (p
->sleep_type
== SLEEP_NORMAL
) {
921 * Tasks which were woken up by interrupts (ie. hw events)
922 * are most likely of interactive nature. So we give them
923 * the credit of extending their sleep time to the period
924 * of time they spend on the runqueue, waiting for execution
925 * on a CPU, first time around:
928 p
->sleep_type
= SLEEP_INTERRUPTED
;
931 * Normal first-time wakeups get a credit too for
932 * on-runqueue time, but it will be weighted down:
934 p
->sleep_type
= SLEEP_INTERACTIVE
;
939 __activate_task(p
, rq
);
943 * deactivate_task - remove a task from the runqueue.
945 static void deactivate_task(struct task_struct
*p
, runqueue_t
*rq
)
947 dec_nr_running(p
, rq
);
948 dequeue_task(p
, p
->array
);
953 * resched_task - mark a task 'to be rescheduled now'.
955 * On UP this means the setting of the need_resched flag, on SMP it
956 * might also involve a cross-CPU call to trigger the scheduler on
961 #ifndef tsk_is_polling
962 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
965 static void resched_task(task_t
*p
)
969 assert_spin_locked(&task_rq(p
)->lock
);
971 if (unlikely(test_tsk_thread_flag(p
, TIF_NEED_RESCHED
)))
974 set_tsk_thread_flag(p
, TIF_NEED_RESCHED
);
977 if (cpu
== smp_processor_id())
980 /* NEED_RESCHED must be visible before we test polling */
982 if (!tsk_is_polling(p
))
983 smp_send_reschedule(cpu
);
986 static inline void resched_task(task_t
*p
)
988 assert_spin_locked(&task_rq(p
)->lock
);
989 set_tsk_need_resched(p
);
994 * task_curr - is this task currently executing on a CPU?
995 * @p: the task in question.
997 inline int task_curr(const task_t
*p
)
999 return cpu_curr(task_cpu(p
)) == p
;
1002 /* Used instead of source_load when we know the type == 0 */
1003 unsigned long weighted_cpuload(const int cpu
)
1005 return cpu_rq(cpu
)->raw_weighted_load
;
1010 struct list_head list
;
1015 struct completion done
;
1019 * The task's runqueue lock must be held.
1020 * Returns true if you have to wait for migration thread.
1022 static int migrate_task(task_t
*p
, int dest_cpu
, migration_req_t
*req
)
1024 runqueue_t
*rq
= task_rq(p
);
1027 * If the task is not on a runqueue (and not running), then
1028 * it is sufficient to simply update the task's cpu field.
1030 if (!p
->array
&& !task_running(rq
, p
)) {
1031 set_task_cpu(p
, dest_cpu
);
1035 init_completion(&req
->done
);
1037 req
->dest_cpu
= dest_cpu
;
1038 list_add(&req
->list
, &rq
->migration_queue
);
1044 * wait_task_inactive - wait for a thread to unschedule.
1046 * The caller must ensure that the task *will* unschedule sometime soon,
1047 * else this function might spin for a *long* time. This function can't
1048 * be called with interrupts off, or it may introduce deadlock with
1049 * smp_call_function() if an IPI is sent by the same process we are
1050 * waiting to become inactive.
1052 void wait_task_inactive(task_t
*p
)
1054 unsigned long flags
;
1059 rq
= task_rq_lock(p
, &flags
);
1060 /* Must be off runqueue entirely, not preempted. */
1061 if (unlikely(p
->array
|| task_running(rq
, p
))) {
1062 /* If it's preempted, we yield. It could be a while. */
1063 preempted
= !task_running(rq
, p
);
1064 task_rq_unlock(rq
, &flags
);
1070 task_rq_unlock(rq
, &flags
);
1074 * kick_process - kick a running thread to enter/exit the kernel
1075 * @p: the to-be-kicked thread
1077 * Cause a process which is running on another CPU to enter
1078 * kernel-mode, without any delay. (to get signals handled.)
1080 * NOTE: this function doesnt have to take the runqueue lock,
1081 * because all it wants to ensure is that the remote task enters
1082 * the kernel. If the IPI races and the task has been migrated
1083 * to another CPU then no harm is done and the purpose has been
1086 void kick_process(task_t
*p
)
1092 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1093 smp_send_reschedule(cpu
);
1098 * Return a low guess at the load of a migration-source cpu weighted
1099 * according to the scheduling class and "nice" value.
1101 * We want to under-estimate the load of migration sources, to
1102 * balance conservatively.
1104 static inline unsigned long source_load(int cpu
, int type
)
1106 runqueue_t
*rq
= cpu_rq(cpu
);
1109 return rq
->raw_weighted_load
;
1111 return min(rq
->cpu_load
[type
-1], rq
->raw_weighted_load
);
1115 * Return a high guess at the load of a migration-target cpu weighted
1116 * according to the scheduling class and "nice" value.
1118 static inline unsigned long target_load(int cpu
, int type
)
1120 runqueue_t
*rq
= cpu_rq(cpu
);
1123 return rq
->raw_weighted_load
;
1125 return max(rq
->cpu_load
[type
-1], rq
->raw_weighted_load
);
1129 * Return the average load per task on the cpu's run queue
1131 static inline unsigned long cpu_avg_load_per_task(int cpu
)
1133 runqueue_t
*rq
= cpu_rq(cpu
);
1134 unsigned long n
= rq
->nr_running
;
1136 return n
? rq
->raw_weighted_load
/ n
: SCHED_LOAD_SCALE
;
1140 * find_idlest_group finds and returns the least busy CPU group within the
1143 static struct sched_group
*
1144 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1146 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1147 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1148 int load_idx
= sd
->forkexec_idx
;
1149 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1152 unsigned long load
, avg_load
;
1156 /* Skip over this group if it has no CPUs allowed */
1157 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1160 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1162 /* Tally up the load of all CPUs in the group */
1165 for_each_cpu_mask(i
, group
->cpumask
) {
1166 /* Bias balancing toward cpus of our domain */
1168 load
= source_load(i
, load_idx
);
1170 load
= target_load(i
, load_idx
);
1175 /* Adjust by relative CPU power of the group */
1176 avg_load
= (avg_load
* SCHED_LOAD_SCALE
) / group
->cpu_power
;
1179 this_load
= avg_load
;
1181 } else if (avg_load
< min_load
) {
1182 min_load
= avg_load
;
1186 group
= group
->next
;
1187 } while (group
!= sd
->groups
);
1189 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1195 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1198 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1201 unsigned long load
, min_load
= ULONG_MAX
;
1205 /* Traverse only the allowed CPUs */
1206 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1208 for_each_cpu_mask(i
, tmp
) {
1209 load
= weighted_cpuload(i
);
1211 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1221 * sched_balance_self: balance the current task (running on cpu) in domains
1222 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1225 * Balance, ie. select the least loaded group.
1227 * Returns the target CPU number, or the same CPU if no balancing is needed.
1229 * preempt must be disabled.
1231 static int sched_balance_self(int cpu
, int flag
)
1233 struct task_struct
*t
= current
;
1234 struct sched_domain
*tmp
, *sd
= NULL
;
1236 for_each_domain(cpu
, tmp
) {
1238 * If power savings logic is enabled for a domain, stop there.
1240 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1242 if (tmp
->flags
& flag
)
1248 struct sched_group
*group
;
1253 group
= find_idlest_group(sd
, t
, cpu
);
1257 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1258 if (new_cpu
== -1 || new_cpu
== cpu
)
1261 /* Now try balancing at a lower domain level */
1265 weight
= cpus_weight(span
);
1266 for_each_domain(cpu
, tmp
) {
1267 if (weight
<= cpus_weight(tmp
->span
))
1269 if (tmp
->flags
& flag
)
1272 /* while loop will break here if sd == NULL */
1278 #endif /* CONFIG_SMP */
1281 * wake_idle() will wake a task on an idle cpu if task->cpu is
1282 * not idle and an idle cpu is available. The span of cpus to
1283 * search starts with cpus closest then further out as needed,
1284 * so we always favor a closer, idle cpu.
1286 * Returns the CPU we should wake onto.
1288 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1289 static int wake_idle(int cpu
, task_t
*p
)
1292 struct sched_domain
*sd
;
1298 for_each_domain(cpu
, sd
) {
1299 if (sd
->flags
& SD_WAKE_IDLE
) {
1300 cpus_and(tmp
, sd
->span
, p
->cpus_allowed
);
1301 for_each_cpu_mask(i
, tmp
) {
1312 static inline int wake_idle(int cpu
, task_t
*p
)
1319 * try_to_wake_up - wake up a thread
1320 * @p: the to-be-woken-up thread
1321 * @state: the mask of task states that can be woken
1322 * @sync: do a synchronous wakeup?
1324 * Put it on the run-queue if it's not already there. The "current"
1325 * thread is always on the run-queue (except when the actual
1326 * re-schedule is in progress), and as such you're allowed to do
1327 * the simpler "current->state = TASK_RUNNING" to mark yourself
1328 * runnable without the overhead of this.
1330 * returns failure only if the task is already active.
1332 static int try_to_wake_up(task_t
*p
, unsigned int state
, int sync
)
1334 int cpu
, this_cpu
, success
= 0;
1335 unsigned long flags
;
1339 unsigned long load
, this_load
;
1340 struct sched_domain
*sd
, *this_sd
= NULL
;
1344 rq
= task_rq_lock(p
, &flags
);
1345 old_state
= p
->state
;
1346 if (!(old_state
& state
))
1353 this_cpu
= smp_processor_id();
1356 if (unlikely(task_running(rq
, p
)))
1361 schedstat_inc(rq
, ttwu_cnt
);
1362 if (cpu
== this_cpu
) {
1363 schedstat_inc(rq
, ttwu_local
);
1367 for_each_domain(this_cpu
, sd
) {
1368 if (cpu_isset(cpu
, sd
->span
)) {
1369 schedstat_inc(sd
, ttwu_wake_remote
);
1375 if (unlikely(!cpu_isset(this_cpu
, p
->cpus_allowed
)))
1379 * Check for affine wakeup and passive balancing possibilities.
1382 int idx
= this_sd
->wake_idx
;
1383 unsigned int imbalance
;
1385 imbalance
= 100 + (this_sd
->imbalance_pct
- 100) / 2;
1387 load
= source_load(cpu
, idx
);
1388 this_load
= target_load(this_cpu
, idx
);
1390 new_cpu
= this_cpu
; /* Wake to this CPU if we can */
1392 if (this_sd
->flags
& SD_WAKE_AFFINE
) {
1393 unsigned long tl
= this_load
;
1394 unsigned long tl_per_task
= cpu_avg_load_per_task(this_cpu
);
1397 * If sync wakeup then subtract the (maximum possible)
1398 * effect of the currently running task from the load
1399 * of the current CPU:
1402 tl
-= current
->load_weight
;
1405 tl
+ target_load(cpu
, idx
) <= tl_per_task
) ||
1406 100*(tl
+ p
->load_weight
) <= imbalance
*load
) {
1408 * This domain has SD_WAKE_AFFINE and
1409 * p is cache cold in this domain, and
1410 * there is no bad imbalance.
1412 schedstat_inc(this_sd
, ttwu_move_affine
);
1418 * Start passive balancing when half the imbalance_pct
1421 if (this_sd
->flags
& SD_WAKE_BALANCE
) {
1422 if (imbalance
*this_load
<= 100*load
) {
1423 schedstat_inc(this_sd
, ttwu_move_balance
);
1429 new_cpu
= cpu
; /* Could not wake to this_cpu. Wake to cpu instead */
1431 new_cpu
= wake_idle(new_cpu
, p
);
1432 if (new_cpu
!= cpu
) {
1433 set_task_cpu(p
, new_cpu
);
1434 task_rq_unlock(rq
, &flags
);
1435 /* might preempt at this point */
1436 rq
= task_rq_lock(p
, &flags
);
1437 old_state
= p
->state
;
1438 if (!(old_state
& state
))
1443 this_cpu
= smp_processor_id();
1448 #endif /* CONFIG_SMP */
1449 if (old_state
== TASK_UNINTERRUPTIBLE
) {
1450 rq
->nr_uninterruptible
--;
1452 * Tasks on involuntary sleep don't earn
1453 * sleep_avg beyond just interactive state.
1455 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
1459 * Tasks that have marked their sleep as noninteractive get
1460 * woken up with their sleep average not weighted in an
1463 if (old_state
& TASK_NONINTERACTIVE
)
1464 p
->sleep_type
= SLEEP_NONINTERACTIVE
;
1467 activate_task(p
, rq
, cpu
== this_cpu
);
1469 * Sync wakeups (i.e. those types of wakeups where the waker
1470 * has indicated that it will leave the CPU in short order)
1471 * don't trigger a preemption, if the woken up task will run on
1472 * this cpu. (in this case the 'I will reschedule' promise of
1473 * the waker guarantees that the freshly woken up task is going
1474 * to be considered on this CPU.)
1476 if (!sync
|| cpu
!= this_cpu
) {
1477 if (TASK_PREEMPTS_CURR(p
, rq
))
1478 resched_task(rq
->curr
);
1483 p
->state
= TASK_RUNNING
;
1485 task_rq_unlock(rq
, &flags
);
1490 int fastcall
wake_up_process(task_t
*p
)
1492 return try_to_wake_up(p
, TASK_STOPPED
| TASK_TRACED
|
1493 TASK_INTERRUPTIBLE
| TASK_UNINTERRUPTIBLE
, 0);
1495 EXPORT_SYMBOL(wake_up_process
);
1497 int fastcall
wake_up_state(task_t
*p
, unsigned int state
)
1499 return try_to_wake_up(p
, state
, 0);
1503 * Perform scheduler related setup for a newly forked process p.
1504 * p is forked by current.
1506 void fastcall
sched_fork(task_t
*p
, int clone_flags
)
1508 int cpu
= get_cpu();
1511 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
1513 set_task_cpu(p
, cpu
);
1516 * We mark the process as running here, but have not actually
1517 * inserted it onto the runqueue yet. This guarantees that
1518 * nobody will actually run it, and a signal or other external
1519 * event cannot wake it up and insert it on the runqueue either.
1521 p
->state
= TASK_RUNNING
;
1524 * Make sure we do not leak PI boosting priority to the child:
1526 p
->prio
= current
->normal_prio
;
1528 INIT_LIST_HEAD(&p
->run_list
);
1530 #ifdef CONFIG_SCHEDSTATS
1531 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1533 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1536 #ifdef CONFIG_PREEMPT
1537 /* Want to start with kernel preemption disabled. */
1538 task_thread_info(p
)->preempt_count
= 1;
1541 * Share the timeslice between parent and child, thus the
1542 * total amount of pending timeslices in the system doesn't change,
1543 * resulting in more scheduling fairness.
1545 local_irq_disable();
1546 p
->time_slice
= (current
->time_slice
+ 1) >> 1;
1548 * The remainder of the first timeslice might be recovered by
1549 * the parent if the child exits early enough.
1551 p
->first_time_slice
= 1;
1552 current
->time_slice
>>= 1;
1553 p
->timestamp
= sched_clock();
1554 if (unlikely(!current
->time_slice
)) {
1556 * This case is rare, it happens when the parent has only
1557 * a single jiffy left from its timeslice. Taking the
1558 * runqueue lock is not a problem.
1560 current
->time_slice
= 1;
1568 * wake_up_new_task - wake up a newly created task for the first time.
1570 * This function will do some initial scheduler statistics housekeeping
1571 * that must be done for every newly created context, then puts the task
1572 * on the runqueue and wakes it.
1574 void fastcall
wake_up_new_task(task_t
*p
, unsigned long clone_flags
)
1576 unsigned long flags
;
1578 runqueue_t
*rq
, *this_rq
;
1580 rq
= task_rq_lock(p
, &flags
);
1581 BUG_ON(p
->state
!= TASK_RUNNING
);
1582 this_cpu
= smp_processor_id();
1586 * We decrease the sleep average of forking parents
1587 * and children as well, to keep max-interactive tasks
1588 * from forking tasks that are max-interactive. The parent
1589 * (current) is done further down, under its lock.
1591 p
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(p
) *
1592 CHILD_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1594 p
->prio
= effective_prio(p
);
1596 if (likely(cpu
== this_cpu
)) {
1597 if (!(clone_flags
& CLONE_VM
)) {
1599 * The VM isn't cloned, so we're in a good position to
1600 * do child-runs-first in anticipation of an exec. This
1601 * usually avoids a lot of COW overhead.
1603 if (unlikely(!current
->array
))
1604 __activate_task(p
, rq
);
1606 p
->prio
= current
->prio
;
1607 p
->normal_prio
= current
->normal_prio
;
1608 list_add_tail(&p
->run_list
, ¤t
->run_list
);
1609 p
->array
= current
->array
;
1610 p
->array
->nr_active
++;
1611 inc_nr_running(p
, rq
);
1615 /* Run child last */
1616 __activate_task(p
, rq
);
1618 * We skip the following code due to cpu == this_cpu
1620 * task_rq_unlock(rq, &flags);
1621 * this_rq = task_rq_lock(current, &flags);
1625 this_rq
= cpu_rq(this_cpu
);
1628 * Not the local CPU - must adjust timestamp. This should
1629 * get optimised away in the !CONFIG_SMP case.
1631 p
->timestamp
= (p
->timestamp
- this_rq
->timestamp_last_tick
)
1632 + rq
->timestamp_last_tick
;
1633 __activate_task(p
, rq
);
1634 if (TASK_PREEMPTS_CURR(p
, rq
))
1635 resched_task(rq
->curr
);
1638 * Parent and child are on different CPUs, now get the
1639 * parent runqueue to update the parent's ->sleep_avg:
1641 task_rq_unlock(rq
, &flags
);
1642 this_rq
= task_rq_lock(current
, &flags
);
1644 current
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(current
) *
1645 PARENT_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1646 task_rq_unlock(this_rq
, &flags
);
1650 * Potentially available exiting-child timeslices are
1651 * retrieved here - this way the parent does not get
1652 * penalized for creating too many threads.
1654 * (this cannot be used to 'generate' timeslices
1655 * artificially, because any timeslice recovered here
1656 * was given away by the parent in the first place.)
1658 void fastcall
sched_exit(task_t
*p
)
1660 unsigned long flags
;
1664 * If the child was a (relative-) CPU hog then decrease
1665 * the sleep_avg of the parent as well.
1667 rq
= task_rq_lock(p
->parent
, &flags
);
1668 if (p
->first_time_slice
&& task_cpu(p
) == task_cpu(p
->parent
)) {
1669 p
->parent
->time_slice
+= p
->time_slice
;
1670 if (unlikely(p
->parent
->time_slice
> task_timeslice(p
)))
1671 p
->parent
->time_slice
= task_timeslice(p
);
1673 if (p
->sleep_avg
< p
->parent
->sleep_avg
)
1674 p
->parent
->sleep_avg
= p
->parent
->sleep_avg
/
1675 (EXIT_WEIGHT
+ 1) * EXIT_WEIGHT
+ p
->sleep_avg
/
1677 task_rq_unlock(rq
, &flags
);
1681 * prepare_task_switch - prepare to switch tasks
1682 * @rq: the runqueue preparing to switch
1683 * @next: the task we are going to switch to.
1685 * This is called with the rq lock held and interrupts off. It must
1686 * be paired with a subsequent finish_task_switch after the context
1689 * prepare_task_switch sets up locking and calls architecture specific
1692 static inline void prepare_task_switch(runqueue_t
*rq
, task_t
*next
)
1694 prepare_lock_switch(rq
, next
);
1695 prepare_arch_switch(next
);
1699 * finish_task_switch - clean up after a task-switch
1700 * @rq: runqueue associated with task-switch
1701 * @prev: the thread we just switched away from.
1703 * finish_task_switch must be called after the context switch, paired
1704 * with a prepare_task_switch call before the context switch.
1705 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1706 * and do any other architecture-specific cleanup actions.
1708 * Note that we may have delayed dropping an mm in context_switch(). If
1709 * so, we finish that here outside of the runqueue lock. (Doing it
1710 * with the lock held can cause deadlocks; see schedule() for
1713 static inline void finish_task_switch(runqueue_t
*rq
, task_t
*prev
)
1714 __releases(rq
->lock
)
1716 struct mm_struct
*mm
= rq
->prev_mm
;
1717 unsigned long prev_task_flags
;
1722 * A task struct has one reference for the use as "current".
1723 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1724 * calls schedule one last time. The schedule call will never return,
1725 * and the scheduled task must drop that reference.
1726 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1727 * still held, otherwise prev could be scheduled on another cpu, die
1728 * there before we look at prev->state, and then the reference would
1730 * Manfred Spraul <manfred@colorfullife.com>
1732 prev_task_flags
= prev
->flags
;
1733 finish_arch_switch(prev
);
1734 finish_lock_switch(rq
, prev
);
1737 if (unlikely(prev_task_flags
& PF_DEAD
)) {
1739 * Remove function-return probe instances associated with this
1740 * task and put them back on the free list.
1742 kprobe_flush_task(prev
);
1743 put_task_struct(prev
);
1748 * schedule_tail - first thing a freshly forked thread must call.
1749 * @prev: the thread we just switched away from.
1751 asmlinkage
void schedule_tail(task_t
*prev
)
1752 __releases(rq
->lock
)
1754 runqueue_t
*rq
= this_rq();
1755 finish_task_switch(rq
, prev
);
1756 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1757 /* In this case, finish_task_switch does not reenable preemption */
1760 if (current
->set_child_tid
)
1761 put_user(current
->pid
, current
->set_child_tid
);
1765 * context_switch - switch to the new MM and the new
1766 * thread's register state.
1769 task_t
* context_switch(runqueue_t
*rq
, task_t
*prev
, task_t
*next
)
1771 struct mm_struct
*mm
= next
->mm
;
1772 struct mm_struct
*oldmm
= prev
->active_mm
;
1774 if (unlikely(!mm
)) {
1775 next
->active_mm
= oldmm
;
1776 atomic_inc(&oldmm
->mm_count
);
1777 enter_lazy_tlb(oldmm
, next
);
1779 switch_mm(oldmm
, mm
, next
);
1781 if (unlikely(!prev
->mm
)) {
1782 prev
->active_mm
= NULL
;
1783 WARN_ON(rq
->prev_mm
);
1784 rq
->prev_mm
= oldmm
;
1786 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
1788 /* Here we just switch the register state and the stack. */
1789 switch_to(prev
, next
, prev
);
1795 * nr_running, nr_uninterruptible and nr_context_switches:
1797 * externally visible scheduler statistics: current number of runnable
1798 * threads, current number of uninterruptible-sleeping threads, total
1799 * number of context switches performed since bootup.
1801 unsigned long nr_running(void)
1803 unsigned long i
, sum
= 0;
1805 for_each_online_cpu(i
)
1806 sum
+= cpu_rq(i
)->nr_running
;
1811 unsigned long nr_uninterruptible(void)
1813 unsigned long i
, sum
= 0;
1815 for_each_possible_cpu(i
)
1816 sum
+= cpu_rq(i
)->nr_uninterruptible
;
1819 * Since we read the counters lockless, it might be slightly
1820 * inaccurate. Do not allow it to go below zero though:
1822 if (unlikely((long)sum
< 0))
1828 unsigned long long nr_context_switches(void)
1831 unsigned long long sum
= 0;
1833 for_each_possible_cpu(i
)
1834 sum
+= cpu_rq(i
)->nr_switches
;
1839 unsigned long nr_iowait(void)
1841 unsigned long i
, sum
= 0;
1843 for_each_possible_cpu(i
)
1844 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
1849 unsigned long nr_active(void)
1851 unsigned long i
, running
= 0, uninterruptible
= 0;
1853 for_each_online_cpu(i
) {
1854 running
+= cpu_rq(i
)->nr_running
;
1855 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
1858 if (unlikely((long)uninterruptible
< 0))
1859 uninterruptible
= 0;
1861 return running
+ uninterruptible
;
1867 * Is this task likely cache-hot:
1870 task_hot(struct task_struct
*p
, unsigned long long now
, struct sched_domain
*sd
)
1872 return (long long)(now
- p
->last_ran
) < (long long)sd
->cache_hot_time
;
1876 * double_rq_lock - safely lock two runqueues
1878 * Note this does not disable interrupts like task_rq_lock,
1879 * you need to do so manually before calling.
1881 static void double_rq_lock(runqueue_t
*rq1
, runqueue_t
*rq2
)
1882 __acquires(rq1
->lock
)
1883 __acquires(rq2
->lock
)
1886 spin_lock(&rq1
->lock
);
1887 __acquire(rq2
->lock
); /* Fake it out ;) */
1890 spin_lock(&rq1
->lock
);
1891 spin_lock(&rq2
->lock
);
1893 spin_lock(&rq2
->lock
);
1894 spin_lock(&rq1
->lock
);
1900 * double_rq_unlock - safely unlock two runqueues
1902 * Note this does not restore interrupts like task_rq_unlock,
1903 * you need to do so manually after calling.
1905 static void double_rq_unlock(runqueue_t
*rq1
, runqueue_t
*rq2
)
1906 __releases(rq1
->lock
)
1907 __releases(rq2
->lock
)
1909 spin_unlock(&rq1
->lock
);
1911 spin_unlock(&rq2
->lock
);
1913 __release(rq2
->lock
);
1917 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1919 static void double_lock_balance(runqueue_t
*this_rq
, runqueue_t
*busiest
)
1920 __releases(this_rq
->lock
)
1921 __acquires(busiest
->lock
)
1922 __acquires(this_rq
->lock
)
1924 if (unlikely(!spin_trylock(&busiest
->lock
))) {
1925 if (busiest
< this_rq
) {
1926 spin_unlock(&this_rq
->lock
);
1927 spin_lock(&busiest
->lock
);
1928 spin_lock(&this_rq
->lock
);
1930 spin_lock(&busiest
->lock
);
1935 * If dest_cpu is allowed for this process, migrate the task to it.
1936 * This is accomplished by forcing the cpu_allowed mask to only
1937 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1938 * the cpu_allowed mask is restored.
1940 static void sched_migrate_task(task_t
*p
, int dest_cpu
)
1942 migration_req_t req
;
1944 unsigned long flags
;
1946 rq
= task_rq_lock(p
, &flags
);
1947 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
1948 || unlikely(cpu_is_offline(dest_cpu
)))
1951 /* force the process onto the specified CPU */
1952 if (migrate_task(p
, dest_cpu
, &req
)) {
1953 /* Need to wait for migration thread (might exit: take ref). */
1954 struct task_struct
*mt
= rq
->migration_thread
;
1955 get_task_struct(mt
);
1956 task_rq_unlock(rq
, &flags
);
1957 wake_up_process(mt
);
1958 put_task_struct(mt
);
1959 wait_for_completion(&req
.done
);
1963 task_rq_unlock(rq
, &flags
);
1967 * sched_exec - execve() is a valuable balancing opportunity, because at
1968 * this point the task has the smallest effective memory and cache footprint.
1970 void sched_exec(void)
1972 int new_cpu
, this_cpu
= get_cpu();
1973 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
1975 if (new_cpu
!= this_cpu
)
1976 sched_migrate_task(current
, new_cpu
);
1980 * pull_task - move a task from a remote runqueue to the local runqueue.
1981 * Both runqueues must be locked.
1984 void pull_task(runqueue_t
*src_rq
, prio_array_t
*src_array
, task_t
*p
,
1985 runqueue_t
*this_rq
, prio_array_t
*this_array
, int this_cpu
)
1987 dequeue_task(p
, src_array
);
1988 dec_nr_running(p
, src_rq
);
1989 set_task_cpu(p
, this_cpu
);
1990 inc_nr_running(p
, this_rq
);
1991 enqueue_task(p
, this_array
);
1992 p
->timestamp
= (p
->timestamp
- src_rq
->timestamp_last_tick
)
1993 + this_rq
->timestamp_last_tick
;
1995 * Note that idle threads have a prio of MAX_PRIO, for this test
1996 * to be always true for them.
1998 if (TASK_PREEMPTS_CURR(p
, this_rq
))
1999 resched_task(this_rq
->curr
);
2003 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2006 int can_migrate_task(task_t
*p
, runqueue_t
*rq
, int this_cpu
,
2007 struct sched_domain
*sd
, enum idle_type idle
,
2011 * We do not migrate tasks that are:
2012 * 1) running (obviously), or
2013 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2014 * 3) are cache-hot on their current CPU.
2016 if (!cpu_isset(this_cpu
, p
->cpus_allowed
))
2020 if (task_running(rq
, p
))
2024 * Aggressive migration if:
2025 * 1) task is cache cold, or
2026 * 2) too many balance attempts have failed.
2029 if (sd
->nr_balance_failed
> sd
->cache_nice_tries
)
2032 if (task_hot(p
, rq
->timestamp_last_tick
, sd
))
2037 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2040 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2041 * load from busiest to this_rq, as part of a balancing operation within
2042 * "domain". Returns the number of tasks moved.
2044 * Called with both runqueues locked.
2046 static int move_tasks(runqueue_t
*this_rq
, int this_cpu
, runqueue_t
*busiest
,
2047 unsigned long max_nr_move
, unsigned long max_load_move
,
2048 struct sched_domain
*sd
, enum idle_type idle
,
2051 int idx
, pulled
= 0, pinned
= 0, this_best_prio
, best_prio
,
2052 best_prio_seen
, skip_for_load
;
2053 prio_array_t
*array
, *dst_array
;
2054 struct list_head
*head
, *curr
;
2058 if (max_nr_move
== 0 || max_load_move
== 0)
2061 rem_load_move
= max_load_move
;
2063 this_best_prio
= rq_best_prio(this_rq
);
2064 best_prio
= rq_best_prio(busiest
);
2066 * Enable handling of the case where there is more than one task
2067 * with the best priority. If the current running task is one
2068 * of those with prio==best_prio we know it won't be moved
2069 * and therefore it's safe to override the skip (based on load) of
2070 * any task we find with that prio.
2072 best_prio_seen
= best_prio
== busiest
->curr
->prio
;
2075 * We first consider expired tasks. Those will likely not be
2076 * executed in the near future, and they are most likely to
2077 * be cache-cold, thus switching CPUs has the least effect
2080 if (busiest
->expired
->nr_active
) {
2081 array
= busiest
->expired
;
2082 dst_array
= this_rq
->expired
;
2084 array
= busiest
->active
;
2085 dst_array
= this_rq
->active
;
2089 /* Start searching at priority 0: */
2093 idx
= sched_find_first_bit(array
->bitmap
);
2095 idx
= find_next_bit(array
->bitmap
, MAX_PRIO
, idx
);
2096 if (idx
>= MAX_PRIO
) {
2097 if (array
== busiest
->expired
&& busiest
->active
->nr_active
) {
2098 array
= busiest
->active
;
2099 dst_array
= this_rq
->active
;
2105 head
= array
->queue
+ idx
;
2108 tmp
= list_entry(curr
, task_t
, run_list
);
2113 * To help distribute high priority tasks accross CPUs we don't
2114 * skip a task if it will be the highest priority task (i.e. smallest
2115 * prio value) on its new queue regardless of its load weight
2117 skip_for_load
= tmp
->load_weight
> rem_load_move
;
2118 if (skip_for_load
&& idx
< this_best_prio
)
2119 skip_for_load
= !best_prio_seen
&& idx
== best_prio
;
2120 if (skip_for_load
||
2121 !can_migrate_task(tmp
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2123 best_prio_seen
|= idx
== best_prio
;
2130 #ifdef CONFIG_SCHEDSTATS
2131 if (task_hot(tmp
, busiest
->timestamp_last_tick
, sd
))
2132 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2135 pull_task(busiest
, array
, tmp
, this_rq
, dst_array
, this_cpu
);
2137 rem_load_move
-= tmp
->load_weight
;
2140 * We only want to steal up to the prescribed number of tasks
2141 * and the prescribed amount of weighted load.
2143 if (pulled
< max_nr_move
&& rem_load_move
> 0) {
2144 if (idx
< this_best_prio
)
2145 this_best_prio
= idx
;
2153 * Right now, this is the only place pull_task() is called,
2154 * so we can safely collect pull_task() stats here rather than
2155 * inside pull_task().
2157 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2160 *all_pinned
= pinned
;
2165 * find_busiest_group finds and returns the busiest CPU group within the
2166 * domain. It calculates and returns the amount of weighted load which
2167 * should be moved to restore balance via the imbalance parameter.
2169 static struct sched_group
*
2170 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2171 unsigned long *imbalance
, enum idle_type idle
, int *sd_idle
)
2173 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2174 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2175 unsigned long max_pull
;
2176 unsigned long busiest_load_per_task
, busiest_nr_running
;
2177 unsigned long this_load_per_task
, this_nr_running
;
2179 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2180 int power_savings_balance
= 1;
2181 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2182 unsigned long min_nr_running
= ULONG_MAX
;
2183 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2186 max_load
= this_load
= total_load
= total_pwr
= 0;
2187 busiest_load_per_task
= busiest_nr_running
= 0;
2188 this_load_per_task
= this_nr_running
= 0;
2189 if (idle
== NOT_IDLE
)
2190 load_idx
= sd
->busy_idx
;
2191 else if (idle
== NEWLY_IDLE
)
2192 load_idx
= sd
->newidle_idx
;
2194 load_idx
= sd
->idle_idx
;
2197 unsigned long load
, group_capacity
;
2200 unsigned long sum_nr_running
, sum_weighted_load
;
2202 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2204 /* Tally up the load of all CPUs in the group */
2205 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2207 for_each_cpu_mask(i
, group
->cpumask
) {
2208 runqueue_t
*rq
= cpu_rq(i
);
2210 if (*sd_idle
&& !idle_cpu(i
))
2213 /* Bias balancing toward cpus of our domain */
2215 load
= target_load(i
, load_idx
);
2217 load
= source_load(i
, load_idx
);
2220 sum_nr_running
+= rq
->nr_running
;
2221 sum_weighted_load
+= rq
->raw_weighted_load
;
2224 total_load
+= avg_load
;
2225 total_pwr
+= group
->cpu_power
;
2227 /* Adjust by relative CPU power of the group */
2228 avg_load
= (avg_load
* SCHED_LOAD_SCALE
) / group
->cpu_power
;
2230 group_capacity
= group
->cpu_power
/ SCHED_LOAD_SCALE
;
2233 this_load
= avg_load
;
2235 this_nr_running
= sum_nr_running
;
2236 this_load_per_task
= sum_weighted_load
;
2237 } else if (avg_load
> max_load
&&
2238 sum_nr_running
> group_capacity
) {
2239 max_load
= avg_load
;
2241 busiest_nr_running
= sum_nr_running
;
2242 busiest_load_per_task
= sum_weighted_load
;
2245 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2247 * Busy processors will not participate in power savings
2250 if (idle
== NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2254 * If the local group is idle or completely loaded
2255 * no need to do power savings balance at this domain
2257 if (local_group
&& (this_nr_running
>= group_capacity
||
2259 power_savings_balance
= 0;
2262 * If a group is already running at full capacity or idle,
2263 * don't include that group in power savings calculations
2265 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2270 * Calculate the group which has the least non-idle load.
2271 * This is the group from where we need to pick up the load
2274 if ((sum_nr_running
< min_nr_running
) ||
2275 (sum_nr_running
== min_nr_running
&&
2276 first_cpu(group
->cpumask
) <
2277 first_cpu(group_min
->cpumask
))) {
2279 min_nr_running
= sum_nr_running
;
2280 min_load_per_task
= sum_weighted_load
/
2285 * Calculate the group which is almost near its
2286 * capacity but still has some space to pick up some load
2287 * from other group and save more power
2289 if (sum_nr_running
<= group_capacity
- 1) {
2290 if (sum_nr_running
> leader_nr_running
||
2291 (sum_nr_running
== leader_nr_running
&&
2292 first_cpu(group
->cpumask
) >
2293 first_cpu(group_leader
->cpumask
))) {
2294 group_leader
= group
;
2295 leader_nr_running
= sum_nr_running
;
2300 group
= group
->next
;
2301 } while (group
!= sd
->groups
);
2303 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2306 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2308 if (this_load
>= avg_load
||
2309 100*max_load
<= sd
->imbalance_pct
*this_load
)
2312 busiest_load_per_task
/= busiest_nr_running
;
2314 * We're trying to get all the cpus to the average_load, so we don't
2315 * want to push ourselves above the average load, nor do we wish to
2316 * reduce the max loaded cpu below the average load, as either of these
2317 * actions would just result in more rebalancing later, and ping-pong
2318 * tasks around. Thus we look for the minimum possible imbalance.
2319 * Negative imbalances (*we* are more loaded than anyone else) will
2320 * be counted as no imbalance for these purposes -- we can't fix that
2321 * by pulling tasks to us. Be careful of negative numbers as they'll
2322 * appear as very large values with unsigned longs.
2324 if (max_load
<= busiest_load_per_task
)
2328 * In the presence of smp nice balancing, certain scenarios can have
2329 * max load less than avg load(as we skip the groups at or below
2330 * its cpu_power, while calculating max_load..)
2332 if (max_load
< avg_load
) {
2334 goto small_imbalance
;
2337 /* Don't want to pull so many tasks that a group would go idle */
2338 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2340 /* How much load to actually move to equalise the imbalance */
2341 *imbalance
= min(max_pull
* busiest
->cpu_power
,
2342 (avg_load
- this_load
) * this->cpu_power
)
2346 * if *imbalance is less than the average load per runnable task
2347 * there is no gaurantee that any tasks will be moved so we'll have
2348 * a think about bumping its value to force at least one task to be
2351 if (*imbalance
< busiest_load_per_task
) {
2352 unsigned long tmp
, pwr_now
, pwr_move
;
2356 pwr_move
= pwr_now
= 0;
2358 if (this_nr_running
) {
2359 this_load_per_task
/= this_nr_running
;
2360 if (busiest_load_per_task
> this_load_per_task
)
2363 this_load_per_task
= SCHED_LOAD_SCALE
;
2365 if (max_load
- this_load
>= busiest_load_per_task
* imbn
) {
2366 *imbalance
= busiest_load_per_task
;
2371 * OK, we don't have enough imbalance to justify moving tasks,
2372 * however we may be able to increase total CPU power used by
2376 pwr_now
+= busiest
->cpu_power
*
2377 min(busiest_load_per_task
, max_load
);
2378 pwr_now
+= this->cpu_power
*
2379 min(this_load_per_task
, this_load
);
2380 pwr_now
/= SCHED_LOAD_SCALE
;
2382 /* Amount of load we'd subtract */
2383 tmp
= busiest_load_per_task
*SCHED_LOAD_SCALE
/busiest
->cpu_power
;
2385 pwr_move
+= busiest
->cpu_power
*
2386 min(busiest_load_per_task
, max_load
- tmp
);
2388 /* Amount of load we'd add */
2389 if (max_load
*busiest
->cpu_power
<
2390 busiest_load_per_task
*SCHED_LOAD_SCALE
)
2391 tmp
= max_load
*busiest
->cpu_power
/this->cpu_power
;
2393 tmp
= busiest_load_per_task
*SCHED_LOAD_SCALE
/this->cpu_power
;
2394 pwr_move
+= this->cpu_power
*min(this_load_per_task
, this_load
+ tmp
);
2395 pwr_move
/= SCHED_LOAD_SCALE
;
2397 /* Move if we gain throughput */
2398 if (pwr_move
<= pwr_now
)
2401 *imbalance
= busiest_load_per_task
;
2407 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2408 if (idle
== NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2411 if (this == group_leader
&& group_leader
!= group_min
) {
2412 *imbalance
= min_load_per_task
;
2422 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2425 find_busiest_queue(struct sched_group
*group
, enum idle_type idle
,
2426 unsigned long imbalance
)
2428 runqueue_t
*busiest
= NULL
, *rq
;
2429 unsigned long max_load
= 0;
2432 for_each_cpu_mask(i
, group
->cpumask
) {
2435 if (rq
->nr_running
== 1 && rq
->raw_weighted_load
> imbalance
)
2438 if (rq
->raw_weighted_load
> max_load
) {
2439 max_load
= rq
->raw_weighted_load
;
2448 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2449 * so long as it is large enough.
2451 #define MAX_PINNED_INTERVAL 512
2453 static inline unsigned long minus_1_or_zero(unsigned long n
)
2455 return n
> 0 ? n
- 1 : 0;
2459 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2460 * tasks if there is an imbalance.
2462 * Called with this_rq unlocked.
2464 static int load_balance(int this_cpu
, runqueue_t
*this_rq
,
2465 struct sched_domain
*sd
, enum idle_type idle
)
2467 int nr_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
2468 struct sched_group
*group
;
2469 unsigned long imbalance
;
2470 runqueue_t
*busiest
;
2472 if (idle
!= NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2473 !sched_smt_power_savings
)
2476 schedstat_inc(sd
, lb_cnt
[idle
]);
2478 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
);
2480 schedstat_inc(sd
, lb_nobusyg
[idle
]);
2484 busiest
= find_busiest_queue(group
, idle
, imbalance
);
2486 schedstat_inc(sd
, lb_nobusyq
[idle
]);
2490 BUG_ON(busiest
== this_rq
);
2492 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
2495 if (busiest
->nr_running
> 1) {
2497 * Attempt to move tasks. If find_busiest_group has found
2498 * an imbalance but busiest->nr_running <= 1, the group is
2499 * still unbalanced. nr_moved simply stays zero, so it is
2500 * correctly treated as an imbalance.
2502 double_rq_lock(this_rq
, busiest
);
2503 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2504 minus_1_or_zero(busiest
->nr_running
),
2505 imbalance
, sd
, idle
, &all_pinned
);
2506 double_rq_unlock(this_rq
, busiest
);
2508 /* All tasks on this runqueue were pinned by CPU affinity */
2509 if (unlikely(all_pinned
))
2514 schedstat_inc(sd
, lb_failed
[idle
]);
2515 sd
->nr_balance_failed
++;
2517 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
2519 spin_lock(&busiest
->lock
);
2521 /* don't kick the migration_thread, if the curr
2522 * task on busiest cpu can't be moved to this_cpu
2524 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
2525 spin_unlock(&busiest
->lock
);
2527 goto out_one_pinned
;
2530 if (!busiest
->active_balance
) {
2531 busiest
->active_balance
= 1;
2532 busiest
->push_cpu
= this_cpu
;
2535 spin_unlock(&busiest
->lock
);
2537 wake_up_process(busiest
->migration_thread
);
2540 * We've kicked active balancing, reset the failure
2543 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
2546 sd
->nr_balance_failed
= 0;
2548 if (likely(!active_balance
)) {
2549 /* We were unbalanced, so reset the balancing interval */
2550 sd
->balance_interval
= sd
->min_interval
;
2553 * If we've begun active balancing, start to back off. This
2554 * case may not be covered by the all_pinned logic if there
2555 * is only 1 task on the busy runqueue (because we don't call
2558 if (sd
->balance_interval
< sd
->max_interval
)
2559 sd
->balance_interval
*= 2;
2562 if (!nr_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2563 !sched_smt_power_savings
)
2568 schedstat_inc(sd
, lb_balanced
[idle
]);
2570 sd
->nr_balance_failed
= 0;
2573 /* tune up the balancing interval */
2574 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
2575 (sd
->balance_interval
< sd
->max_interval
))
2576 sd
->balance_interval
*= 2;
2578 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2579 !sched_smt_power_savings
)
2585 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2586 * tasks if there is an imbalance.
2588 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2589 * this_rq is locked.
2592 load_balance_newidle(int this_cpu
, runqueue_t
*this_rq
, struct sched_domain
*sd
)
2594 struct sched_group
*group
;
2595 runqueue_t
*busiest
= NULL
;
2596 unsigned long imbalance
;
2600 if (sd
->flags
& SD_SHARE_CPUPOWER
&& !sched_smt_power_savings
)
2603 schedstat_inc(sd
, lb_cnt
[NEWLY_IDLE
]);
2604 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, NEWLY_IDLE
, &sd_idle
);
2606 schedstat_inc(sd
, lb_nobusyg
[NEWLY_IDLE
]);
2610 busiest
= find_busiest_queue(group
, NEWLY_IDLE
, imbalance
);
2612 schedstat_inc(sd
, lb_nobusyq
[NEWLY_IDLE
]);
2616 BUG_ON(busiest
== this_rq
);
2618 schedstat_add(sd
, lb_imbalance
[NEWLY_IDLE
], imbalance
);
2621 if (busiest
->nr_running
> 1) {
2622 /* Attempt to move tasks */
2623 double_lock_balance(this_rq
, busiest
);
2624 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2625 minus_1_or_zero(busiest
->nr_running
),
2626 imbalance
, sd
, NEWLY_IDLE
, NULL
);
2627 spin_unlock(&busiest
->lock
);
2631 schedstat_inc(sd
, lb_failed
[NEWLY_IDLE
]);
2632 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
)
2635 sd
->nr_balance_failed
= 0;
2640 schedstat_inc(sd
, lb_balanced
[NEWLY_IDLE
]);
2641 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2642 !sched_smt_power_savings
)
2644 sd
->nr_balance_failed
= 0;
2650 * idle_balance is called by schedule() if this_cpu is about to become
2651 * idle. Attempts to pull tasks from other CPUs.
2653 static void idle_balance(int this_cpu
, runqueue_t
*this_rq
)
2655 struct sched_domain
*sd
;
2657 for_each_domain(this_cpu
, sd
) {
2658 if (sd
->flags
& SD_BALANCE_NEWIDLE
) {
2659 /* If we've pulled tasks over stop searching: */
2660 if (load_balance_newidle(this_cpu
, this_rq
, sd
))
2667 * active_load_balance is run by migration threads. It pushes running tasks
2668 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2669 * running on each physical CPU where possible, and avoids physical /
2670 * logical imbalances.
2672 * Called with busiest_rq locked.
2674 static void active_load_balance(runqueue_t
*busiest_rq
, int busiest_cpu
)
2676 struct sched_domain
*sd
;
2677 runqueue_t
*target_rq
;
2678 int target_cpu
= busiest_rq
->push_cpu
;
2680 /* Is there any task to move? */
2681 if (busiest_rq
->nr_running
<= 1)
2684 target_rq
= cpu_rq(target_cpu
);
2687 * This condition is "impossible", if it occurs
2688 * we need to fix it. Originally reported by
2689 * Bjorn Helgaas on a 128-cpu setup.
2691 BUG_ON(busiest_rq
== target_rq
);
2693 /* move a task from busiest_rq to target_rq */
2694 double_lock_balance(busiest_rq
, target_rq
);
2696 /* Search for an sd spanning us and the target CPU. */
2697 for_each_domain(target_cpu
, sd
) {
2698 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
2699 cpu_isset(busiest_cpu
, sd
->span
))
2704 schedstat_inc(sd
, alb_cnt
);
2706 if (move_tasks(target_rq
, target_cpu
, busiest_rq
, 1,
2707 RTPRIO_TO_LOAD_WEIGHT(100), sd
, SCHED_IDLE
,
2709 schedstat_inc(sd
, alb_pushed
);
2711 schedstat_inc(sd
, alb_failed
);
2713 spin_unlock(&target_rq
->lock
);
2717 * rebalance_tick will get called every timer tick, on every CPU.
2719 * It checks each scheduling domain to see if it is due to be balanced,
2720 * and initiates a balancing operation if so.
2722 * Balancing parameters are set up in arch_init_sched_domains.
2725 /* Don't have all balancing operations going off at once: */
2726 static inline unsigned long cpu_offset(int cpu
)
2728 return jiffies
+ cpu
* HZ
/ NR_CPUS
;
2732 rebalance_tick(int this_cpu
, runqueue_t
*this_rq
, enum idle_type idle
)
2734 unsigned long this_load
, interval
, j
= cpu_offset(this_cpu
);
2735 struct sched_domain
*sd
;
2738 this_load
= this_rq
->raw_weighted_load
;
2740 /* Update our load: */
2741 for (i
= 0, scale
= 1; i
< 3; i
++, scale
<<= 1) {
2742 unsigned long old_load
, new_load
;
2744 old_load
= this_rq
->cpu_load
[i
];
2745 new_load
= this_load
;
2747 * Round up the averaging division if load is increasing. This
2748 * prevents us from getting stuck on 9 if the load is 10, for
2751 if (new_load
> old_load
)
2752 new_load
+= scale
-1;
2753 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) / scale
;
2756 for_each_domain(this_cpu
, sd
) {
2757 if (!(sd
->flags
& SD_LOAD_BALANCE
))
2760 interval
= sd
->balance_interval
;
2761 if (idle
!= SCHED_IDLE
)
2762 interval
*= sd
->busy_factor
;
2764 /* scale ms to jiffies */
2765 interval
= msecs_to_jiffies(interval
);
2766 if (unlikely(!interval
))
2769 if (j
- sd
->last_balance
>= interval
) {
2770 if (load_balance(this_cpu
, this_rq
, sd
, idle
)) {
2772 * We've pulled tasks over so either we're no
2773 * longer idle, or one of our SMT siblings is
2778 sd
->last_balance
+= interval
;
2784 * on UP we do not need to balance between CPUs:
2786 static inline void rebalance_tick(int cpu
, runqueue_t
*rq
, enum idle_type idle
)
2789 static inline void idle_balance(int cpu
, runqueue_t
*rq
)
2794 static inline int wake_priority_sleeper(runqueue_t
*rq
)
2798 #ifdef CONFIG_SCHED_SMT
2799 spin_lock(&rq
->lock
);
2801 * If an SMT sibling task has been put to sleep for priority
2802 * reasons reschedule the idle task to see if it can now run.
2804 if (rq
->nr_running
) {
2805 resched_task(rq
->idle
);
2808 spin_unlock(&rq
->lock
);
2813 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
2815 EXPORT_PER_CPU_SYMBOL(kstat
);
2818 * This is called on clock ticks and on context switches.
2819 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2822 update_cpu_clock(task_t
*p
, runqueue_t
*rq
, unsigned long long now
)
2824 p
->sched_time
+= now
- max(p
->timestamp
, rq
->timestamp_last_tick
);
2828 * Return current->sched_time plus any more ns on the sched_clock
2829 * that have not yet been banked.
2831 unsigned long long current_sched_time(const task_t
*p
)
2833 unsigned long long ns
;
2834 unsigned long flags
;
2836 local_irq_save(flags
);
2837 ns
= max(p
->timestamp
, task_rq(p
)->timestamp_last_tick
);
2838 ns
= p
->sched_time
+ sched_clock() - ns
;
2839 local_irq_restore(flags
);
2845 * We place interactive tasks back into the active array, if possible.
2847 * To guarantee that this does not starve expired tasks we ignore the
2848 * interactivity of a task if the first expired task had to wait more
2849 * than a 'reasonable' amount of time. This deadline timeout is
2850 * load-dependent, as the frequency of array switched decreases with
2851 * increasing number of running tasks. We also ignore the interactivity
2852 * if a better static_prio task has expired:
2854 static inline int expired_starving(runqueue_t
*rq
)
2856 if (rq
->curr
->static_prio
> rq
->best_expired_prio
)
2858 if (!STARVATION_LIMIT
|| !rq
->expired_timestamp
)
2860 if (jiffies
- rq
->expired_timestamp
> STARVATION_LIMIT
* rq
->nr_running
)
2866 * Account user cpu time to a process.
2867 * @p: the process that the cpu time gets accounted to
2868 * @hardirq_offset: the offset to subtract from hardirq_count()
2869 * @cputime: the cpu time spent in user space since the last update
2871 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
2873 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2876 p
->utime
= cputime_add(p
->utime
, cputime
);
2878 /* Add user time to cpustat. */
2879 tmp
= cputime_to_cputime64(cputime
);
2880 if (TASK_NICE(p
) > 0)
2881 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
2883 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
2887 * Account system cpu time to a process.
2888 * @p: the process that the cpu time gets accounted to
2889 * @hardirq_offset: the offset to subtract from hardirq_count()
2890 * @cputime: the cpu time spent in kernel space since the last update
2892 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
2895 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2896 runqueue_t
*rq
= this_rq();
2899 p
->stime
= cputime_add(p
->stime
, cputime
);
2901 /* Add system time to cpustat. */
2902 tmp
= cputime_to_cputime64(cputime
);
2903 if (hardirq_count() - hardirq_offset
)
2904 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
2905 else if (softirq_count())
2906 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
2907 else if (p
!= rq
->idle
)
2908 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
2909 else if (atomic_read(&rq
->nr_iowait
) > 0)
2910 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
2912 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
2913 /* Account for system time used */
2914 acct_update_integrals(p
);
2918 * Account for involuntary wait time.
2919 * @p: the process from which the cpu time has been stolen
2920 * @steal: the cpu time spent in involuntary wait
2922 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
2924 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2925 cputime64_t tmp
= cputime_to_cputime64(steal
);
2926 runqueue_t
*rq
= this_rq();
2928 if (p
== rq
->idle
) {
2929 p
->stime
= cputime_add(p
->stime
, steal
);
2930 if (atomic_read(&rq
->nr_iowait
) > 0)
2931 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
2933 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
2935 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
2939 * This function gets called by the timer code, with HZ frequency.
2940 * We call it with interrupts disabled.
2942 * It also gets called by the fork code, when changing the parent's
2945 void scheduler_tick(void)
2947 unsigned long long now
= sched_clock();
2948 int cpu
= smp_processor_id();
2949 runqueue_t
*rq
= this_rq();
2950 task_t
*p
= current
;
2952 update_cpu_clock(p
, rq
, now
);
2954 rq
->timestamp_last_tick
= now
;
2956 if (p
== rq
->idle
) {
2957 if (wake_priority_sleeper(rq
))
2959 rebalance_tick(cpu
, rq
, SCHED_IDLE
);
2963 /* Task might have expired already, but not scheduled off yet */
2964 if (p
->array
!= rq
->active
) {
2965 set_tsk_need_resched(p
);
2968 spin_lock(&rq
->lock
);
2970 * The task was running during this tick - update the
2971 * time slice counter. Note: we do not update a thread's
2972 * priority until it either goes to sleep or uses up its
2973 * timeslice. This makes it possible for interactive tasks
2974 * to use up their timeslices at their highest priority levels.
2978 * RR tasks need a special form of timeslice management.
2979 * FIFO tasks have no timeslices.
2981 if ((p
->policy
== SCHED_RR
) && !--p
->time_slice
) {
2982 p
->time_slice
= task_timeslice(p
);
2983 p
->first_time_slice
= 0;
2984 set_tsk_need_resched(p
);
2986 /* put it at the end of the queue: */
2987 requeue_task(p
, rq
->active
);
2991 if (!--p
->time_slice
) {
2992 dequeue_task(p
, rq
->active
);
2993 set_tsk_need_resched(p
);
2994 p
->prio
= effective_prio(p
);
2995 p
->time_slice
= task_timeslice(p
);
2996 p
->first_time_slice
= 0;
2998 if (!rq
->expired_timestamp
)
2999 rq
->expired_timestamp
= jiffies
;
3000 if (!TASK_INTERACTIVE(p
) || expired_starving(rq
)) {
3001 enqueue_task(p
, rq
->expired
);
3002 if (p
->static_prio
< rq
->best_expired_prio
)
3003 rq
->best_expired_prio
= p
->static_prio
;
3005 enqueue_task(p
, rq
->active
);
3008 * Prevent a too long timeslice allowing a task to monopolize
3009 * the CPU. We do this by splitting up the timeslice into
3012 * Note: this does not mean the task's timeslices expire or
3013 * get lost in any way, they just might be preempted by
3014 * another task of equal priority. (one with higher
3015 * priority would have preempted this task already.) We
3016 * requeue this task to the end of the list on this priority
3017 * level, which is in essence a round-robin of tasks with
3020 * This only applies to tasks in the interactive
3021 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3023 if (TASK_INTERACTIVE(p
) && !((task_timeslice(p
) -
3024 p
->time_slice
) % TIMESLICE_GRANULARITY(p
)) &&
3025 (p
->time_slice
>= TIMESLICE_GRANULARITY(p
)) &&
3026 (p
->array
== rq
->active
)) {
3028 requeue_task(p
, rq
->active
);
3029 set_tsk_need_resched(p
);
3033 spin_unlock(&rq
->lock
);
3035 rebalance_tick(cpu
, rq
, NOT_IDLE
);
3038 #ifdef CONFIG_SCHED_SMT
3039 static inline void wakeup_busy_runqueue(runqueue_t
*rq
)
3041 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3042 if (rq
->curr
== rq
->idle
&& rq
->nr_running
)
3043 resched_task(rq
->idle
);
3047 * Called with interrupt disabled and this_rq's runqueue locked.
3049 static void wake_sleeping_dependent(int this_cpu
)
3051 struct sched_domain
*tmp
, *sd
= NULL
;
3054 for_each_domain(this_cpu
, tmp
) {
3055 if (tmp
->flags
& SD_SHARE_CPUPOWER
) {
3064 for_each_cpu_mask(i
, sd
->span
) {
3065 runqueue_t
*smt_rq
= cpu_rq(i
);
3069 if (unlikely(!spin_trylock(&smt_rq
->lock
)))
3072 wakeup_busy_runqueue(smt_rq
);
3073 spin_unlock(&smt_rq
->lock
);
3078 * number of 'lost' timeslices this task wont be able to fully
3079 * utilize, if another task runs on a sibling. This models the
3080 * slowdown effect of other tasks running on siblings:
3082 static inline unsigned long smt_slice(task_t
*p
, struct sched_domain
*sd
)
3084 return p
->time_slice
* (100 - sd
->per_cpu_gain
) / 100;
3088 * To minimise lock contention and not have to drop this_rq's runlock we only
3089 * trylock the sibling runqueues and bypass those runqueues if we fail to
3090 * acquire their lock. As we only trylock the normal locking order does not
3091 * need to be obeyed.
3093 static int dependent_sleeper(int this_cpu
, runqueue_t
*this_rq
, task_t
*p
)
3095 struct sched_domain
*tmp
, *sd
= NULL
;
3098 /* kernel/rt threads do not participate in dependent sleeping */
3099 if (!p
->mm
|| rt_task(p
))
3102 for_each_domain(this_cpu
, tmp
) {
3103 if (tmp
->flags
& SD_SHARE_CPUPOWER
) {
3112 for_each_cpu_mask(i
, sd
->span
) {
3120 if (unlikely(!spin_trylock(&smt_rq
->lock
)))
3123 smt_curr
= smt_rq
->curr
;
3129 * If a user task with lower static priority than the
3130 * running task on the SMT sibling is trying to schedule,
3131 * delay it till there is proportionately less timeslice
3132 * left of the sibling task to prevent a lower priority
3133 * task from using an unfair proportion of the
3134 * physical cpu's resources. -ck
3136 if (rt_task(smt_curr
)) {
3138 * With real time tasks we run non-rt tasks only
3139 * per_cpu_gain% of the time.
3141 if ((jiffies
% DEF_TIMESLICE
) >
3142 (sd
->per_cpu_gain
* DEF_TIMESLICE
/ 100))
3145 if (smt_curr
->static_prio
< p
->static_prio
&&
3146 !TASK_PREEMPTS_CURR(p
, smt_rq
) &&
3147 smt_slice(smt_curr
, sd
) > task_timeslice(p
))
3151 spin_unlock(&smt_rq
->lock
);
3156 static inline void wake_sleeping_dependent(int this_cpu
)
3160 dependent_sleeper(int this_cpu
, runqueue_t
*this_rq
, task_t
*p
)
3166 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3168 void fastcall
add_preempt_count(int val
)
3173 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3175 preempt_count() += val
;
3177 * Spinlock count overflowing soon?
3179 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >= PREEMPT_MASK
-10);
3181 EXPORT_SYMBOL(add_preempt_count
);
3183 void fastcall
sub_preempt_count(int val
)
3188 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3191 * Is the spinlock portion underflowing?
3193 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3194 !(preempt_count() & PREEMPT_MASK
)))
3197 preempt_count() -= val
;
3199 EXPORT_SYMBOL(sub_preempt_count
);
3203 static inline int interactive_sleep(enum sleep_type sleep_type
)
3205 return (sleep_type
== SLEEP_INTERACTIVE
||
3206 sleep_type
== SLEEP_INTERRUPTED
);
3210 * schedule() is the main scheduler function.
3212 asmlinkage
void __sched
schedule(void)
3214 struct list_head
*queue
;
3215 unsigned long long now
;
3216 unsigned long run_time
;
3217 int cpu
, idx
, new_prio
;
3218 task_t
*prev
, *next
;
3219 prio_array_t
*array
;
3224 * Test if we are atomic. Since do_exit() needs to call into
3225 * schedule() atomically, we ignore that path for now.
3226 * Otherwise, whine if we are scheduling when we should not be.
3228 if (unlikely(in_atomic() && !current
->exit_state
)) {
3229 printk(KERN_ERR
"BUG: scheduling while atomic: "
3231 current
->comm
, preempt_count(), current
->pid
);
3234 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3239 release_kernel_lock(prev
);
3240 need_resched_nonpreemptible
:
3244 * The idle thread is not allowed to schedule!
3245 * Remove this check after it has been exercised a bit.
3247 if (unlikely(prev
== rq
->idle
) && prev
->state
!= TASK_RUNNING
) {
3248 printk(KERN_ERR
"bad: scheduling from the idle thread!\n");
3252 schedstat_inc(rq
, sched_cnt
);
3253 now
= sched_clock();
3254 if (likely((long long)(now
- prev
->timestamp
) < NS_MAX_SLEEP_AVG
)) {
3255 run_time
= now
- prev
->timestamp
;
3256 if (unlikely((long long)(now
- prev
->timestamp
) < 0))
3259 run_time
= NS_MAX_SLEEP_AVG
;
3262 * Tasks charged proportionately less run_time at high sleep_avg to
3263 * delay them losing their interactive status
3265 run_time
/= (CURRENT_BONUS(prev
) ? : 1);
3267 spin_lock_irq(&rq
->lock
);
3269 if (unlikely(prev
->flags
& PF_DEAD
))
3270 prev
->state
= EXIT_DEAD
;
3272 switch_count
= &prev
->nivcsw
;
3273 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3274 switch_count
= &prev
->nvcsw
;
3275 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3276 unlikely(signal_pending(prev
))))
3277 prev
->state
= TASK_RUNNING
;
3279 if (prev
->state
== TASK_UNINTERRUPTIBLE
)
3280 rq
->nr_uninterruptible
++;
3281 deactivate_task(prev
, rq
);
3285 cpu
= smp_processor_id();
3286 if (unlikely(!rq
->nr_running
)) {
3287 idle_balance(cpu
, rq
);
3288 if (!rq
->nr_running
) {
3290 rq
->expired_timestamp
= 0;
3291 wake_sleeping_dependent(cpu
);
3297 if (unlikely(!array
->nr_active
)) {
3299 * Switch the active and expired arrays.
3301 schedstat_inc(rq
, sched_switch
);
3302 rq
->active
= rq
->expired
;
3303 rq
->expired
= array
;
3305 rq
->expired_timestamp
= 0;
3306 rq
->best_expired_prio
= MAX_PRIO
;
3309 idx
= sched_find_first_bit(array
->bitmap
);
3310 queue
= array
->queue
+ idx
;
3311 next
= list_entry(queue
->next
, task_t
, run_list
);
3313 if (!rt_task(next
) && interactive_sleep(next
->sleep_type
)) {
3314 unsigned long long delta
= now
- next
->timestamp
;
3315 if (unlikely((long long)(now
- next
->timestamp
) < 0))
3318 if (next
->sleep_type
== SLEEP_INTERACTIVE
)
3319 delta
= delta
* (ON_RUNQUEUE_WEIGHT
* 128 / 100) / 128;
3321 array
= next
->array
;
3322 new_prio
= recalc_task_prio(next
, next
->timestamp
+ delta
);
3324 if (unlikely(next
->prio
!= new_prio
)) {
3325 dequeue_task(next
, array
);
3326 next
->prio
= new_prio
;
3327 enqueue_task(next
, array
);
3330 next
->sleep_type
= SLEEP_NORMAL
;
3331 if (dependent_sleeper(cpu
, rq
, next
))
3334 if (next
== rq
->idle
)
3335 schedstat_inc(rq
, sched_goidle
);
3337 prefetch_stack(next
);
3338 clear_tsk_need_resched(prev
);
3339 rcu_qsctr_inc(task_cpu(prev
));
3341 update_cpu_clock(prev
, rq
, now
);
3343 prev
->sleep_avg
-= run_time
;
3344 if ((long)prev
->sleep_avg
<= 0)
3345 prev
->sleep_avg
= 0;
3346 prev
->timestamp
= prev
->last_ran
= now
;
3348 sched_info_switch(prev
, next
);
3349 if (likely(prev
!= next
)) {
3350 next
->timestamp
= now
;
3355 prepare_task_switch(rq
, next
);
3356 prev
= context_switch(rq
, prev
, next
);
3359 * this_rq must be evaluated again because prev may have moved
3360 * CPUs since it called schedule(), thus the 'rq' on its stack
3361 * frame will be invalid.
3363 finish_task_switch(this_rq(), prev
);
3365 spin_unlock_irq(&rq
->lock
);
3368 if (unlikely(reacquire_kernel_lock(prev
) < 0))
3369 goto need_resched_nonpreemptible
;
3370 preempt_enable_no_resched();
3371 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3374 EXPORT_SYMBOL(schedule
);
3376 #ifdef CONFIG_PREEMPT
3378 * this is is the entry point to schedule() from in-kernel preemption
3379 * off of preempt_enable. Kernel preemptions off return from interrupt
3380 * occur there and call schedule directly.
3382 asmlinkage
void __sched
preempt_schedule(void)
3384 struct thread_info
*ti
= current_thread_info();
3385 #ifdef CONFIG_PREEMPT_BKL
3386 struct task_struct
*task
= current
;
3387 int saved_lock_depth
;
3390 * If there is a non-zero preempt_count or interrupts are disabled,
3391 * we do not want to preempt the current task. Just return..
3393 if (unlikely(ti
->preempt_count
|| irqs_disabled()))
3397 add_preempt_count(PREEMPT_ACTIVE
);
3399 * We keep the big kernel semaphore locked, but we
3400 * clear ->lock_depth so that schedule() doesnt
3401 * auto-release the semaphore:
3403 #ifdef CONFIG_PREEMPT_BKL
3404 saved_lock_depth
= task
->lock_depth
;
3405 task
->lock_depth
= -1;
3408 #ifdef CONFIG_PREEMPT_BKL
3409 task
->lock_depth
= saved_lock_depth
;
3411 sub_preempt_count(PREEMPT_ACTIVE
);
3413 /* we could miss a preemption opportunity between schedule and now */
3415 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3418 EXPORT_SYMBOL(preempt_schedule
);
3421 * this is is the entry point to schedule() from kernel preemption
3422 * off of irq context.
3423 * Note, that this is called and return with irqs disabled. This will
3424 * protect us against recursive calling from irq.
3426 asmlinkage
void __sched
preempt_schedule_irq(void)
3428 struct thread_info
*ti
= current_thread_info();
3429 #ifdef CONFIG_PREEMPT_BKL
3430 struct task_struct
*task
= current
;
3431 int saved_lock_depth
;
3433 /* Catch callers which need to be fixed*/
3434 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
3437 add_preempt_count(PREEMPT_ACTIVE
);
3439 * We keep the big kernel semaphore locked, but we
3440 * clear ->lock_depth so that schedule() doesnt
3441 * auto-release the semaphore:
3443 #ifdef CONFIG_PREEMPT_BKL
3444 saved_lock_depth
= task
->lock_depth
;
3445 task
->lock_depth
= -1;
3449 local_irq_disable();
3450 #ifdef CONFIG_PREEMPT_BKL
3451 task
->lock_depth
= saved_lock_depth
;
3453 sub_preempt_count(PREEMPT_ACTIVE
);
3455 /* we could miss a preemption opportunity between schedule and now */
3457 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3461 #endif /* CONFIG_PREEMPT */
3463 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
3466 return try_to_wake_up(curr
->private, mode
, sync
);
3468 EXPORT_SYMBOL(default_wake_function
);
3471 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3472 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3473 * number) then we wake all the non-exclusive tasks and one exclusive task.
3475 * There are circumstances in which we can try to wake a task which has already
3476 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3477 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3479 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
3480 int nr_exclusive
, int sync
, void *key
)
3482 struct list_head
*tmp
, *next
;
3484 list_for_each_safe(tmp
, next
, &q
->task_list
) {
3485 wait_queue_t
*curr
= list_entry(tmp
, wait_queue_t
, task_list
);
3486 unsigned flags
= curr
->flags
;
3488 if (curr
->func(curr
, mode
, sync
, key
) &&
3489 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
3495 * __wake_up - wake up threads blocked on a waitqueue.
3497 * @mode: which threads
3498 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3499 * @key: is directly passed to the wakeup function
3501 void fastcall
__wake_up(wait_queue_head_t
*q
, unsigned int mode
,
3502 int nr_exclusive
, void *key
)
3504 unsigned long flags
;
3506 spin_lock_irqsave(&q
->lock
, flags
);
3507 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
3508 spin_unlock_irqrestore(&q
->lock
, flags
);
3510 EXPORT_SYMBOL(__wake_up
);
3513 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3515 void fastcall
__wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
3517 __wake_up_common(q
, mode
, 1, 0, NULL
);
3521 * __wake_up_sync - wake up threads blocked on a waitqueue.
3523 * @mode: which threads
3524 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3526 * The sync wakeup differs that the waker knows that it will schedule
3527 * away soon, so while the target thread will be woken up, it will not
3528 * be migrated to another CPU - ie. the two threads are 'synchronized'
3529 * with each other. This can prevent needless bouncing between CPUs.
3531 * On UP it can prevent extra preemption.
3534 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
3536 unsigned long flags
;
3542 if (unlikely(!nr_exclusive
))
3545 spin_lock_irqsave(&q
->lock
, flags
);
3546 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
3547 spin_unlock_irqrestore(&q
->lock
, flags
);
3549 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
3551 void fastcall
complete(struct completion
*x
)
3553 unsigned long flags
;
3555 spin_lock_irqsave(&x
->wait
.lock
, flags
);
3557 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
3559 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
3561 EXPORT_SYMBOL(complete
);
3563 void fastcall
complete_all(struct completion
*x
)
3565 unsigned long flags
;
3567 spin_lock_irqsave(&x
->wait
.lock
, flags
);
3568 x
->done
+= UINT_MAX
/2;
3569 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
3571 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
3573 EXPORT_SYMBOL(complete_all
);
3575 void fastcall __sched
wait_for_completion(struct completion
*x
)
3579 spin_lock_irq(&x
->wait
.lock
);
3581 DECLARE_WAITQUEUE(wait
, current
);
3583 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3584 __add_wait_queue_tail(&x
->wait
, &wait
);
3586 __set_current_state(TASK_UNINTERRUPTIBLE
);
3587 spin_unlock_irq(&x
->wait
.lock
);
3589 spin_lock_irq(&x
->wait
.lock
);
3591 __remove_wait_queue(&x
->wait
, &wait
);
3594 spin_unlock_irq(&x
->wait
.lock
);
3596 EXPORT_SYMBOL(wait_for_completion
);
3598 unsigned long fastcall __sched
3599 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
3603 spin_lock_irq(&x
->wait
.lock
);
3605 DECLARE_WAITQUEUE(wait
, current
);
3607 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3608 __add_wait_queue_tail(&x
->wait
, &wait
);
3610 __set_current_state(TASK_UNINTERRUPTIBLE
);
3611 spin_unlock_irq(&x
->wait
.lock
);
3612 timeout
= schedule_timeout(timeout
);
3613 spin_lock_irq(&x
->wait
.lock
);
3615 __remove_wait_queue(&x
->wait
, &wait
);
3619 __remove_wait_queue(&x
->wait
, &wait
);
3623 spin_unlock_irq(&x
->wait
.lock
);
3626 EXPORT_SYMBOL(wait_for_completion_timeout
);
3628 int fastcall __sched
wait_for_completion_interruptible(struct completion
*x
)
3634 spin_lock_irq(&x
->wait
.lock
);
3636 DECLARE_WAITQUEUE(wait
, current
);
3638 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3639 __add_wait_queue_tail(&x
->wait
, &wait
);
3641 if (signal_pending(current
)) {
3643 __remove_wait_queue(&x
->wait
, &wait
);
3646 __set_current_state(TASK_INTERRUPTIBLE
);
3647 spin_unlock_irq(&x
->wait
.lock
);
3649 spin_lock_irq(&x
->wait
.lock
);
3651 __remove_wait_queue(&x
->wait
, &wait
);
3655 spin_unlock_irq(&x
->wait
.lock
);
3659 EXPORT_SYMBOL(wait_for_completion_interruptible
);
3661 unsigned long fastcall __sched
3662 wait_for_completion_interruptible_timeout(struct completion
*x
,
3663 unsigned long timeout
)
3667 spin_lock_irq(&x
->wait
.lock
);
3669 DECLARE_WAITQUEUE(wait
, current
);
3671 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
3672 __add_wait_queue_tail(&x
->wait
, &wait
);
3674 if (signal_pending(current
)) {
3675 timeout
= -ERESTARTSYS
;
3676 __remove_wait_queue(&x
->wait
, &wait
);
3679 __set_current_state(TASK_INTERRUPTIBLE
);
3680 spin_unlock_irq(&x
->wait
.lock
);
3681 timeout
= schedule_timeout(timeout
);
3682 spin_lock_irq(&x
->wait
.lock
);
3684 __remove_wait_queue(&x
->wait
, &wait
);
3688 __remove_wait_queue(&x
->wait
, &wait
);
3692 spin_unlock_irq(&x
->wait
.lock
);
3695 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
3698 #define SLEEP_ON_VAR \
3699 unsigned long flags; \
3700 wait_queue_t wait; \
3701 init_waitqueue_entry(&wait, current);
3703 #define SLEEP_ON_HEAD \
3704 spin_lock_irqsave(&q->lock,flags); \
3705 __add_wait_queue(q, &wait); \
3706 spin_unlock(&q->lock);
3708 #define SLEEP_ON_TAIL \
3709 spin_lock_irq(&q->lock); \
3710 __remove_wait_queue(q, &wait); \
3711 spin_unlock_irqrestore(&q->lock, flags);
3713 void fastcall __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
3717 current
->state
= TASK_INTERRUPTIBLE
;
3723 EXPORT_SYMBOL(interruptible_sleep_on
);
3725 long fastcall __sched
3726 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3730 current
->state
= TASK_INTERRUPTIBLE
;
3733 timeout
= schedule_timeout(timeout
);
3738 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
3740 void fastcall __sched
sleep_on(wait_queue_head_t
*q
)
3744 current
->state
= TASK_UNINTERRUPTIBLE
;
3750 EXPORT_SYMBOL(sleep_on
);
3752 long fastcall __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3756 current
->state
= TASK_UNINTERRUPTIBLE
;
3759 timeout
= schedule_timeout(timeout
);
3765 EXPORT_SYMBOL(sleep_on_timeout
);
3767 #ifdef CONFIG_RT_MUTEXES
3770 * rt_mutex_setprio - set the current priority of a task
3772 * @prio: prio value (kernel-internal form)
3774 * This function changes the 'effective' priority of a task. It does
3775 * not touch ->normal_prio like __setscheduler().
3777 * Used by the rt_mutex code to implement priority inheritance logic.
3779 void rt_mutex_setprio(task_t
*p
, int prio
)
3781 unsigned long flags
;
3782 prio_array_t
*array
;
3786 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
3788 rq
= task_rq_lock(p
, &flags
);
3793 dequeue_task(p
, array
);
3798 * If changing to an RT priority then queue it
3799 * in the active array!
3803 enqueue_task(p
, array
);
3805 * Reschedule if we are currently running on this runqueue and
3806 * our priority decreased, or if we are not currently running on
3807 * this runqueue and our priority is higher than the current's
3809 if (task_running(rq
, p
)) {
3810 if (p
->prio
> oldprio
)
3811 resched_task(rq
->curr
);
3812 } else if (TASK_PREEMPTS_CURR(p
, rq
))
3813 resched_task(rq
->curr
);
3815 task_rq_unlock(rq
, &flags
);
3820 void set_user_nice(task_t
*p
, long nice
)
3822 int old_prio
, delta
;
3823 unsigned long flags
;
3824 prio_array_t
*array
;
3827 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
3830 * We have to be careful, if called from sys_setpriority(),
3831 * the task might be in the middle of scheduling on another CPU.
3833 rq
= task_rq_lock(p
, &flags
);
3835 * The RT priorities are set via sched_setscheduler(), but we still
3836 * allow the 'normal' nice value to be set - but as expected
3837 * it wont have any effect on scheduling until the task is
3838 * not SCHED_NORMAL/SCHED_BATCH:
3840 if (has_rt_policy(p
)) {
3841 p
->static_prio
= NICE_TO_PRIO(nice
);
3846 dequeue_task(p
, array
);
3847 dec_raw_weighted_load(rq
, p
);
3850 p
->static_prio
= NICE_TO_PRIO(nice
);
3853 p
->prio
= effective_prio(p
);
3854 delta
= p
->prio
- old_prio
;
3857 enqueue_task(p
, array
);
3858 inc_raw_weighted_load(rq
, p
);
3860 * If the task increased its priority or is running and
3861 * lowered its priority, then reschedule its CPU:
3863 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
3864 resched_task(rq
->curr
);
3867 task_rq_unlock(rq
, &flags
);
3869 EXPORT_SYMBOL(set_user_nice
);
3872 * can_nice - check if a task can reduce its nice value
3876 int can_nice(const task_t
*p
, const int nice
)
3878 /* convert nice value [19,-20] to rlimit style value [1,40] */
3879 int nice_rlim
= 20 - nice
;
3881 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
3882 capable(CAP_SYS_NICE
));
3885 #ifdef __ARCH_WANT_SYS_NICE
3888 * sys_nice - change the priority of the current process.
3889 * @increment: priority increment
3891 * sys_setpriority is a more generic, but much slower function that
3892 * does similar things.
3894 asmlinkage
long sys_nice(int increment
)
3899 * Setpriority might change our priority at the same moment.
3900 * We don't have to worry. Conceptually one call occurs first
3901 * and we have a single winner.
3903 if (increment
< -40)
3908 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
3914 if (increment
< 0 && !can_nice(current
, nice
))
3917 retval
= security_task_setnice(current
, nice
);
3921 set_user_nice(current
, nice
);
3928 * task_prio - return the priority value of a given task.
3929 * @p: the task in question.
3931 * This is the priority value as seen by users in /proc.
3932 * RT tasks are offset by -200. Normal tasks are centered
3933 * around 0, value goes from -16 to +15.
3935 int task_prio(const task_t
*p
)
3937 return p
->prio
- MAX_RT_PRIO
;
3941 * task_nice - return the nice value of a given task.
3942 * @p: the task in question.
3944 int task_nice(const task_t
*p
)
3946 return TASK_NICE(p
);
3948 EXPORT_SYMBOL_GPL(task_nice
);
3951 * idle_cpu - is a given cpu idle currently?
3952 * @cpu: the processor in question.
3954 int idle_cpu(int cpu
)
3956 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
3960 * idle_task - return the idle task for a given cpu.
3961 * @cpu: the processor in question.
3963 task_t
*idle_task(int cpu
)
3965 return cpu_rq(cpu
)->idle
;
3969 * find_process_by_pid - find a process with a matching PID value.
3970 * @pid: the pid in question.
3972 static inline task_t
*find_process_by_pid(pid_t pid
)
3974 return pid
? find_task_by_pid(pid
) : current
;
3977 /* Actually do priority change: must hold rq lock. */
3978 static void __setscheduler(struct task_struct
*p
, int policy
, int prio
)
3983 p
->rt_priority
= prio
;
3984 p
->normal_prio
= normal_prio(p
);
3985 /* we are holding p->pi_lock already */
3986 p
->prio
= rt_mutex_getprio(p
);
3988 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3990 if (policy
== SCHED_BATCH
)
3996 * sched_setscheduler - change the scheduling policy and/or RT priority of
3998 * @p: the task in question.
3999 * @policy: new policy.
4000 * @param: structure containing the new RT priority.
4002 int sched_setscheduler(struct task_struct
*p
, int policy
,
4003 struct sched_param
*param
)
4005 int retval
, oldprio
, oldpolicy
= -1;
4006 prio_array_t
*array
;
4007 unsigned long flags
;
4010 /* may grab non-irq protected spin_locks */
4011 BUG_ON(in_interrupt());
4013 /* double check policy once rq lock held */
4015 policy
= oldpolicy
= p
->policy
;
4016 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4017 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
)
4020 * Valid priorities for SCHED_FIFO and SCHED_RR are
4021 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4024 if (param
->sched_priority
< 0 ||
4025 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4026 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4028 if ((policy
== SCHED_NORMAL
|| policy
== SCHED_BATCH
)
4029 != (param
->sched_priority
== 0))
4033 * Allow unprivileged RT tasks to decrease priority:
4035 if (!capable(CAP_SYS_NICE
)) {
4037 * can't change policy, except between SCHED_NORMAL
4040 if (((policy
!= SCHED_NORMAL
&& p
->policy
!= SCHED_BATCH
) &&
4041 (policy
!= SCHED_BATCH
&& p
->policy
!= SCHED_NORMAL
)) &&
4042 !p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
)
4044 /* can't increase priority */
4045 if ((policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
) &&
4046 param
->sched_priority
> p
->rt_priority
&&
4047 param
->sched_priority
>
4048 p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
)
4050 /* can't change other user's priorities */
4051 if ((current
->euid
!= p
->euid
) &&
4052 (current
->euid
!= p
->uid
))
4056 retval
= security_task_setscheduler(p
, policy
, param
);
4060 * make sure no PI-waiters arrive (or leave) while we are
4061 * changing the priority of the task:
4063 spin_lock_irqsave(&p
->pi_lock
, flags
);
4065 * To be able to change p->policy safely, the apropriate
4066 * runqueue lock must be held.
4068 rq
= __task_rq_lock(p
);
4069 /* recheck policy now with rq lock held */
4070 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4071 policy
= oldpolicy
= -1;
4072 __task_rq_unlock(rq
);
4073 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4078 deactivate_task(p
, rq
);
4080 __setscheduler(p
, policy
, param
->sched_priority
);
4082 __activate_task(p
, rq
);
4084 * Reschedule if we are currently running on this runqueue and
4085 * our priority decreased, or if we are not currently running on
4086 * this runqueue and our priority is higher than the current's
4088 if (task_running(rq
, p
)) {
4089 if (p
->prio
> oldprio
)
4090 resched_task(rq
->curr
);
4091 } else if (TASK_PREEMPTS_CURR(p
, rq
))
4092 resched_task(rq
->curr
);
4094 __task_rq_unlock(rq
);
4095 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4097 rt_mutex_adjust_pi(p
);
4101 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4104 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4107 struct sched_param lparam
;
4108 struct task_struct
*p
;
4110 if (!param
|| pid
< 0)
4112 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4114 read_lock_irq(&tasklist_lock
);
4115 p
= find_process_by_pid(pid
);
4117 read_unlock_irq(&tasklist_lock
);
4121 read_unlock_irq(&tasklist_lock
);
4122 retval
= sched_setscheduler(p
, policy
, &lparam
);
4128 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4129 * @pid: the pid in question.
4130 * @policy: new policy.
4131 * @param: structure containing the new RT priority.
4133 asmlinkage
long sys_sched_setscheduler(pid_t pid
, int policy
,
4134 struct sched_param __user
*param
)
4136 /* negative values for policy are not valid */
4140 return do_sched_setscheduler(pid
, policy
, param
);
4144 * sys_sched_setparam - set/change the RT priority of a thread
4145 * @pid: the pid in question.
4146 * @param: structure containing the new RT priority.
4148 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4150 return do_sched_setscheduler(pid
, -1, param
);
4154 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4155 * @pid: the pid in question.
4157 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4159 int retval
= -EINVAL
;
4166 read_lock(&tasklist_lock
);
4167 p
= find_process_by_pid(pid
);
4169 retval
= security_task_getscheduler(p
);
4173 read_unlock(&tasklist_lock
);
4180 * sys_sched_getscheduler - get the RT priority of a thread
4181 * @pid: the pid in question.
4182 * @param: structure containing the RT priority.
4184 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4186 struct sched_param lp
;
4187 int retval
= -EINVAL
;
4190 if (!param
|| pid
< 0)
4193 read_lock(&tasklist_lock
);
4194 p
= find_process_by_pid(pid
);
4199 retval
= security_task_getscheduler(p
);
4203 lp
.sched_priority
= p
->rt_priority
;
4204 read_unlock(&tasklist_lock
);
4207 * This one might sleep, we cannot do it with a spinlock held ...
4209 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4215 read_unlock(&tasklist_lock
);
4219 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4223 cpumask_t cpus_allowed
;
4226 read_lock(&tasklist_lock
);
4228 p
= find_process_by_pid(pid
);
4230 read_unlock(&tasklist_lock
);
4231 unlock_cpu_hotplug();
4236 * It is not safe to call set_cpus_allowed with the
4237 * tasklist_lock held. We will bump the task_struct's
4238 * usage count and then drop tasklist_lock.
4241 read_unlock(&tasklist_lock
);
4244 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4245 !capable(CAP_SYS_NICE
))
4248 retval
= security_task_setscheduler(p
, 0, NULL
);
4252 cpus_allowed
= cpuset_cpus_allowed(p
);
4253 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4254 retval
= set_cpus_allowed(p
, new_mask
);
4258 unlock_cpu_hotplug();
4262 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4263 cpumask_t
*new_mask
)
4265 if (len
< sizeof(cpumask_t
)) {
4266 memset(new_mask
, 0, sizeof(cpumask_t
));
4267 } else if (len
> sizeof(cpumask_t
)) {
4268 len
= sizeof(cpumask_t
);
4270 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4274 * sys_sched_setaffinity - set the cpu affinity of a process
4275 * @pid: pid of the process
4276 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4277 * @user_mask_ptr: user-space pointer to the new cpu mask
4279 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4280 unsigned long __user
*user_mask_ptr
)
4285 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4289 return sched_setaffinity(pid
, new_mask
);
4293 * Represents all cpu's present in the system
4294 * In systems capable of hotplug, this map could dynamically grow
4295 * as new cpu's are detected in the system via any platform specific
4296 * method, such as ACPI for e.g.
4299 cpumask_t cpu_present_map __read_mostly
;
4300 EXPORT_SYMBOL(cpu_present_map
);
4303 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4304 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4307 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4313 read_lock(&tasklist_lock
);
4316 p
= find_process_by_pid(pid
);
4320 retval
= security_task_getscheduler(p
);
4324 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4327 read_unlock(&tasklist_lock
);
4328 unlock_cpu_hotplug();
4336 * sys_sched_getaffinity - get the cpu affinity of a process
4337 * @pid: pid of the process
4338 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4339 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4341 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4342 unsigned long __user
*user_mask_ptr
)
4347 if (len
< sizeof(cpumask_t
))
4350 ret
= sched_getaffinity(pid
, &mask
);
4354 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4357 return sizeof(cpumask_t
);
4361 * sys_sched_yield - yield the current processor to other threads.
4363 * this function yields the current CPU by moving the calling thread
4364 * to the expired array. If there are no other threads running on this
4365 * CPU then this function will return.
4367 asmlinkage
long sys_sched_yield(void)
4369 runqueue_t
*rq
= this_rq_lock();
4370 prio_array_t
*array
= current
->array
;
4371 prio_array_t
*target
= rq
->expired
;
4373 schedstat_inc(rq
, yld_cnt
);
4375 * We implement yielding by moving the task into the expired
4378 * (special rule: RT tasks will just roundrobin in the active
4381 if (rt_task(current
))
4382 target
= rq
->active
;
4384 if (array
->nr_active
== 1) {
4385 schedstat_inc(rq
, yld_act_empty
);
4386 if (!rq
->expired
->nr_active
)
4387 schedstat_inc(rq
, yld_both_empty
);
4388 } else if (!rq
->expired
->nr_active
)
4389 schedstat_inc(rq
, yld_exp_empty
);
4391 if (array
!= target
) {
4392 dequeue_task(current
, array
);
4393 enqueue_task(current
, target
);
4396 * requeue_task is cheaper so perform that if possible.
4398 requeue_task(current
, array
);
4401 * Since we are going to call schedule() anyway, there's
4402 * no need to preempt or enable interrupts:
4404 __release(rq
->lock
);
4405 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4406 _raw_spin_unlock(&rq
->lock
);
4407 preempt_enable_no_resched();
4414 static inline int __resched_legal(void)
4416 if (unlikely(preempt_count()))
4418 if (unlikely(system_state
!= SYSTEM_RUNNING
))
4423 static void __cond_resched(void)
4425 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4426 __might_sleep(__FILE__
, __LINE__
);
4429 * The BKS might be reacquired before we have dropped
4430 * PREEMPT_ACTIVE, which could trigger a second
4431 * cond_resched() call.
4434 add_preempt_count(PREEMPT_ACTIVE
);
4436 sub_preempt_count(PREEMPT_ACTIVE
);
4437 } while (need_resched());
4440 int __sched
cond_resched(void)
4442 if (need_resched() && __resched_legal()) {
4448 EXPORT_SYMBOL(cond_resched
);
4451 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4452 * call schedule, and on return reacquire the lock.
4454 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4455 * operations here to prevent schedule() from being called twice (once via
4456 * spin_unlock(), once by hand).
4458 int cond_resched_lock(spinlock_t
*lock
)
4462 if (need_lockbreak(lock
)) {
4468 if (need_resched() && __resched_legal()) {
4469 spin_release(&lock
->dep_map
, 1, _THIS_IP_
);
4470 _raw_spin_unlock(lock
);
4471 preempt_enable_no_resched();
4478 EXPORT_SYMBOL(cond_resched_lock
);
4480 int __sched
cond_resched_softirq(void)
4482 BUG_ON(!in_softirq());
4484 if (need_resched() && __resched_legal()) {
4485 raw_local_irq_disable();
4487 raw_local_irq_enable();
4494 EXPORT_SYMBOL(cond_resched_softirq
);
4497 * yield - yield the current processor to other threads.
4499 * this is a shortcut for kernel-space yielding - it marks the
4500 * thread runnable and calls sys_sched_yield().
4502 void __sched
yield(void)
4504 set_current_state(TASK_RUNNING
);
4507 EXPORT_SYMBOL(yield
);
4510 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4511 * that process accounting knows that this is a task in IO wait state.
4513 * But don't do that if it is a deliberate, throttling IO wait (this task
4514 * has set its backing_dev_info: the queue against which it should throttle)
4516 void __sched
io_schedule(void)
4518 struct runqueue
*rq
= &__raw_get_cpu_var(runqueues
);
4520 atomic_inc(&rq
->nr_iowait
);
4522 atomic_dec(&rq
->nr_iowait
);
4524 EXPORT_SYMBOL(io_schedule
);
4526 long __sched
io_schedule_timeout(long timeout
)
4528 struct runqueue
*rq
= &__raw_get_cpu_var(runqueues
);
4531 atomic_inc(&rq
->nr_iowait
);
4532 ret
= schedule_timeout(timeout
);
4533 atomic_dec(&rq
->nr_iowait
);
4538 * sys_sched_get_priority_max - return maximum RT priority.
4539 * @policy: scheduling class.
4541 * this syscall returns the maximum rt_priority that can be used
4542 * by a given scheduling class.
4544 asmlinkage
long sys_sched_get_priority_max(int policy
)
4551 ret
= MAX_USER_RT_PRIO
-1;
4562 * sys_sched_get_priority_min - return minimum RT priority.
4563 * @policy: scheduling class.
4565 * this syscall returns the minimum rt_priority that can be used
4566 * by a given scheduling class.
4568 asmlinkage
long sys_sched_get_priority_min(int policy
)
4585 * sys_sched_rr_get_interval - return the default timeslice of a process.
4586 * @pid: pid of the process.
4587 * @interval: userspace pointer to the timeslice value.
4589 * this syscall writes the default timeslice value of a given process
4590 * into the user-space timespec buffer. A value of '0' means infinity.
4593 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
4595 int retval
= -EINVAL
;
4603 read_lock(&tasklist_lock
);
4604 p
= find_process_by_pid(pid
);
4608 retval
= security_task_getscheduler(p
);
4612 jiffies_to_timespec(p
->policy
== SCHED_FIFO
?
4613 0 : task_timeslice(p
), &t
);
4614 read_unlock(&tasklist_lock
);
4615 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
4619 read_unlock(&tasklist_lock
);
4623 static inline struct task_struct
*eldest_child(struct task_struct
*p
)
4625 if (list_empty(&p
->children
))
4627 return list_entry(p
->children
.next
,struct task_struct
,sibling
);
4630 static inline struct task_struct
*older_sibling(struct task_struct
*p
)
4632 if (p
->sibling
.prev
==&p
->parent
->children
)
4634 return list_entry(p
->sibling
.prev
,struct task_struct
,sibling
);
4637 static inline struct task_struct
*younger_sibling(struct task_struct
*p
)
4639 if (p
->sibling
.next
==&p
->parent
->children
)
4641 return list_entry(p
->sibling
.next
,struct task_struct
,sibling
);
4644 static void show_task(task_t
*p
)
4648 unsigned long free
= 0;
4649 static const char *stat_nam
[] = { "R", "S", "D", "T", "t", "Z", "X" };
4651 printk("%-13.13s ", p
->comm
);
4652 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
4653 if (state
< ARRAY_SIZE(stat_nam
))
4654 printk(stat_nam
[state
]);
4657 #if (BITS_PER_LONG == 32)
4658 if (state
== TASK_RUNNING
)
4659 printk(" running ");
4661 printk(" %08lX ", thread_saved_pc(p
));
4663 if (state
== TASK_RUNNING
)
4664 printk(" running task ");
4666 printk(" %016lx ", thread_saved_pc(p
));
4668 #ifdef CONFIG_DEBUG_STACK_USAGE
4670 unsigned long *n
= end_of_stack(p
);
4673 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
4676 printk("%5lu %5d %6d ", free
, p
->pid
, p
->parent
->pid
);
4677 if ((relative
= eldest_child(p
)))
4678 printk("%5d ", relative
->pid
);
4681 if ((relative
= younger_sibling(p
)))
4682 printk("%7d", relative
->pid
);
4685 if ((relative
= older_sibling(p
)))
4686 printk(" %5d", relative
->pid
);
4690 printk(" (L-TLB)\n");
4692 printk(" (NOTLB)\n");
4694 if (state
!= TASK_RUNNING
)
4695 show_stack(p
, NULL
);
4698 void show_state(void)
4702 #if (BITS_PER_LONG == 32)
4705 printk(" task PC pid father child younger older\n");
4709 printk(" task PC pid father child younger older\n");
4711 read_lock(&tasklist_lock
);
4712 do_each_thread(g
, p
) {
4714 * reset the NMI-timeout, listing all files on a slow
4715 * console might take alot of time:
4717 touch_nmi_watchdog();
4719 } while_each_thread(g
, p
);
4721 read_unlock(&tasklist_lock
);
4722 debug_show_all_locks();
4726 * init_idle - set up an idle thread for a given CPU
4727 * @idle: task in question
4728 * @cpu: cpu the idle task belongs to
4730 * NOTE: this function does not set the idle thread's NEED_RESCHED
4731 * flag, to make booting more robust.
4733 void __devinit
init_idle(task_t
*idle
, int cpu
)
4735 runqueue_t
*rq
= cpu_rq(cpu
);
4736 unsigned long flags
;
4738 idle
->timestamp
= sched_clock();
4739 idle
->sleep_avg
= 0;
4741 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
4742 idle
->state
= TASK_RUNNING
;
4743 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
4744 set_task_cpu(idle
, cpu
);
4746 spin_lock_irqsave(&rq
->lock
, flags
);
4747 rq
->curr
= rq
->idle
= idle
;
4748 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4751 spin_unlock_irqrestore(&rq
->lock
, flags
);
4753 /* Set the preempt count _outside_ the spinlocks! */
4754 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4755 task_thread_info(idle
)->preempt_count
= (idle
->lock_depth
>= 0);
4757 task_thread_info(idle
)->preempt_count
= 0;
4762 * In a system that switches off the HZ timer nohz_cpu_mask
4763 * indicates which cpus entered this state. This is used
4764 * in the rcu update to wait only for active cpus. For system
4765 * which do not switch off the HZ timer nohz_cpu_mask should
4766 * always be CPU_MASK_NONE.
4768 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
4772 * This is how migration works:
4774 * 1) we queue a migration_req_t structure in the source CPU's
4775 * runqueue and wake up that CPU's migration thread.
4776 * 2) we down() the locked semaphore => thread blocks.
4777 * 3) migration thread wakes up (implicitly it forces the migrated
4778 * thread off the CPU)
4779 * 4) it gets the migration request and checks whether the migrated
4780 * task is still in the wrong runqueue.
4781 * 5) if it's in the wrong runqueue then the migration thread removes
4782 * it and puts it into the right queue.
4783 * 6) migration thread up()s the semaphore.
4784 * 7) we wake up and the migration is done.
4788 * Change a given task's CPU affinity. Migrate the thread to a
4789 * proper CPU and schedule it away if the CPU it's executing on
4790 * is removed from the allowed bitmask.
4792 * NOTE: the caller must have a valid reference to the task, the
4793 * task must not exit() & deallocate itself prematurely. The
4794 * call is not atomic; no spinlocks may be held.
4796 int set_cpus_allowed(task_t
*p
, cpumask_t new_mask
)
4798 unsigned long flags
;
4799 migration_req_t req
;
4803 rq
= task_rq_lock(p
, &flags
);
4804 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
4809 p
->cpus_allowed
= new_mask
;
4810 /* Can the task run on the task's current CPU? If so, we're done */
4811 if (cpu_isset(task_cpu(p
), new_mask
))
4814 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
4815 /* Need help from migration thread: drop lock and wait. */
4816 task_rq_unlock(rq
, &flags
);
4817 wake_up_process(rq
->migration_thread
);
4818 wait_for_completion(&req
.done
);
4819 tlb_migrate_finish(p
->mm
);
4823 task_rq_unlock(rq
, &flags
);
4827 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
4830 * Move (not current) task off this cpu, onto dest cpu. We're doing
4831 * this because either it can't run here any more (set_cpus_allowed()
4832 * away from this CPU, or CPU going down), or because we're
4833 * attempting to rebalance this task on exec (sched_exec).
4835 * So we race with normal scheduler movements, but that's OK, as long
4836 * as the task is no longer on this CPU.
4838 * Returns non-zero if task was successfully migrated.
4840 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
4842 runqueue_t
*rq_dest
, *rq_src
;
4845 if (unlikely(cpu_is_offline(dest_cpu
)))
4848 rq_src
= cpu_rq(src_cpu
);
4849 rq_dest
= cpu_rq(dest_cpu
);
4851 double_rq_lock(rq_src
, rq_dest
);
4852 /* Already moved. */
4853 if (task_cpu(p
) != src_cpu
)
4855 /* Affinity changed (again). */
4856 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
4859 set_task_cpu(p
, dest_cpu
);
4862 * Sync timestamp with rq_dest's before activating.
4863 * The same thing could be achieved by doing this step
4864 * afterwards, and pretending it was a local activate.
4865 * This way is cleaner and logically correct.
4867 p
->timestamp
= p
->timestamp
- rq_src
->timestamp_last_tick
4868 + rq_dest
->timestamp_last_tick
;
4869 deactivate_task(p
, rq_src
);
4870 activate_task(p
, rq_dest
, 0);
4871 if (TASK_PREEMPTS_CURR(p
, rq_dest
))
4872 resched_task(rq_dest
->curr
);
4876 double_rq_unlock(rq_src
, rq_dest
);
4881 * migration_thread - this is a highprio system thread that performs
4882 * thread migration by bumping thread off CPU then 'pushing' onto
4885 static int migration_thread(void *data
)
4887 int cpu
= (long)data
;
4891 BUG_ON(rq
->migration_thread
!= current
);
4893 set_current_state(TASK_INTERRUPTIBLE
);
4894 while (!kthread_should_stop()) {
4895 struct list_head
*head
;
4896 migration_req_t
*req
;
4900 spin_lock_irq(&rq
->lock
);
4902 if (cpu_is_offline(cpu
)) {
4903 spin_unlock_irq(&rq
->lock
);
4907 if (rq
->active_balance
) {
4908 active_load_balance(rq
, cpu
);
4909 rq
->active_balance
= 0;
4912 head
= &rq
->migration_queue
;
4914 if (list_empty(head
)) {
4915 spin_unlock_irq(&rq
->lock
);
4917 set_current_state(TASK_INTERRUPTIBLE
);
4920 req
= list_entry(head
->next
, migration_req_t
, list
);
4921 list_del_init(head
->next
);
4923 spin_unlock(&rq
->lock
);
4924 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
4927 complete(&req
->done
);
4929 __set_current_state(TASK_RUNNING
);
4933 /* Wait for kthread_stop */
4934 set_current_state(TASK_INTERRUPTIBLE
);
4935 while (!kthread_should_stop()) {
4937 set_current_state(TASK_INTERRUPTIBLE
);
4939 __set_current_state(TASK_RUNNING
);
4943 #ifdef CONFIG_HOTPLUG_CPU
4944 /* Figure out where task on dead CPU should go, use force if neccessary. */
4945 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
4948 unsigned long flags
;
4954 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
4955 cpus_and(mask
, mask
, p
->cpus_allowed
);
4956 dest_cpu
= any_online_cpu(mask
);
4958 /* On any allowed CPU? */
4959 if (dest_cpu
== NR_CPUS
)
4960 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
4962 /* No more Mr. Nice Guy. */
4963 if (dest_cpu
== NR_CPUS
) {
4964 rq
= task_rq_lock(p
, &flags
);
4965 cpus_setall(p
->cpus_allowed
);
4966 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
4967 task_rq_unlock(rq
, &flags
);
4970 * Don't tell them about moving exiting tasks or
4971 * kernel threads (both mm NULL), since they never
4974 if (p
->mm
&& printk_ratelimit())
4975 printk(KERN_INFO
"process %d (%s) no "
4976 "longer affine to cpu%d\n",
4977 p
->pid
, p
->comm
, dead_cpu
);
4979 if (!__migrate_task(p
, dead_cpu
, dest_cpu
))
4984 * While a dead CPU has no uninterruptible tasks queued at this point,
4985 * it might still have a nonzero ->nr_uninterruptible counter, because
4986 * for performance reasons the counter is not stricly tracking tasks to
4987 * their home CPUs. So we just add the counter to another CPU's counter,
4988 * to keep the global sum constant after CPU-down:
4990 static void migrate_nr_uninterruptible(runqueue_t
*rq_src
)
4992 runqueue_t
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
4993 unsigned long flags
;
4995 local_irq_save(flags
);
4996 double_rq_lock(rq_src
, rq_dest
);
4997 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
4998 rq_src
->nr_uninterruptible
= 0;
4999 double_rq_unlock(rq_src
, rq_dest
);
5000 local_irq_restore(flags
);
5003 /* Run through task list and migrate tasks from the dead cpu. */
5004 static void migrate_live_tasks(int src_cpu
)
5006 struct task_struct
*p
, *t
;
5008 write_lock_irq(&tasklist_lock
);
5010 do_each_thread(t
, p
) {
5014 if (task_cpu(p
) == src_cpu
)
5015 move_task_off_dead_cpu(src_cpu
, p
);
5016 } while_each_thread(t
, p
);
5018 write_unlock_irq(&tasklist_lock
);
5021 /* Schedules idle task to be the next runnable task on current CPU.
5022 * It does so by boosting its priority to highest possible and adding it to
5023 * the _front_ of the runqueue. Used by CPU offline code.
5025 void sched_idle_next(void)
5027 int this_cpu
= smp_processor_id();
5028 runqueue_t
*rq
= cpu_rq(this_cpu
);
5029 struct task_struct
*p
= rq
->idle
;
5030 unsigned long flags
;
5032 /* cpu has to be offline */
5033 BUG_ON(cpu_online(this_cpu
));
5036 * Strictly not necessary since rest of the CPUs are stopped by now
5037 * and interrupts disabled on the current cpu.
5039 spin_lock_irqsave(&rq
->lock
, flags
);
5041 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5043 /* Add idle task to the _front_ of its priority queue: */
5044 __activate_idle_task(p
, rq
);
5046 spin_unlock_irqrestore(&rq
->lock
, flags
);
5050 * Ensures that the idle task is using init_mm right before its cpu goes
5053 void idle_task_exit(void)
5055 struct mm_struct
*mm
= current
->active_mm
;
5057 BUG_ON(cpu_online(smp_processor_id()));
5060 switch_mm(mm
, &init_mm
, current
);
5064 static void migrate_dead(unsigned int dead_cpu
, task_t
*p
)
5066 struct runqueue
*rq
= cpu_rq(dead_cpu
);
5068 /* Must be exiting, otherwise would be on tasklist. */
5069 BUG_ON(p
->exit_state
!= EXIT_ZOMBIE
&& p
->exit_state
!= EXIT_DEAD
);
5071 /* Cannot have done final schedule yet: would have vanished. */
5072 BUG_ON(p
->flags
& PF_DEAD
);
5077 * Drop lock around migration; if someone else moves it,
5078 * that's OK. No task can be added to this CPU, so iteration is
5081 spin_unlock_irq(&rq
->lock
);
5082 move_task_off_dead_cpu(dead_cpu
, p
);
5083 spin_lock_irq(&rq
->lock
);
5088 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5089 static void migrate_dead_tasks(unsigned int dead_cpu
)
5091 struct runqueue
*rq
= cpu_rq(dead_cpu
);
5092 unsigned int arr
, i
;
5094 for (arr
= 0; arr
< 2; arr
++) {
5095 for (i
= 0; i
< MAX_PRIO
; i
++) {
5096 struct list_head
*list
= &rq
->arrays
[arr
].queue
[i
];
5098 while (!list_empty(list
))
5099 migrate_dead(dead_cpu
,
5100 list_entry(list
->next
, task_t
,
5105 #endif /* CONFIG_HOTPLUG_CPU */
5108 * migration_call - callback that gets triggered when a CPU is added.
5109 * Here we can start up the necessary migration thread for the new CPU.
5111 static int __cpuinit
5112 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5114 struct task_struct
*p
;
5115 int cpu
= (long)hcpu
;
5116 struct runqueue
*rq
;
5117 unsigned long flags
;
5120 case CPU_UP_PREPARE
:
5121 p
= kthread_create(migration_thread
, hcpu
, "migration/%d",cpu
);
5124 p
->flags
|= PF_NOFREEZE
;
5125 kthread_bind(p
, cpu
);
5126 /* Must be high prio: stop_machine expects to yield to it. */
5127 rq
= task_rq_lock(p
, &flags
);
5128 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5129 task_rq_unlock(rq
, &flags
);
5130 cpu_rq(cpu
)->migration_thread
= p
;
5134 /* Strictly unneccessary, as first user will wake it. */
5135 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5138 #ifdef CONFIG_HOTPLUG_CPU
5139 case CPU_UP_CANCELED
:
5140 if (!cpu_rq(cpu
)->migration_thread
)
5142 /* Unbind it from offline cpu so it can run. Fall thru. */
5143 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5144 any_online_cpu(cpu_online_map
));
5145 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5146 cpu_rq(cpu
)->migration_thread
= NULL
;
5150 migrate_live_tasks(cpu
);
5152 kthread_stop(rq
->migration_thread
);
5153 rq
->migration_thread
= NULL
;
5154 /* Idle task back to normal (off runqueue, low prio) */
5155 rq
= task_rq_lock(rq
->idle
, &flags
);
5156 deactivate_task(rq
->idle
, rq
);
5157 rq
->idle
->static_prio
= MAX_PRIO
;
5158 __setscheduler(rq
->idle
, SCHED_NORMAL
, 0);
5159 migrate_dead_tasks(cpu
);
5160 task_rq_unlock(rq
, &flags
);
5161 migrate_nr_uninterruptible(rq
);
5162 BUG_ON(rq
->nr_running
!= 0);
5164 /* No need to migrate the tasks: it was best-effort if
5165 * they didn't do lock_cpu_hotplug(). Just wake up
5166 * the requestors. */
5167 spin_lock_irq(&rq
->lock
);
5168 while (!list_empty(&rq
->migration_queue
)) {
5169 migration_req_t
*req
;
5170 req
= list_entry(rq
->migration_queue
.next
,
5171 migration_req_t
, list
);
5172 list_del_init(&req
->list
);
5173 complete(&req
->done
);
5175 spin_unlock_irq(&rq
->lock
);
5182 /* Register at highest priority so that task migration (migrate_all_tasks)
5183 * happens before everything else.
5185 static struct notifier_block __cpuinitdata migration_notifier
= {
5186 .notifier_call
= migration_call
,
5190 int __init
migration_init(void)
5192 void *cpu
= (void *)(long)smp_processor_id();
5194 /* Start one for the boot CPU: */
5195 migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5196 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5197 register_cpu_notifier(&migration_notifier
);
5204 #undef SCHED_DOMAIN_DEBUG
5205 #ifdef SCHED_DOMAIN_DEBUG
5206 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
5211 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
5215 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
5220 struct sched_group
*group
= sd
->groups
;
5221 cpumask_t groupmask
;
5223 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
5224 cpus_clear(groupmask
);
5227 for (i
= 0; i
< level
+ 1; i
++)
5229 printk("domain %d: ", level
);
5231 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5232 printk("does not load-balance\n");
5234 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain has parent");
5238 printk("span %s\n", str
);
5240 if (!cpu_isset(cpu
, sd
->span
))
5241 printk(KERN_ERR
"ERROR: domain->span does not contain CPU%d\n", cpu
);
5242 if (!cpu_isset(cpu
, group
->cpumask
))
5243 printk(KERN_ERR
"ERROR: domain->groups does not contain CPU%d\n", cpu
);
5246 for (i
= 0; i
< level
+ 2; i
++)
5252 printk(KERN_ERR
"ERROR: group is NULL\n");
5256 if (!group
->cpu_power
) {
5258 printk(KERN_ERR
"ERROR: domain->cpu_power not set\n");
5261 if (!cpus_weight(group
->cpumask
)) {
5263 printk(KERN_ERR
"ERROR: empty group\n");
5266 if (cpus_intersects(groupmask
, group
->cpumask
)) {
5268 printk(KERN_ERR
"ERROR: repeated CPUs\n");
5271 cpus_or(groupmask
, groupmask
, group
->cpumask
);
5273 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
5276 group
= group
->next
;
5277 } while (group
!= sd
->groups
);
5280 if (!cpus_equal(sd
->span
, groupmask
))
5281 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
5287 if (!cpus_subset(groupmask
, sd
->span
))
5288 printk(KERN_ERR
"ERROR: parent span is not a superset of domain->span\n");
5294 # define sched_domain_debug(sd, cpu) do { } while (0)
5297 static int sd_degenerate(struct sched_domain
*sd
)
5299 if (cpus_weight(sd
->span
) == 1)
5302 /* Following flags need at least 2 groups */
5303 if (sd
->flags
& (SD_LOAD_BALANCE
|
5304 SD_BALANCE_NEWIDLE
|
5307 if (sd
->groups
!= sd
->groups
->next
)
5311 /* Following flags don't use groups */
5312 if (sd
->flags
& (SD_WAKE_IDLE
|
5321 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
5323 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
5325 if (sd_degenerate(parent
))
5328 if (!cpus_equal(sd
->span
, parent
->span
))
5331 /* Does parent contain flags not in child? */
5332 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5333 if (cflags
& SD_WAKE_AFFINE
)
5334 pflags
&= ~SD_WAKE_BALANCE
;
5335 /* Flags needing groups don't count if only 1 group in parent */
5336 if (parent
->groups
== parent
->groups
->next
) {
5337 pflags
&= ~(SD_LOAD_BALANCE
|
5338 SD_BALANCE_NEWIDLE
|
5342 if (~cflags
& pflags
)
5349 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5350 * hold the hotplug lock.
5352 static void cpu_attach_domain(struct sched_domain
*sd
, int cpu
)
5354 runqueue_t
*rq
= cpu_rq(cpu
);
5355 struct sched_domain
*tmp
;
5357 /* Remove the sched domains which do not contribute to scheduling. */
5358 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
5359 struct sched_domain
*parent
= tmp
->parent
;
5362 if (sd_parent_degenerate(tmp
, parent
))
5363 tmp
->parent
= parent
->parent
;
5366 if (sd
&& sd_degenerate(sd
))
5369 sched_domain_debug(sd
, cpu
);
5371 rcu_assign_pointer(rq
->sd
, sd
);
5374 /* cpus with isolated domains */
5375 static cpumask_t __devinitdata cpu_isolated_map
= CPU_MASK_NONE
;
5377 /* Setup the mask of cpus configured for isolated domains */
5378 static int __init
isolated_cpu_setup(char *str
)
5380 int ints
[NR_CPUS
], i
;
5382 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
5383 cpus_clear(cpu_isolated_map
);
5384 for (i
= 1; i
<= ints
[0]; i
++)
5385 if (ints
[i
] < NR_CPUS
)
5386 cpu_set(ints
[i
], cpu_isolated_map
);
5390 __setup ("isolcpus=", isolated_cpu_setup
);
5393 * init_sched_build_groups takes an array of groups, the cpumask we wish
5394 * to span, and a pointer to a function which identifies what group a CPU
5395 * belongs to. The return value of group_fn must be a valid index into the
5396 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5397 * keep track of groups covered with a cpumask_t).
5399 * init_sched_build_groups will build a circular linked list of the groups
5400 * covered by the given span, and will set each group's ->cpumask correctly,
5401 * and ->cpu_power to 0.
5403 static void init_sched_build_groups(struct sched_group groups
[], cpumask_t span
,
5404 int (*group_fn
)(int cpu
))
5406 struct sched_group
*first
= NULL
, *last
= NULL
;
5407 cpumask_t covered
= CPU_MASK_NONE
;
5410 for_each_cpu_mask(i
, span
) {
5411 int group
= group_fn(i
);
5412 struct sched_group
*sg
= &groups
[group
];
5415 if (cpu_isset(i
, covered
))
5418 sg
->cpumask
= CPU_MASK_NONE
;
5421 for_each_cpu_mask(j
, span
) {
5422 if (group_fn(j
) != group
)
5425 cpu_set(j
, covered
);
5426 cpu_set(j
, sg
->cpumask
);
5437 #define SD_NODES_PER_DOMAIN 16
5440 * Self-tuning task migration cost measurement between source and target CPUs.
5442 * This is done by measuring the cost of manipulating buffers of varying
5443 * sizes. For a given buffer-size here are the steps that are taken:
5445 * 1) the source CPU reads+dirties a shared buffer
5446 * 2) the target CPU reads+dirties the same shared buffer
5448 * We measure how long they take, in the following 4 scenarios:
5450 * - source: CPU1, target: CPU2 | cost1
5451 * - source: CPU2, target: CPU1 | cost2
5452 * - source: CPU1, target: CPU1 | cost3
5453 * - source: CPU2, target: CPU2 | cost4
5455 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5456 * the cost of migration.
5458 * We then start off from a small buffer-size and iterate up to larger
5459 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5460 * doing a maximum search for the cost. (The maximum cost for a migration
5461 * normally occurs when the working set size is around the effective cache
5464 #define SEARCH_SCOPE 2
5465 #define MIN_CACHE_SIZE (64*1024U)
5466 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5467 #define ITERATIONS 1
5468 #define SIZE_THRESH 130
5469 #define COST_THRESH 130
5472 * The migration cost is a function of 'domain distance'. Domain
5473 * distance is the number of steps a CPU has to iterate down its
5474 * domain tree to share a domain with the other CPU. The farther
5475 * two CPUs are from each other, the larger the distance gets.
5477 * Note that we use the distance only to cache measurement results,
5478 * the distance value is not used numerically otherwise. When two
5479 * CPUs have the same distance it is assumed that the migration
5480 * cost is the same. (this is a simplification but quite practical)
5482 #define MAX_DOMAIN_DISTANCE 32
5484 static unsigned long long migration_cost
[MAX_DOMAIN_DISTANCE
] =
5485 { [ 0 ... MAX_DOMAIN_DISTANCE
-1 ] =
5487 * Architectures may override the migration cost and thus avoid
5488 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5489 * virtualized hardware:
5491 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5492 CONFIG_DEFAULT_MIGRATION_COST
5499 * Allow override of migration cost - in units of microseconds.
5500 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5501 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5503 static int __init
migration_cost_setup(char *str
)
5505 int ints
[MAX_DOMAIN_DISTANCE
+1], i
;
5507 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
5509 printk("#ints: %d\n", ints
[0]);
5510 for (i
= 1; i
<= ints
[0]; i
++) {
5511 migration_cost
[i
-1] = (unsigned long long)ints
[i
]*1000;
5512 printk("migration_cost[%d]: %Ld\n", i
-1, migration_cost
[i
-1]);
5517 __setup ("migration_cost=", migration_cost_setup
);
5520 * Global multiplier (divisor) for migration-cutoff values,
5521 * in percentiles. E.g. use a value of 150 to get 1.5 times
5522 * longer cache-hot cutoff times.
5524 * (We scale it from 100 to 128 to long long handling easier.)
5527 #define MIGRATION_FACTOR_SCALE 128
5529 static unsigned int migration_factor
= MIGRATION_FACTOR_SCALE
;
5531 static int __init
setup_migration_factor(char *str
)
5533 get_option(&str
, &migration_factor
);
5534 migration_factor
= migration_factor
* MIGRATION_FACTOR_SCALE
/ 100;
5538 __setup("migration_factor=", setup_migration_factor
);
5541 * Estimated distance of two CPUs, measured via the number of domains
5542 * we have to pass for the two CPUs to be in the same span:
5544 static unsigned long domain_distance(int cpu1
, int cpu2
)
5546 unsigned long distance
= 0;
5547 struct sched_domain
*sd
;
5549 for_each_domain(cpu1
, sd
) {
5550 WARN_ON(!cpu_isset(cpu1
, sd
->span
));
5551 if (cpu_isset(cpu2
, sd
->span
))
5555 if (distance
>= MAX_DOMAIN_DISTANCE
) {
5557 distance
= MAX_DOMAIN_DISTANCE
-1;
5563 static unsigned int migration_debug
;
5565 static int __init
setup_migration_debug(char *str
)
5567 get_option(&str
, &migration_debug
);
5571 __setup("migration_debug=", setup_migration_debug
);
5574 * Maximum cache-size that the scheduler should try to measure.
5575 * Architectures with larger caches should tune this up during
5576 * bootup. Gets used in the domain-setup code (i.e. during SMP
5579 unsigned int max_cache_size
;
5581 static int __init
setup_max_cache_size(char *str
)
5583 get_option(&str
, &max_cache_size
);
5587 __setup("max_cache_size=", setup_max_cache_size
);
5590 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5591 * is the operation that is timed, so we try to generate unpredictable
5592 * cachemisses that still end up filling the L2 cache:
5594 static void touch_cache(void *__cache
, unsigned long __size
)
5596 unsigned long size
= __size
/sizeof(long), chunk1
= size
/3,
5598 unsigned long *cache
= __cache
;
5601 for (i
= 0; i
< size
/6; i
+= 8) {
5604 case 1: cache
[size
-1-i
]++;
5605 case 2: cache
[chunk1
-i
]++;
5606 case 3: cache
[chunk1
+i
]++;
5607 case 4: cache
[chunk2
-i
]++;
5608 case 5: cache
[chunk2
+i
]++;
5614 * Measure the cache-cost of one task migration. Returns in units of nsec.
5616 static unsigned long long
5617 measure_one(void *cache
, unsigned long size
, int source
, int target
)
5619 cpumask_t mask
, saved_mask
;
5620 unsigned long long t0
, t1
, t2
, t3
, cost
;
5622 saved_mask
= current
->cpus_allowed
;
5625 * Flush source caches to RAM and invalidate them:
5630 * Migrate to the source CPU:
5632 mask
= cpumask_of_cpu(source
);
5633 set_cpus_allowed(current
, mask
);
5634 WARN_ON(smp_processor_id() != source
);
5637 * Dirty the working set:
5640 touch_cache(cache
, size
);
5644 * Migrate to the target CPU, dirty the L2 cache and access
5645 * the shared buffer. (which represents the working set
5646 * of a migrated task.)
5648 mask
= cpumask_of_cpu(target
);
5649 set_cpus_allowed(current
, mask
);
5650 WARN_ON(smp_processor_id() != target
);
5653 touch_cache(cache
, size
);
5656 cost
= t1
-t0
+ t3
-t2
;
5658 if (migration_debug
>= 2)
5659 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5660 source
, target
, t1
-t0
, t1
-t0
, t3
-t2
, cost
);
5662 * Flush target caches to RAM and invalidate them:
5666 set_cpus_allowed(current
, saved_mask
);
5672 * Measure a series of task migrations and return the average
5673 * result. Since this code runs early during bootup the system
5674 * is 'undisturbed' and the average latency makes sense.
5676 * The algorithm in essence auto-detects the relevant cache-size,
5677 * so it will properly detect different cachesizes for different
5678 * cache-hierarchies, depending on how the CPUs are connected.
5680 * Architectures can prime the upper limit of the search range via
5681 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5683 static unsigned long long
5684 measure_cost(int cpu1
, int cpu2
, void *cache
, unsigned int size
)
5686 unsigned long long cost1
, cost2
;
5690 * Measure the migration cost of 'size' bytes, over an
5691 * average of 10 runs:
5693 * (We perturb the cache size by a small (0..4k)
5694 * value to compensate size/alignment related artifacts.
5695 * We also subtract the cost of the operation done on
5701 * dry run, to make sure we start off cache-cold on cpu1,
5702 * and to get any vmalloc pagefaults in advance:
5704 measure_one(cache
, size
, cpu1
, cpu2
);
5705 for (i
= 0; i
< ITERATIONS
; i
++)
5706 cost1
+= measure_one(cache
, size
- i
*1024, cpu1
, cpu2
);
5708 measure_one(cache
, size
, cpu2
, cpu1
);
5709 for (i
= 0; i
< ITERATIONS
; i
++)
5710 cost1
+= measure_one(cache
, size
- i
*1024, cpu2
, cpu1
);
5713 * (We measure the non-migrating [cached] cost on both
5714 * cpu1 and cpu2, to handle CPUs with different speeds)
5718 measure_one(cache
, size
, cpu1
, cpu1
);
5719 for (i
= 0; i
< ITERATIONS
; i
++)
5720 cost2
+= measure_one(cache
, size
- i
*1024, cpu1
, cpu1
);
5722 measure_one(cache
, size
, cpu2
, cpu2
);
5723 for (i
= 0; i
< ITERATIONS
; i
++)
5724 cost2
+= measure_one(cache
, size
- i
*1024, cpu2
, cpu2
);
5727 * Get the per-iteration migration cost:
5729 do_div(cost1
, 2*ITERATIONS
);
5730 do_div(cost2
, 2*ITERATIONS
);
5732 return cost1
- cost2
;
5735 static unsigned long long measure_migration_cost(int cpu1
, int cpu2
)
5737 unsigned long long max_cost
= 0, fluct
= 0, avg_fluct
= 0;
5738 unsigned int max_size
, size
, size_found
= 0;
5739 long long cost
= 0, prev_cost
;
5743 * Search from max_cache_size*5 down to 64K - the real relevant
5744 * cachesize has to lie somewhere inbetween.
5746 if (max_cache_size
) {
5747 max_size
= max(max_cache_size
* SEARCH_SCOPE
, MIN_CACHE_SIZE
);
5748 size
= max(max_cache_size
/ SEARCH_SCOPE
, MIN_CACHE_SIZE
);
5751 * Since we have no estimation about the relevant
5754 max_size
= DEFAULT_CACHE_SIZE
* SEARCH_SCOPE
;
5755 size
= MIN_CACHE_SIZE
;
5758 if (!cpu_online(cpu1
) || !cpu_online(cpu2
)) {
5759 printk("cpu %d and %d not both online!\n", cpu1
, cpu2
);
5764 * Allocate the working set:
5766 cache
= vmalloc(max_size
);
5768 printk("could not vmalloc %d bytes for cache!\n", 2*max_size
);
5769 return 1000000; // return 1 msec on very small boxen
5772 while (size
<= max_size
) {
5774 cost
= measure_cost(cpu1
, cpu2
, cache
, size
);
5780 if (max_cost
< cost
) {
5786 * Calculate average fluctuation, we use this to prevent
5787 * noise from triggering an early break out of the loop:
5789 fluct
= abs(cost
- prev_cost
);
5790 avg_fluct
= (avg_fluct
+ fluct
)/2;
5792 if (migration_debug
)
5793 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5795 (long)cost
/ 1000000,
5796 ((long)cost
/ 100000) % 10,
5797 (long)max_cost
/ 1000000,
5798 ((long)max_cost
/ 100000) % 10,
5799 domain_distance(cpu1
, cpu2
),
5803 * If we iterated at least 20% past the previous maximum,
5804 * and the cost has dropped by more than 20% already,
5805 * (taking fluctuations into account) then we assume to
5806 * have found the maximum and break out of the loop early:
5808 if (size_found
&& (size
*100 > size_found
*SIZE_THRESH
))
5809 if (cost
+avg_fluct
<= 0 ||
5810 max_cost
*100 > (cost
+avg_fluct
)*COST_THRESH
) {
5812 if (migration_debug
)
5813 printk("-> found max.\n");
5817 * Increase the cachesize in 10% steps:
5819 size
= size
* 10 / 9;
5822 if (migration_debug
)
5823 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5824 cpu1
, cpu2
, size_found
, max_cost
);
5829 * A task is considered 'cache cold' if at least 2 times
5830 * the worst-case cost of migration has passed.
5832 * (this limit is only listened to if the load-balancing
5833 * situation is 'nice' - if there is a large imbalance we
5834 * ignore it for the sake of CPU utilization and
5835 * processing fairness.)
5837 return 2 * max_cost
* migration_factor
/ MIGRATION_FACTOR_SCALE
;
5840 static void calibrate_migration_costs(const cpumask_t
*cpu_map
)
5842 int cpu1
= -1, cpu2
= -1, cpu
, orig_cpu
= raw_smp_processor_id();
5843 unsigned long j0
, j1
, distance
, max_distance
= 0;
5844 struct sched_domain
*sd
;
5849 * First pass - calculate the cacheflush times:
5851 for_each_cpu_mask(cpu1
, *cpu_map
) {
5852 for_each_cpu_mask(cpu2
, *cpu_map
) {
5855 distance
= domain_distance(cpu1
, cpu2
);
5856 max_distance
= max(max_distance
, distance
);
5858 * No result cached yet?
5860 if (migration_cost
[distance
] == -1LL)
5861 migration_cost
[distance
] =
5862 measure_migration_cost(cpu1
, cpu2
);
5866 * Second pass - update the sched domain hierarchy with
5867 * the new cache-hot-time estimations:
5869 for_each_cpu_mask(cpu
, *cpu_map
) {
5871 for_each_domain(cpu
, sd
) {
5872 sd
->cache_hot_time
= migration_cost
[distance
];
5879 if (migration_debug
)
5880 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5888 if (system_state
== SYSTEM_BOOTING
) {
5889 printk("migration_cost=");
5890 for (distance
= 0; distance
<= max_distance
; distance
++) {
5893 printk("%ld", (long)migration_cost
[distance
] / 1000);
5898 if (migration_debug
)
5899 printk("migration: %ld seconds\n", (j1
-j0
)/HZ
);
5902 * Move back to the original CPU. NUMA-Q gets confused
5903 * if we migrate to another quad during bootup.
5905 if (raw_smp_processor_id() != orig_cpu
) {
5906 cpumask_t mask
= cpumask_of_cpu(orig_cpu
),
5907 saved_mask
= current
->cpus_allowed
;
5909 set_cpus_allowed(current
, mask
);
5910 set_cpus_allowed(current
, saved_mask
);
5917 * find_next_best_node - find the next node to include in a sched_domain
5918 * @node: node whose sched_domain we're building
5919 * @used_nodes: nodes already in the sched_domain
5921 * Find the next node to include in a given scheduling domain. Simply
5922 * finds the closest node not already in the @used_nodes map.
5924 * Should use nodemask_t.
5926 static int find_next_best_node(int node
, unsigned long *used_nodes
)
5928 int i
, n
, val
, min_val
, best_node
= 0;
5932 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
5933 /* Start at @node */
5934 n
= (node
+ i
) % MAX_NUMNODES
;
5936 if (!nr_cpus_node(n
))
5939 /* Skip already used nodes */
5940 if (test_bit(n
, used_nodes
))
5943 /* Simple min distance search */
5944 val
= node_distance(node
, n
);
5946 if (val
< min_val
) {
5952 set_bit(best_node
, used_nodes
);
5957 * sched_domain_node_span - get a cpumask for a node's sched_domain
5958 * @node: node whose cpumask we're constructing
5959 * @size: number of nodes to include in this span
5961 * Given a node, construct a good cpumask for its sched_domain to span. It
5962 * should be one that prevents unnecessary balancing, but also spreads tasks
5965 static cpumask_t
sched_domain_node_span(int node
)
5967 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
5968 cpumask_t span
, nodemask
;
5972 bitmap_zero(used_nodes
, MAX_NUMNODES
);
5974 nodemask
= node_to_cpumask(node
);
5975 cpus_or(span
, span
, nodemask
);
5976 set_bit(node
, used_nodes
);
5978 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
5979 int next_node
= find_next_best_node(node
, used_nodes
);
5981 nodemask
= node_to_cpumask(next_node
);
5982 cpus_or(span
, span
, nodemask
);
5989 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
5992 * SMT sched-domains:
5994 #ifdef CONFIG_SCHED_SMT
5995 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
5996 static struct sched_group sched_group_cpus
[NR_CPUS
];
5998 static int cpu_to_cpu_group(int cpu
)
6005 * multi-core sched-domains:
6007 #ifdef CONFIG_SCHED_MC
6008 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6009 static struct sched_group
*sched_group_core_bycpu
[NR_CPUS
];
6012 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6013 static int cpu_to_core_group(int cpu
)
6015 return first_cpu(cpu_sibling_map
[cpu
]);
6017 #elif defined(CONFIG_SCHED_MC)
6018 static int cpu_to_core_group(int cpu
)
6024 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6025 static struct sched_group
*sched_group_phys_bycpu
[NR_CPUS
];
6027 static int cpu_to_phys_group(int cpu
)
6029 #ifdef CONFIG_SCHED_MC
6030 cpumask_t mask
= cpu_coregroup_map(cpu
);
6031 return first_cpu(mask
);
6032 #elif defined(CONFIG_SCHED_SMT)
6033 return first_cpu(cpu_sibling_map
[cpu
]);
6041 * The init_sched_build_groups can't handle what we want to do with node
6042 * groups, so roll our own. Now each node has its own list of groups which
6043 * gets dynamically allocated.
6045 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6046 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6048 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6049 static struct sched_group
*sched_group_allnodes_bycpu
[NR_CPUS
];
6051 static int cpu_to_allnodes_group(int cpu
)
6053 return cpu_to_node(cpu
);
6055 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6057 struct sched_group
*sg
= group_head
;
6063 for_each_cpu_mask(j
, sg
->cpumask
) {
6064 struct sched_domain
*sd
;
6066 sd
= &per_cpu(phys_domains
, j
);
6067 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6069 * Only add "power" once for each
6075 sg
->cpu_power
+= sd
->groups
->cpu_power
;
6078 if (sg
!= group_head
)
6083 /* Free memory allocated for various sched_group structures */
6084 static void free_sched_groups(const cpumask_t
*cpu_map
)
6090 for_each_cpu_mask(cpu
, *cpu_map
) {
6091 struct sched_group
*sched_group_allnodes
6092 = sched_group_allnodes_bycpu
[cpu
];
6093 struct sched_group
**sched_group_nodes
6094 = sched_group_nodes_bycpu
[cpu
];
6096 if (sched_group_allnodes
) {
6097 kfree(sched_group_allnodes
);
6098 sched_group_allnodes_bycpu
[cpu
] = NULL
;
6101 if (!sched_group_nodes
)
6104 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6105 cpumask_t nodemask
= node_to_cpumask(i
);
6106 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6108 cpus_and(nodemask
, nodemask
, *cpu_map
);
6109 if (cpus_empty(nodemask
))
6119 if (oldsg
!= sched_group_nodes
[i
])
6122 kfree(sched_group_nodes
);
6123 sched_group_nodes_bycpu
[cpu
] = NULL
;
6126 for_each_cpu_mask(cpu
, *cpu_map
) {
6127 if (sched_group_phys_bycpu
[cpu
]) {
6128 kfree(sched_group_phys_bycpu
[cpu
]);
6129 sched_group_phys_bycpu
[cpu
] = NULL
;
6131 #ifdef CONFIG_SCHED_MC
6132 if (sched_group_core_bycpu
[cpu
]) {
6133 kfree(sched_group_core_bycpu
[cpu
]);
6134 sched_group_core_bycpu
[cpu
] = NULL
;
6141 * Build sched domains for a given set of cpus and attach the sched domains
6142 * to the individual cpus
6144 static int build_sched_domains(const cpumask_t
*cpu_map
)
6147 struct sched_group
*sched_group_phys
= NULL
;
6148 #ifdef CONFIG_SCHED_MC
6149 struct sched_group
*sched_group_core
= NULL
;
6152 struct sched_group
**sched_group_nodes
= NULL
;
6153 struct sched_group
*sched_group_allnodes
= NULL
;
6156 * Allocate the per-node list of sched groups
6158 sched_group_nodes
= kzalloc(sizeof(struct sched_group
*)*MAX_NUMNODES
,
6160 if (!sched_group_nodes
) {
6161 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6164 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6168 * Set up domains for cpus specified by the cpu_map.
6170 for_each_cpu_mask(i
, *cpu_map
) {
6172 struct sched_domain
*sd
= NULL
, *p
;
6173 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6175 cpus_and(nodemask
, nodemask
, *cpu_map
);
6178 if (cpus_weight(*cpu_map
)
6179 > SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6180 if (!sched_group_allnodes
) {
6181 sched_group_allnodes
6182 = kmalloc(sizeof(struct sched_group
)
6185 if (!sched_group_allnodes
) {
6187 "Can not alloc allnodes sched group\n");
6190 sched_group_allnodes_bycpu
[i
]
6191 = sched_group_allnodes
;
6193 sd
= &per_cpu(allnodes_domains
, i
);
6194 *sd
= SD_ALLNODES_INIT
;
6195 sd
->span
= *cpu_map
;
6196 group
= cpu_to_allnodes_group(i
);
6197 sd
->groups
= &sched_group_allnodes
[group
];
6202 sd
= &per_cpu(node_domains
, i
);
6204 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6206 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6209 if (!sched_group_phys
) {
6211 = kmalloc(sizeof(struct sched_group
) * NR_CPUS
,
6213 if (!sched_group_phys
) {
6214 printk (KERN_WARNING
"Can not alloc phys sched"
6218 sched_group_phys_bycpu
[i
] = sched_group_phys
;
6222 sd
= &per_cpu(phys_domains
, i
);
6223 group
= cpu_to_phys_group(i
);
6225 sd
->span
= nodemask
;
6227 sd
->groups
= &sched_group_phys
[group
];
6229 #ifdef CONFIG_SCHED_MC
6230 if (!sched_group_core
) {
6232 = kmalloc(sizeof(struct sched_group
) * NR_CPUS
,
6234 if (!sched_group_core
) {
6235 printk (KERN_WARNING
"Can not alloc core sched"
6239 sched_group_core_bycpu
[i
] = sched_group_core
;
6243 sd
= &per_cpu(core_domains
, i
);
6244 group
= cpu_to_core_group(i
);
6246 sd
->span
= cpu_coregroup_map(i
);
6247 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6249 sd
->groups
= &sched_group_core
[group
];
6252 #ifdef CONFIG_SCHED_SMT
6254 sd
= &per_cpu(cpu_domains
, i
);
6255 group
= cpu_to_cpu_group(i
);
6256 *sd
= SD_SIBLING_INIT
;
6257 sd
->span
= cpu_sibling_map
[i
];
6258 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6260 sd
->groups
= &sched_group_cpus
[group
];
6264 #ifdef CONFIG_SCHED_SMT
6265 /* Set up CPU (sibling) groups */
6266 for_each_cpu_mask(i
, *cpu_map
) {
6267 cpumask_t this_sibling_map
= cpu_sibling_map
[i
];
6268 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6269 if (i
!= first_cpu(this_sibling_map
))
6272 init_sched_build_groups(sched_group_cpus
, this_sibling_map
,
6277 #ifdef CONFIG_SCHED_MC
6278 /* Set up multi-core groups */
6279 for_each_cpu_mask(i
, *cpu_map
) {
6280 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6281 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6282 if (i
!= first_cpu(this_core_map
))
6284 init_sched_build_groups(sched_group_core
, this_core_map
,
6285 &cpu_to_core_group
);
6290 /* Set up physical groups */
6291 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6292 cpumask_t nodemask
= node_to_cpumask(i
);
6294 cpus_and(nodemask
, nodemask
, *cpu_map
);
6295 if (cpus_empty(nodemask
))
6298 init_sched_build_groups(sched_group_phys
, nodemask
,
6299 &cpu_to_phys_group
);
6303 /* Set up node groups */
6304 if (sched_group_allnodes
)
6305 init_sched_build_groups(sched_group_allnodes
, *cpu_map
,
6306 &cpu_to_allnodes_group
);
6308 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6309 /* Set up node groups */
6310 struct sched_group
*sg
, *prev
;
6311 cpumask_t nodemask
= node_to_cpumask(i
);
6312 cpumask_t domainspan
;
6313 cpumask_t covered
= CPU_MASK_NONE
;
6316 cpus_and(nodemask
, nodemask
, *cpu_map
);
6317 if (cpus_empty(nodemask
)) {
6318 sched_group_nodes
[i
] = NULL
;
6322 domainspan
= sched_domain_node_span(i
);
6323 cpus_and(domainspan
, domainspan
, *cpu_map
);
6325 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6327 printk(KERN_WARNING
"Can not alloc domain group for "
6331 sched_group_nodes
[i
] = sg
;
6332 for_each_cpu_mask(j
, nodemask
) {
6333 struct sched_domain
*sd
;
6334 sd
= &per_cpu(node_domains
, j
);
6338 sg
->cpumask
= nodemask
;
6340 cpus_or(covered
, covered
, nodemask
);
6343 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6344 cpumask_t tmp
, notcovered
;
6345 int n
= (i
+ j
) % MAX_NUMNODES
;
6347 cpus_complement(notcovered
, covered
);
6348 cpus_and(tmp
, notcovered
, *cpu_map
);
6349 cpus_and(tmp
, tmp
, domainspan
);
6350 if (cpus_empty(tmp
))
6353 nodemask
= node_to_cpumask(n
);
6354 cpus_and(tmp
, tmp
, nodemask
);
6355 if (cpus_empty(tmp
))
6358 sg
= kmalloc_node(sizeof(struct sched_group
),
6362 "Can not alloc domain group for node %d\n", j
);
6367 sg
->next
= prev
->next
;
6368 cpus_or(covered
, covered
, tmp
);
6375 /* Calculate CPU power for physical packages and nodes */
6376 #ifdef CONFIG_SCHED_SMT
6377 for_each_cpu_mask(i
, *cpu_map
) {
6378 struct sched_domain
*sd
;
6379 sd
= &per_cpu(cpu_domains
, i
);
6380 sd
->groups
->cpu_power
= SCHED_LOAD_SCALE
;
6383 #ifdef CONFIG_SCHED_MC
6384 for_each_cpu_mask(i
, *cpu_map
) {
6386 struct sched_domain
*sd
;
6387 sd
= &per_cpu(core_domains
, i
);
6388 if (sched_smt_power_savings
)
6389 power
= SCHED_LOAD_SCALE
* cpus_weight(sd
->groups
->cpumask
);
6391 power
= SCHED_LOAD_SCALE
+ (cpus_weight(sd
->groups
->cpumask
)-1)
6392 * SCHED_LOAD_SCALE
/ 10;
6393 sd
->groups
->cpu_power
= power
;
6397 for_each_cpu_mask(i
, *cpu_map
) {
6398 struct sched_domain
*sd
;
6399 #ifdef CONFIG_SCHED_MC
6400 sd
= &per_cpu(phys_domains
, i
);
6401 if (i
!= first_cpu(sd
->groups
->cpumask
))
6404 sd
->groups
->cpu_power
= 0;
6405 if (sched_mc_power_savings
|| sched_smt_power_savings
) {
6408 for_each_cpu_mask(j
, sd
->groups
->cpumask
) {
6409 struct sched_domain
*sd1
;
6410 sd1
= &per_cpu(core_domains
, j
);
6412 * for each core we will add once
6413 * to the group in physical domain
6415 if (j
!= first_cpu(sd1
->groups
->cpumask
))
6418 if (sched_smt_power_savings
)
6419 sd
->groups
->cpu_power
+= sd1
->groups
->cpu_power
;
6421 sd
->groups
->cpu_power
+= SCHED_LOAD_SCALE
;
6425 * This has to be < 2 * SCHED_LOAD_SCALE
6426 * Lets keep it SCHED_LOAD_SCALE, so that
6427 * while calculating NUMA group's cpu_power
6429 * numa_group->cpu_power += phys_group->cpu_power;
6431 * See "only add power once for each physical pkg"
6434 sd
->groups
->cpu_power
= SCHED_LOAD_SCALE
;
6437 sd
= &per_cpu(phys_domains
, i
);
6438 if (sched_smt_power_savings
)
6439 power
= SCHED_LOAD_SCALE
* cpus_weight(sd
->groups
->cpumask
);
6441 power
= SCHED_LOAD_SCALE
;
6442 sd
->groups
->cpu_power
= power
;
6447 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6448 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6450 init_numa_sched_groups_power(sched_group_allnodes
);
6453 /* Attach the domains */
6454 for_each_cpu_mask(i
, *cpu_map
) {
6455 struct sched_domain
*sd
;
6456 #ifdef CONFIG_SCHED_SMT
6457 sd
= &per_cpu(cpu_domains
, i
);
6458 #elif defined(CONFIG_SCHED_MC)
6459 sd
= &per_cpu(core_domains
, i
);
6461 sd
= &per_cpu(phys_domains
, i
);
6463 cpu_attach_domain(sd
, i
);
6466 * Tune cache-hot values:
6468 calibrate_migration_costs(cpu_map
);
6473 free_sched_groups(cpu_map
);
6477 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6479 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6481 cpumask_t cpu_default_map
;
6485 * Setup mask for cpus without special case scheduling requirements.
6486 * For now this just excludes isolated cpus, but could be used to
6487 * exclude other special cases in the future.
6489 cpus_andnot(cpu_default_map
, *cpu_map
, cpu_isolated_map
);
6491 err
= build_sched_domains(&cpu_default_map
);
6496 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6498 free_sched_groups(cpu_map
);
6502 * Detach sched domains from a group of cpus specified in cpu_map
6503 * These cpus will now be attached to the NULL domain
6505 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6509 for_each_cpu_mask(i
, *cpu_map
)
6510 cpu_attach_domain(NULL
, i
);
6511 synchronize_sched();
6512 arch_destroy_sched_domains(cpu_map
);
6516 * Partition sched domains as specified by the cpumasks below.
6517 * This attaches all cpus from the cpumasks to the NULL domain,
6518 * waits for a RCU quiescent period, recalculates sched
6519 * domain information and then attaches them back to the
6520 * correct sched domains
6521 * Call with hotplug lock held
6523 int partition_sched_domains(cpumask_t
*partition1
, cpumask_t
*partition2
)
6525 cpumask_t change_map
;
6528 cpus_and(*partition1
, *partition1
, cpu_online_map
);
6529 cpus_and(*partition2
, *partition2
, cpu_online_map
);
6530 cpus_or(change_map
, *partition1
, *partition2
);
6532 /* Detach sched domains from all of the affected cpus */
6533 detach_destroy_domains(&change_map
);
6534 if (!cpus_empty(*partition1
))
6535 err
= build_sched_domains(partition1
);
6536 if (!err
&& !cpus_empty(*partition2
))
6537 err
= build_sched_domains(partition2
);
6542 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6543 int arch_reinit_sched_domains(void)
6548 detach_destroy_domains(&cpu_online_map
);
6549 err
= arch_init_sched_domains(&cpu_online_map
);
6550 unlock_cpu_hotplug();
6555 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
6559 if (buf
[0] != '0' && buf
[0] != '1')
6563 sched_smt_power_savings
= (buf
[0] == '1');
6565 sched_mc_power_savings
= (buf
[0] == '1');
6567 ret
= arch_reinit_sched_domains();
6569 return ret
? ret
: count
;
6572 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
6576 #ifdef CONFIG_SCHED_SMT
6578 err
= sysfs_create_file(&cls
->kset
.kobj
,
6579 &attr_sched_smt_power_savings
.attr
);
6581 #ifdef CONFIG_SCHED_MC
6582 if (!err
&& mc_capable())
6583 err
= sysfs_create_file(&cls
->kset
.kobj
,
6584 &attr_sched_mc_power_savings
.attr
);
6590 #ifdef CONFIG_SCHED_MC
6591 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
6593 return sprintf(page
, "%u\n", sched_mc_power_savings
);
6595 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
6596 const char *buf
, size_t count
)
6598 return sched_power_savings_store(buf
, count
, 0);
6600 SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
6601 sched_mc_power_savings_store
);
6604 #ifdef CONFIG_SCHED_SMT
6605 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
6607 return sprintf(page
, "%u\n", sched_smt_power_savings
);
6609 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
6610 const char *buf
, size_t count
)
6612 return sched_power_savings_store(buf
, count
, 1);
6614 SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
6615 sched_smt_power_savings_store
);
6619 #ifdef CONFIG_HOTPLUG_CPU
6621 * Force a reinitialization of the sched domains hierarchy. The domains
6622 * and groups cannot be updated in place without racing with the balancing
6623 * code, so we temporarily attach all running cpus to the NULL domain
6624 * which will prevent rebalancing while the sched domains are recalculated.
6626 static int update_sched_domains(struct notifier_block
*nfb
,
6627 unsigned long action
, void *hcpu
)
6630 case CPU_UP_PREPARE
:
6631 case CPU_DOWN_PREPARE
:
6632 detach_destroy_domains(&cpu_online_map
);
6635 case CPU_UP_CANCELED
:
6636 case CPU_DOWN_FAILED
:
6640 * Fall through and re-initialise the domains.
6647 /* The hotplug lock is already held by cpu_up/cpu_down */
6648 arch_init_sched_domains(&cpu_online_map
);
6654 void __init
sched_init_smp(void)
6657 arch_init_sched_domains(&cpu_online_map
);
6658 unlock_cpu_hotplug();
6659 /* XXX: Theoretical race here - CPU may be hotplugged now */
6660 hotcpu_notifier(update_sched_domains
, 0);
6663 void __init
sched_init_smp(void)
6666 #endif /* CONFIG_SMP */
6668 int in_sched_functions(unsigned long addr
)
6670 /* Linker adds these: start and end of __sched functions */
6671 extern char __sched_text_start
[], __sched_text_end
[];
6673 return in_lock_functions(addr
) ||
6674 (addr
>= (unsigned long)__sched_text_start
6675 && addr
< (unsigned long)__sched_text_end
);
6678 void __init
sched_init(void)
6682 for_each_possible_cpu(i
) {
6683 prio_array_t
*array
;
6687 spin_lock_init(&rq
->lock
);
6688 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
6690 rq
->active
= rq
->arrays
;
6691 rq
->expired
= rq
->arrays
+ 1;
6692 rq
->best_expired_prio
= MAX_PRIO
;
6696 for (j
= 1; j
< 3; j
++)
6697 rq
->cpu_load
[j
] = 0;
6698 rq
->active_balance
= 0;
6700 rq
->migration_thread
= NULL
;
6701 INIT_LIST_HEAD(&rq
->migration_queue
);
6703 atomic_set(&rq
->nr_iowait
, 0);
6705 for (j
= 0; j
< 2; j
++) {
6706 array
= rq
->arrays
+ j
;
6707 for (k
= 0; k
< MAX_PRIO
; k
++) {
6708 INIT_LIST_HEAD(array
->queue
+ k
);
6709 __clear_bit(k
, array
->bitmap
);
6711 // delimiter for bitsearch
6712 __set_bit(MAX_PRIO
, array
->bitmap
);
6716 set_load_weight(&init_task
);
6718 * The boot idle thread does lazy MMU switching as well:
6720 atomic_inc(&init_mm
.mm_count
);
6721 enter_lazy_tlb(&init_mm
, current
);
6724 * Make us the idle thread. Technically, schedule() should not be
6725 * called from this thread, however somewhere below it might be,
6726 * but because we are the idle thread, we just pick up running again
6727 * when this runqueue becomes "idle".
6729 init_idle(current
, smp_processor_id());
6732 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6733 void __might_sleep(char *file
, int line
)
6736 static unsigned long prev_jiffy
; /* ratelimiting */
6738 if ((in_atomic() || irqs_disabled()) &&
6739 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
6740 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
6742 prev_jiffy
= jiffies
;
6743 printk(KERN_ERR
"BUG: sleeping function called from invalid"
6744 " context at %s:%d\n", file
, line
);
6745 printk("in_atomic():%d, irqs_disabled():%d\n",
6746 in_atomic(), irqs_disabled());
6751 EXPORT_SYMBOL(__might_sleep
);
6754 #ifdef CONFIG_MAGIC_SYSRQ
6755 void normalize_rt_tasks(void)
6757 struct task_struct
*p
;
6758 prio_array_t
*array
;
6759 unsigned long flags
;
6762 read_lock_irq(&tasklist_lock
);
6763 for_each_process(p
) {
6767 spin_lock_irqsave(&p
->pi_lock
, flags
);
6768 rq
= __task_rq_lock(p
);
6772 deactivate_task(p
, task_rq(p
));
6773 __setscheduler(p
, SCHED_NORMAL
, 0);
6775 __activate_task(p
, task_rq(p
));
6776 resched_task(rq
->curr
);
6779 __task_rq_unlock(rq
);
6780 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
6782 read_unlock_irq(&tasklist_lock
);
6785 #endif /* CONFIG_MAGIC_SYSRQ */
6789 * These functions are only useful for the IA64 MCA handling.
6791 * They can only be called when the whole system has been
6792 * stopped - every CPU needs to be quiescent, and no scheduling
6793 * activity can take place. Using them for anything else would
6794 * be a serious bug, and as a result, they aren't even visible
6795 * under any other configuration.
6799 * curr_task - return the current task for a given cpu.
6800 * @cpu: the processor in question.
6802 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6804 task_t
*curr_task(int cpu
)
6806 return cpu_curr(cpu
);
6810 * set_curr_task - set the current task for a given cpu.
6811 * @cpu: the processor in question.
6812 * @p: the task pointer to set.
6814 * Description: This function must only be used when non-maskable interrupts
6815 * are serviced on a separate stack. It allows the architecture to switch the
6816 * notion of the current task on a cpu in a non-blocking manner. This function
6817 * must be called with all CPU's synchronized, and interrupts disabled, the
6818 * and caller must save the original value of the current task (see
6819 * curr_task() above) and restore that value before reenabling interrupts and
6820 * re-starting the system.
6822 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6824 void set_curr_task(int cpu
, task_t
*p
)