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/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/timer.h>
40 #include <linux/rcupdate.h>
41 #include <linux/cpu.h>
42 #include <linux/percpu.h>
43 #include <linux/kthread.h>
44 #include <linux/seq_file.h>
45 #include <linux/times.h>
48 #include <asm/unistd.h>
51 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
53 #define cpu_to_node_mask(cpu) (cpu_online_map)
57 * Convert user-nice values [ -20 ... 0 ... 19 ]
58 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
61 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
62 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
63 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
66 * 'User priority' is the nice value converted to something we
67 * can work with better when scaling various scheduler parameters,
68 * it's a [ 0 ... 39 ] range.
70 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
71 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
72 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
75 * Some helpers for converting nanosecond timing to jiffy resolution
77 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
78 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
81 * These are the 'tuning knobs' of the scheduler:
83 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
84 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
85 * Timeslices get refilled after they expire.
87 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
88 #define DEF_TIMESLICE (100 * HZ / 1000)
89 #define ON_RUNQUEUE_WEIGHT 30
90 #define CHILD_PENALTY 95
91 #define PARENT_PENALTY 100
93 #define PRIO_BONUS_RATIO 25
94 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
95 #define INTERACTIVE_DELTA 2
96 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
97 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
98 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
99 #define CREDIT_LIMIT 100
102 * If a task is 'interactive' then we reinsert it in the active
103 * array after it has expired its current timeslice. (it will not
104 * continue to run immediately, it will still roundrobin with
105 * other interactive tasks.)
107 * This part scales the interactivity limit depending on niceness.
109 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
110 * Here are a few examples of different nice levels:
112 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
113 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
114 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
118 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
119 * priority range a task can explore, a value of '1' means the
120 * task is rated interactive.)
122 * Ie. nice +19 tasks can never get 'interactive' enough to be
123 * reinserted into the active array. And only heavily CPU-hog nice -20
124 * tasks will be expired. Default nice 0 tasks are somewhere between,
125 * it takes some effort for them to get interactive, but it's not
129 #define CURRENT_BONUS(p) \
130 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
134 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
135 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
138 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
142 #define SCALE(v1,v1_max,v2_max) \
143 (v1) * (v2_max) / (v1_max)
146 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
148 #define TASK_INTERACTIVE(p) \
149 ((p)->prio <= (p)->static_prio - DELTA(p))
151 #define INTERACTIVE_SLEEP(p) \
152 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
153 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
155 #define HIGH_CREDIT(p) \
156 ((p)->interactive_credit > CREDIT_LIMIT)
158 #define LOW_CREDIT(p) \
159 ((p)->interactive_credit < -CREDIT_LIMIT)
161 #define TASK_PREEMPTS_CURR(p, rq) \
162 ((p)->prio < (rq)->curr->prio)
165 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
166 * to time slice values: [800ms ... 100ms ... 5ms]
168 * The higher a thread's priority, the bigger timeslices
169 * it gets during one round of execution. But even the lowest
170 * priority thread gets MIN_TIMESLICE worth of execution time.
173 #define SCALE_PRIO(x, prio) \
174 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
176 static unsigned int task_timeslice(task_t
*p
)
178 if (p
->static_prio
< NICE_TO_PRIO(0))
179 return SCALE_PRIO(DEF_TIMESLICE
*4, p
->static_prio
);
181 return SCALE_PRIO(DEF_TIMESLICE
, p
->static_prio
);
183 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
184 < (long long) (sd)->cache_hot_time)
197 * These are the runqueue data structures:
200 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
202 typedef struct runqueue runqueue_t
;
205 unsigned int nr_active
;
206 unsigned long bitmap
[BITMAP_SIZE
];
207 struct list_head queue
[MAX_PRIO
];
211 * This is the main, per-CPU runqueue data structure.
213 * Locking rule: those places that want to lock multiple runqueues
214 * (such as the load balancing or the thread migration code), lock
215 * acquire operations must be ordered by ascending &runqueue.
221 * nr_running and cpu_load should be in the same cacheline because
222 * remote CPUs use both these fields when doing load calculation.
224 unsigned long nr_running
;
226 unsigned long cpu_load
;
228 unsigned long long nr_switches
;
229 unsigned long expired_timestamp
, nr_uninterruptible
;
230 unsigned long long timestamp_last_tick
;
232 struct mm_struct
*prev_mm
;
233 prio_array_t
*active
, *expired
, arrays
[2];
234 int best_expired_prio
;
238 struct sched_domain
*sd
;
240 /* For active balancing */
244 task_t
*migration_thread
;
245 struct list_head migration_queue
;
248 #ifdef CONFIG_SCHEDSTATS
250 struct sched_info rq_sched_info
;
252 /* sys_sched_yield() stats */
253 unsigned long yld_exp_empty
;
254 unsigned long yld_act_empty
;
255 unsigned long yld_both_empty
;
256 unsigned long yld_cnt
;
258 /* schedule() stats */
259 unsigned long sched_noswitch
;
260 unsigned long sched_switch
;
261 unsigned long sched_cnt
;
262 unsigned long sched_goidle
;
264 /* pull_task() stats */
265 unsigned long pt_gained
[MAX_IDLE_TYPES
];
266 unsigned long pt_lost
[MAX_IDLE_TYPES
];
268 /* active_load_balance() stats */
269 unsigned long alb_cnt
;
270 unsigned long alb_lost
;
271 unsigned long alb_gained
;
272 unsigned long alb_failed
;
274 /* try_to_wake_up() stats */
275 unsigned long ttwu_cnt
;
276 unsigned long ttwu_attempts
;
277 unsigned long ttwu_moved
;
279 /* wake_up_new_task() stats */
280 unsigned long wunt_cnt
;
281 unsigned long wunt_moved
;
283 /* sched_migrate_task() stats */
284 unsigned long smt_cnt
;
286 /* sched_balance_exec() stats */
287 unsigned long sbe_cnt
;
291 static DEFINE_PER_CPU(struct runqueue
, runqueues
);
294 * sched-domains (multiprocessor balancing) declarations:
297 #define SCHED_LOAD_SCALE 128UL /* increase resolution of load */
299 #define SD_BALANCE_NEWIDLE 1 /* Balance when about to become idle */
300 #define SD_BALANCE_EXEC 2 /* Balance on exec */
301 #define SD_WAKE_IDLE 4 /* Wake to idle CPU on task wakeup */
302 #define SD_WAKE_AFFINE 8 /* Wake task to waking CPU */
303 #define SD_WAKE_BALANCE 16 /* Perform balancing at task wakeup */
304 #define SD_SHARE_CPUPOWER 32 /* Domain members share cpu power */
307 struct sched_group
*next
; /* Must be a circular list */
311 * CPU power of this group, SCHED_LOAD_SCALE being max power for a
312 * single CPU. This should be read only (except for setup). Although
313 * it will need to be written to at cpu hot(un)plug time, perhaps the
314 * cpucontrol semaphore will provide enough exclusion?
316 unsigned long cpu_power
;
319 struct sched_domain
{
320 /* These fields must be setup */
321 struct sched_domain
*parent
; /* top domain must be null terminated */
322 struct sched_group
*groups
; /* the balancing groups of the domain */
323 cpumask_t span
; /* span of all CPUs in this domain */
324 unsigned long min_interval
; /* Minimum balance interval ms */
325 unsigned long max_interval
; /* Maximum balance interval ms */
326 unsigned int busy_factor
; /* less balancing by factor if busy */
327 unsigned int imbalance_pct
; /* No balance until over watermark */
328 unsigned long long cache_hot_time
; /* Task considered cache hot (ns) */
329 unsigned int cache_nice_tries
; /* Leave cache hot tasks for # tries */
330 unsigned int per_cpu_gain
; /* CPU % gained by adding domain cpus */
331 int flags
; /* See SD_* */
333 /* Runtime fields. */
334 unsigned long last_balance
; /* init to jiffies. units in jiffies */
335 unsigned int balance_interval
; /* initialise to 1. units in ms. */
336 unsigned int nr_balance_failed
; /* initialise to 0 */
338 #ifdef CONFIG_SCHEDSTATS
339 /* load_balance() stats */
340 unsigned long lb_cnt
[MAX_IDLE_TYPES
];
341 unsigned long lb_failed
[MAX_IDLE_TYPES
];
342 unsigned long lb_imbalance
[MAX_IDLE_TYPES
];
343 unsigned long lb_nobusyg
[MAX_IDLE_TYPES
];
344 unsigned long lb_nobusyq
[MAX_IDLE_TYPES
];
346 /* sched_balance_exec() stats */
347 unsigned long sbe_attempts
;
348 unsigned long sbe_pushed
;
350 /* try_to_wake_up() stats */
351 unsigned long ttwu_wake_affine
;
352 unsigned long ttwu_wake_balance
;
356 #ifndef ARCH_HAS_SCHED_TUNE
357 #ifdef CONFIG_SCHED_SMT
358 #define ARCH_HAS_SCHED_WAKE_IDLE
359 /* Common values for SMT siblings */
360 #define SD_SIBLING_INIT (struct sched_domain) { \
361 .span = CPU_MASK_NONE, \
367 .imbalance_pct = 110, \
368 .cache_hot_time = 0, \
369 .cache_nice_tries = 0, \
370 .per_cpu_gain = 25, \
371 .flags = SD_BALANCE_NEWIDLE \
375 | SD_SHARE_CPUPOWER, \
376 .last_balance = jiffies, \
377 .balance_interval = 1, \
378 .nr_balance_failed = 0, \
382 /* Common values for CPUs */
383 #define SD_CPU_INIT (struct sched_domain) { \
384 .span = CPU_MASK_NONE, \
390 .imbalance_pct = 125, \
391 .cache_hot_time = cache_decay_ticks*1000000 ? : (5*1000000/2),\
392 .cache_nice_tries = 1, \
393 .per_cpu_gain = 100, \
394 .flags = SD_BALANCE_NEWIDLE \
398 .last_balance = jiffies, \
399 .balance_interval = 1, \
400 .nr_balance_failed = 0, \
403 /* Arch can override this macro in processor.h */
404 #if defined(CONFIG_NUMA) && !defined(SD_NODE_INIT)
405 #define SD_NODE_INIT (struct sched_domain) { \
406 .span = CPU_MASK_NONE, \
410 .max_interval = 32, \
412 .imbalance_pct = 125, \
413 .cache_hot_time = (10*1000000), \
414 .cache_nice_tries = 1, \
415 .per_cpu_gain = 100, \
416 .flags = SD_BALANCE_EXEC \
418 .last_balance = jiffies, \
419 .balance_interval = 1, \
420 .nr_balance_failed = 0, \
423 #endif /* ARCH_HAS_SCHED_TUNE */
427 #define for_each_domain(cpu, domain) \
428 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
430 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
431 #define this_rq() (&__get_cpu_var(runqueues))
432 #define task_rq(p) cpu_rq(task_cpu(p))
433 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
436 * Default context-switch locking:
438 #ifndef prepare_arch_switch
439 # define prepare_arch_switch(rq, next) do { } while (0)
440 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
441 # define task_running(rq, p) ((rq)->curr == (p))
445 * task_rq_lock - lock the runqueue a given task resides on and disable
446 * interrupts. Note the ordering: we can safely lookup the task_rq without
447 * explicitly disabling preemption.
449 static runqueue_t
*task_rq_lock(task_t
*p
, unsigned long *flags
)
454 local_irq_save(*flags
);
456 spin_lock(&rq
->lock
);
457 if (unlikely(rq
!= task_rq(p
))) {
458 spin_unlock_irqrestore(&rq
->lock
, *flags
);
459 goto repeat_lock_task
;
464 static inline void task_rq_unlock(runqueue_t
*rq
, unsigned long *flags
)
466 spin_unlock_irqrestore(&rq
->lock
, *flags
);
469 #ifdef CONFIG_SCHEDSTATS
471 * bump this up when changing the output format or the meaning of an existing
472 * format, so that tools can adapt (or abort)
474 #define SCHEDSTAT_VERSION 10
476 static int show_schedstat(struct seq_file
*seq
, void *v
)
479 enum idle_type itype
;
481 seq_printf(seq
, "version %d\n", SCHEDSTAT_VERSION
);
482 seq_printf(seq
, "timestamp %lu\n", jiffies
);
483 for_each_online_cpu(cpu
) {
484 runqueue_t
*rq
= cpu_rq(cpu
);
486 struct sched_domain
*sd
;
490 /* runqueue-specific stats */
492 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
493 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
494 cpu
, rq
->yld_both_empty
,
495 rq
->yld_act_empty
, rq
->yld_exp_empty
,
496 rq
->yld_cnt
, rq
->sched_noswitch
,
497 rq
->sched_switch
, rq
->sched_cnt
, rq
->sched_goidle
,
498 rq
->alb_cnt
, rq
->alb_gained
, rq
->alb_lost
,
500 rq
->ttwu_cnt
, rq
->ttwu_moved
, rq
->ttwu_attempts
,
501 rq
->wunt_cnt
, rq
->wunt_moved
,
502 rq
->smt_cnt
, rq
->sbe_cnt
, rq
->rq_sched_info
.cpu_time
,
503 rq
->rq_sched_info
.run_delay
, rq
->rq_sched_info
.pcnt
);
505 for (itype
= IDLE
; itype
< MAX_IDLE_TYPES
; itype
++)
506 seq_printf(seq
, " %lu %lu", rq
->pt_gained
[itype
],
508 seq_printf(seq
, "\n");
511 /* domain-specific stats */
512 for_each_domain(cpu
, sd
) {
513 char mask_str
[NR_CPUS
];
515 cpumask_scnprintf(mask_str
, NR_CPUS
, sd
->span
);
516 seq_printf(seq
, "domain%d %s", dcnt
++, mask_str
);
517 for (itype
= IDLE
; itype
< MAX_IDLE_TYPES
; itype
++) {
518 seq_printf(seq
, " %lu %lu %lu %lu %lu",
520 sd
->lb_failed
[itype
],
521 sd
->lb_imbalance
[itype
],
522 sd
->lb_nobusyq
[itype
],
523 sd
->lb_nobusyg
[itype
]);
525 seq_printf(seq
, " %lu %lu %lu %lu\n",
526 sd
->sbe_pushed
, sd
->sbe_attempts
,
527 sd
->ttwu_wake_affine
, sd
->ttwu_wake_balance
);
534 static int schedstat_open(struct inode
*inode
, struct file
*file
)
536 unsigned int size
= PAGE_SIZE
* (1 + num_online_cpus() / 32);
537 char *buf
= kmalloc(size
, GFP_KERNEL
);
543 res
= single_open(file
, show_schedstat
, NULL
);
545 m
= file
->private_data
;
553 struct file_operations proc_schedstat_operations
= {
554 .open
= schedstat_open
,
557 .release
= single_release
,
560 # define schedstat_inc(rq, field) rq->field++;
561 # define schedstat_add(rq, field, amt) rq->field += amt;
562 #else /* !CONFIG_SCHEDSTATS */
563 # define schedstat_inc(rq, field) do { } while (0);
564 # define schedstat_add(rq, field, amt) do { } while (0);
568 * rq_lock - lock a given runqueue and disable interrupts.
570 static runqueue_t
*this_rq_lock(void)
576 spin_lock(&rq
->lock
);
581 static inline void rq_unlock(runqueue_t
*rq
)
583 spin_unlock_irq(&rq
->lock
);
586 #ifdef CONFIG_SCHEDSTATS
588 * Called when a process is dequeued from the active array and given
589 * the cpu. We should note that with the exception of interactive
590 * tasks, the expired queue will become the active queue after the active
591 * queue is empty, without explicitly dequeuing and requeuing tasks in the
592 * expired queue. (Interactive tasks may be requeued directly to the
593 * active queue, thus delaying tasks in the expired queue from running;
594 * see scheduler_tick()).
596 * This function is only called from sched_info_arrive(), rather than
597 * dequeue_task(). Even though a task may be queued and dequeued multiple
598 * times as it is shuffled about, we're really interested in knowing how
599 * long it was from the *first* time it was queued to the time that it
602 static inline void sched_info_dequeued(task_t
*t
)
604 t
->sched_info
.last_queued
= 0;
608 * Called when a task finally hits the cpu. We can now calculate how
609 * long it was waiting to run. We also note when it began so that we
610 * can keep stats on how long its timeslice is.
612 static inline void sched_info_arrive(task_t
*t
)
614 unsigned long now
= jiffies
, diff
= 0;
615 struct runqueue
*rq
= task_rq(t
);
617 if (t
->sched_info
.last_queued
)
618 diff
= now
- t
->sched_info
.last_queued
;
619 sched_info_dequeued(t
);
620 t
->sched_info
.run_delay
+= diff
;
621 t
->sched_info
.last_arrival
= now
;
622 t
->sched_info
.pcnt
++;
627 rq
->rq_sched_info
.run_delay
+= diff
;
628 rq
->rq_sched_info
.pcnt
++;
632 * Called when a process is queued into either the active or expired
633 * array. The time is noted and later used to determine how long we
634 * had to wait for us to reach the cpu. Since the expired queue will
635 * become the active queue after active queue is empty, without dequeuing
636 * and requeuing any tasks, we are interested in queuing to either. It
637 * is unusual but not impossible for tasks to be dequeued and immediately
638 * requeued in the same or another array: this can happen in sched_yield(),
639 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
642 * This function is only called from enqueue_task(), but also only updates
643 * the timestamp if it is already not set. It's assumed that
644 * sched_info_dequeued() will clear that stamp when appropriate.
646 static inline void sched_info_queued(task_t
*t
)
648 if (!t
->sched_info
.last_queued
)
649 t
->sched_info
.last_queued
= jiffies
;
653 * Called when a process ceases being the active-running process, either
654 * voluntarily or involuntarily. Now we can calculate how long we ran.
656 static inline void sched_info_depart(task_t
*t
)
658 struct runqueue
*rq
= task_rq(t
);
659 unsigned long diff
= jiffies
- t
->sched_info
.last_arrival
;
661 t
->sched_info
.cpu_time
+= diff
;
664 rq
->rq_sched_info
.cpu_time
+= diff
;
668 * Called when tasks are switched involuntarily due, typically, to expiring
669 * their time slice. (This may also be called when switching to or from
670 * the idle task.) We are only called when prev != next.
672 static inline void sched_info_switch(task_t
*prev
, task_t
*next
)
674 struct runqueue
*rq
= task_rq(prev
);
677 * prev now departs the cpu. It's not interesting to record
678 * stats about how efficient we were at scheduling the idle
681 if (prev
!= rq
->idle
)
682 sched_info_depart(prev
);
684 if (next
!= rq
->idle
)
685 sched_info_arrive(next
);
688 #define sched_info_queued(t) do { } while (0)
689 #define sched_info_switch(t, next) do { } while (0)
690 #endif /* CONFIG_SCHEDSTATS */
693 * Adding/removing a task to/from a priority array:
695 static void dequeue_task(struct task_struct
*p
, prio_array_t
*array
)
698 list_del(&p
->run_list
);
699 if (list_empty(array
->queue
+ p
->prio
))
700 __clear_bit(p
->prio
, array
->bitmap
);
703 static void enqueue_task(struct task_struct
*p
, prio_array_t
*array
)
705 sched_info_queued(p
);
706 list_add_tail(&p
->run_list
, array
->queue
+ p
->prio
);
707 __set_bit(p
->prio
, array
->bitmap
);
713 * Used by the migration code - we pull tasks from the head of the
714 * remote queue so we want these tasks to show up at the head of the
717 static inline void enqueue_task_head(struct task_struct
*p
, prio_array_t
*array
)
719 list_add(&p
->run_list
, array
->queue
+ p
->prio
);
720 __set_bit(p
->prio
, array
->bitmap
);
726 * effective_prio - return the priority that is based on the static
727 * priority but is modified by bonuses/penalties.
729 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
730 * into the -5 ... 0 ... +5 bonus/penalty range.
732 * We use 25% of the full 0...39 priority range so that:
734 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
735 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
737 * Both properties are important to certain workloads.
739 static int effective_prio(task_t
*p
)
746 bonus
= CURRENT_BONUS(p
) - MAX_BONUS
/ 2;
748 prio
= p
->static_prio
- bonus
;
749 if (prio
< MAX_RT_PRIO
)
751 if (prio
> MAX_PRIO
-1)
757 * __activate_task - move a task to the runqueue.
759 static inline void __activate_task(task_t
*p
, runqueue_t
*rq
)
761 enqueue_task(p
, rq
->active
);
766 * __activate_idle_task - move idle task to the _front_ of runqueue.
768 static inline void __activate_idle_task(task_t
*p
, runqueue_t
*rq
)
770 enqueue_task_head(p
, rq
->active
);
774 static void recalc_task_prio(task_t
*p
, unsigned long long now
)
776 unsigned long long __sleep_time
= now
- p
->timestamp
;
777 unsigned long sleep_time
;
779 if (__sleep_time
> NS_MAX_SLEEP_AVG
)
780 sleep_time
= NS_MAX_SLEEP_AVG
;
782 sleep_time
= (unsigned long)__sleep_time
;
784 if (likely(sleep_time
> 0)) {
786 * User tasks that sleep a long time are categorised as
787 * idle and will get just interactive status to stay active &
788 * prevent them suddenly becoming cpu hogs and starving
791 if (p
->mm
&& p
->activated
!= -1 &&
792 sleep_time
> INTERACTIVE_SLEEP(p
)) {
793 p
->sleep_avg
= JIFFIES_TO_NS(MAX_SLEEP_AVG
-
796 p
->interactive_credit
++;
799 * The lower the sleep avg a task has the more
800 * rapidly it will rise with sleep time.
802 sleep_time
*= (MAX_BONUS
- CURRENT_BONUS(p
)) ? : 1;
805 * Tasks with low interactive_credit are limited to
806 * one timeslice worth of sleep avg bonus.
809 sleep_time
> JIFFIES_TO_NS(task_timeslice(p
)))
810 sleep_time
= JIFFIES_TO_NS(task_timeslice(p
));
813 * Non high_credit tasks waking from uninterruptible
814 * sleep are limited in their sleep_avg rise as they
815 * are likely to be cpu hogs waiting on I/O
817 if (p
->activated
== -1 && !HIGH_CREDIT(p
) && p
->mm
) {
818 if (p
->sleep_avg
>= INTERACTIVE_SLEEP(p
))
820 else if (p
->sleep_avg
+ sleep_time
>=
821 INTERACTIVE_SLEEP(p
)) {
822 p
->sleep_avg
= INTERACTIVE_SLEEP(p
);
828 * This code gives a bonus to interactive tasks.
830 * The boost works by updating the 'average sleep time'
831 * value here, based on ->timestamp. The more time a
832 * task spends sleeping, the higher the average gets -
833 * and the higher the priority boost gets as well.
835 p
->sleep_avg
+= sleep_time
;
837 if (p
->sleep_avg
> NS_MAX_SLEEP_AVG
) {
838 p
->sleep_avg
= NS_MAX_SLEEP_AVG
;
840 p
->interactive_credit
++;
845 p
->prio
= effective_prio(p
);
849 * activate_task - move a task to the runqueue and do priority recalculation
851 * Update all the scheduling statistics stuff. (sleep average
852 * calculation, priority modifiers, etc.)
854 static void activate_task(task_t
*p
, runqueue_t
*rq
, int local
)
856 unsigned long long now
;
861 /* Compensate for drifting sched_clock */
862 runqueue_t
*this_rq
= this_rq();
863 now
= (now
- this_rq
->timestamp_last_tick
)
864 + rq
->timestamp_last_tick
;
868 recalc_task_prio(p
, now
);
871 * This checks to make sure it's not an uninterruptible task
872 * that is now waking up.
876 * Tasks which were woken up by interrupts (ie. hw events)
877 * are most likely of interactive nature. So we give them
878 * the credit of extending their sleep time to the period
879 * of time they spend on the runqueue, waiting for execution
880 * on a CPU, first time around:
886 * Normal first-time wakeups get a credit too for
887 * on-runqueue time, but it will be weighted down:
894 __activate_task(p
, rq
);
898 * deactivate_task - remove a task from the runqueue.
900 static void deactivate_task(struct task_struct
*p
, runqueue_t
*rq
)
903 if (p
->state
== TASK_UNINTERRUPTIBLE
)
904 rq
->nr_uninterruptible
++;
905 dequeue_task(p
, p
->array
);
910 * resched_task - mark a task 'to be rescheduled now'.
912 * On UP this means the setting of the need_resched flag, on SMP it
913 * might also involve a cross-CPU call to trigger the scheduler on
917 static void resched_task(task_t
*p
)
919 int need_resched
, nrpolling
;
921 BUG_ON(!spin_is_locked(&task_rq(p
)->lock
));
923 /* minimise the chance of sending an interrupt to poll_idle() */
924 nrpolling
= test_tsk_thread_flag(p
,TIF_POLLING_NRFLAG
);
925 need_resched
= test_and_set_tsk_thread_flag(p
,TIF_NEED_RESCHED
);
926 nrpolling
|= test_tsk_thread_flag(p
,TIF_POLLING_NRFLAG
);
928 if (!need_resched
&& !nrpolling
&& (task_cpu(p
) != smp_processor_id()))
929 smp_send_reschedule(task_cpu(p
));
932 static inline void resched_task(task_t
*p
)
934 set_tsk_need_resched(p
);
939 * task_curr - is this task currently executing on a CPU?
940 * @p: the task in question.
942 inline int task_curr(const task_t
*p
)
944 return cpu_curr(task_cpu(p
)) == p
;
954 struct list_head list
;
955 enum request_type type
;
957 /* For REQ_MOVE_TASK */
961 /* For REQ_SET_DOMAIN */
962 struct sched_domain
*sd
;
964 struct completion done
;
968 * The task's runqueue lock must be held.
969 * Returns true if you have to wait for migration thread.
971 static int migrate_task(task_t
*p
, int dest_cpu
, migration_req_t
*req
)
973 runqueue_t
*rq
= task_rq(p
);
976 * If the task is not on a runqueue (and not running), then
977 * it is sufficient to simply update the task's cpu field.
979 if (!p
->array
&& !task_running(rq
, p
)) {
980 set_task_cpu(p
, dest_cpu
);
984 init_completion(&req
->done
);
985 req
->type
= REQ_MOVE_TASK
;
987 req
->dest_cpu
= dest_cpu
;
988 list_add(&req
->list
, &rq
->migration_queue
);
993 * wait_task_inactive - wait for a thread to unschedule.
995 * The caller must ensure that the task *will* unschedule sometime soon,
996 * else this function might spin for a *long* time. This function can't
997 * be called with interrupts off, or it may introduce deadlock with
998 * smp_call_function() if an IPI is sent by the same process we are
999 * waiting to become inactive.
1001 void wait_task_inactive(task_t
* p
)
1003 unsigned long flags
;
1008 rq
= task_rq_lock(p
, &flags
);
1009 /* Must be off runqueue entirely, not preempted. */
1010 if (unlikely(p
->array
)) {
1011 /* If it's preempted, we yield. It could be a while. */
1012 preempted
= !task_running(rq
, p
);
1013 task_rq_unlock(rq
, &flags
);
1019 task_rq_unlock(rq
, &flags
);
1023 * kick_process - kick a running thread to enter/exit the kernel
1024 * @p: the to-be-kicked thread
1026 * Cause a process which is running on another CPU to enter
1027 * kernel-mode, without any delay. (to get signals handled.)
1029 void kick_process(task_t
*p
)
1035 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1036 smp_send_reschedule(cpu
);
1040 EXPORT_SYMBOL_GPL(kick_process
);
1043 * Return a low guess at the load of a migration-source cpu.
1045 * We want to under-estimate the load of migration sources, to
1046 * balance conservatively.
1048 static inline unsigned long source_load(int cpu
)
1050 runqueue_t
*rq
= cpu_rq(cpu
);
1051 unsigned long load_now
= rq
->nr_running
* SCHED_LOAD_SCALE
;
1053 return min(rq
->cpu_load
, load_now
);
1057 * Return a high guess at the load of a migration-target cpu
1059 static inline unsigned long target_load(int cpu
)
1061 runqueue_t
*rq
= cpu_rq(cpu
);
1062 unsigned long load_now
= rq
->nr_running
* SCHED_LOAD_SCALE
;
1064 return max(rq
->cpu_load
, load_now
);
1070 * wake_idle() is useful especially on SMT architectures to wake a
1071 * task onto an idle sibling if we would otherwise wake it onto a
1074 * Returns the CPU we should wake onto.
1076 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1077 static int wake_idle(int cpu
, task_t
*p
)
1080 runqueue_t
*rq
= cpu_rq(cpu
);
1081 struct sched_domain
*sd
;
1088 if (!(sd
->flags
& SD_WAKE_IDLE
))
1091 cpus_and(tmp
, sd
->span
, cpu_online_map
);
1092 cpus_and(tmp
, tmp
, p
->cpus_allowed
);
1094 for_each_cpu_mask(i
, tmp
) {
1102 static inline int wake_idle(int cpu
, task_t
*p
)
1109 * try_to_wake_up - wake up a thread
1110 * @p: the to-be-woken-up thread
1111 * @state: the mask of task states that can be woken
1112 * @sync: do a synchronous wakeup?
1114 * Put it on the run-queue if it's not already there. The "current"
1115 * thread is always on the run-queue (except when the actual
1116 * re-schedule is in progress), and as such you're allowed to do
1117 * the simpler "current->state = TASK_RUNNING" to mark yourself
1118 * runnable without the overhead of this.
1120 * returns failure only if the task is already active.
1122 static int try_to_wake_up(task_t
* p
, unsigned int state
, int sync
)
1124 int cpu
, this_cpu
, success
= 0;
1125 unsigned long flags
;
1129 unsigned long load
, this_load
;
1130 struct sched_domain
*sd
;
1134 rq
= task_rq_lock(p
, &flags
);
1135 schedstat_inc(rq
, ttwu_cnt
);
1136 old_state
= p
->state
;
1137 if (!(old_state
& state
))
1144 this_cpu
= smp_processor_id();
1147 if (unlikely(task_running(rq
, p
)))
1152 if (cpu
== this_cpu
|| unlikely(!cpu_isset(this_cpu
, p
->cpus_allowed
)))
1155 load
= source_load(cpu
);
1156 this_load
= target_load(this_cpu
);
1159 * If sync wakeup then subtract the (maximum possible) effect of
1160 * the currently running task from the load of the current CPU:
1163 this_load
-= SCHED_LOAD_SCALE
;
1165 /* Don't pull the task off an idle CPU to a busy one */
1166 if (load
< SCHED_LOAD_SCALE
/2 && this_load
> SCHED_LOAD_SCALE
/2)
1169 new_cpu
= this_cpu
; /* Wake to this CPU if we can */
1172 * Scan domains for affine wakeup and passive balancing
1175 for_each_domain(this_cpu
, sd
) {
1176 unsigned int imbalance
;
1178 * Start passive balancing when half the imbalance_pct
1181 imbalance
= sd
->imbalance_pct
+ (sd
->imbalance_pct
- 100) / 2;
1183 if ((sd
->flags
& SD_WAKE_AFFINE
) &&
1184 !task_hot(p
, rq
->timestamp_last_tick
, sd
)) {
1186 * This domain has SD_WAKE_AFFINE and p is cache cold
1189 if (cpu_isset(cpu
, sd
->span
)) {
1190 schedstat_inc(sd
, ttwu_wake_affine
);
1193 } else if ((sd
->flags
& SD_WAKE_BALANCE
) &&
1194 imbalance
*this_load
<= 100*load
) {
1196 * This domain has SD_WAKE_BALANCE and there is
1199 if (cpu_isset(cpu
, sd
->span
)) {
1200 schedstat_inc(sd
, ttwu_wake_balance
);
1206 new_cpu
= cpu
; /* Could not wake to this_cpu. Wake to cpu instead */
1208 schedstat_inc(rq
, ttwu_attempts
);
1209 new_cpu
= wake_idle(new_cpu
, p
);
1210 if (new_cpu
!= cpu
&& cpu_isset(new_cpu
, p
->cpus_allowed
)) {
1211 schedstat_inc(rq
, ttwu_moved
);
1212 set_task_cpu(p
, new_cpu
);
1213 task_rq_unlock(rq
, &flags
);
1214 /* might preempt at this point */
1215 rq
= task_rq_lock(p
, &flags
);
1216 old_state
= p
->state
;
1217 if (!(old_state
& state
))
1222 this_cpu
= smp_processor_id();
1227 #endif /* CONFIG_SMP */
1228 if (old_state
== TASK_UNINTERRUPTIBLE
) {
1229 rq
->nr_uninterruptible
--;
1231 * Tasks on involuntary sleep don't earn
1232 * sleep_avg beyond just interactive state.
1238 * Sync wakeups (i.e. those types of wakeups where the waker
1239 * has indicated that it will leave the CPU in short order)
1240 * don't trigger a preemption, if the woken up task will run on
1241 * this cpu. (in this case the 'I will reschedule' promise of
1242 * the waker guarantees that the freshly woken up task is going
1243 * to be considered on this CPU.)
1245 activate_task(p
, rq
, cpu
== this_cpu
);
1246 if (!sync
|| cpu
!= this_cpu
) {
1247 if (TASK_PREEMPTS_CURR(p
, rq
))
1248 resched_task(rq
->curr
);
1253 p
->state
= TASK_RUNNING
;
1255 task_rq_unlock(rq
, &flags
);
1260 int fastcall
wake_up_process(task_t
* p
)
1262 return try_to_wake_up(p
, TASK_STOPPED
| TASK_TRACED
|
1263 TASK_INTERRUPTIBLE
| TASK_UNINTERRUPTIBLE
, 0);
1266 EXPORT_SYMBOL(wake_up_process
);
1268 int fastcall
wake_up_state(task_t
*p
, unsigned int state
)
1270 return try_to_wake_up(p
, state
, 0);
1274 static int find_idlest_cpu(struct task_struct
*p
, int this_cpu
,
1275 struct sched_domain
*sd
);
1279 * Perform scheduler related setup for a newly forked process p.
1280 * p is forked by current.
1282 void fastcall
sched_fork(task_t
*p
)
1285 * We mark the process as running here, but have not actually
1286 * inserted it onto the runqueue yet. This guarantees that
1287 * nobody will actually run it, and a signal or other external
1288 * event cannot wake it up and insert it on the runqueue either.
1290 p
->state
= TASK_RUNNING
;
1291 INIT_LIST_HEAD(&p
->run_list
);
1293 spin_lock_init(&p
->switch_lock
);
1294 #ifdef CONFIG_SCHEDSTATS
1295 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1297 #ifdef CONFIG_PREEMPT
1299 * During context-switch we hold precisely one spinlock, which
1300 * schedule_tail drops. (in the common case it's this_rq()->lock,
1301 * but it also can be p->switch_lock.) So we compensate with a count
1302 * of 1. Also, we want to start with kernel preemption disabled.
1304 p
->thread_info
->preempt_count
= 1;
1307 * Share the timeslice between parent and child, thus the
1308 * total amount of pending timeslices in the system doesn't change,
1309 * resulting in more scheduling fairness.
1311 local_irq_disable();
1312 p
->time_slice
= (current
->time_slice
+ 1) >> 1;
1314 * The remainder of the first timeslice might be recovered by
1315 * the parent if the child exits early enough.
1317 p
->first_time_slice
= 1;
1318 current
->time_slice
>>= 1;
1319 p
->timestamp
= sched_clock();
1320 if (unlikely(!current
->time_slice
)) {
1322 * This case is rare, it happens when the parent has only
1323 * a single jiffy left from its timeslice. Taking the
1324 * runqueue lock is not a problem.
1326 current
->time_slice
= 1;
1328 scheduler_tick(0, 0);
1336 * wake_up_new_task - wake up a newly created task for the first time.
1338 * This function will do some initial scheduler statistics housekeeping
1339 * that must be done for every newly created context, then puts the task
1340 * on the runqueue and wakes it.
1342 void fastcall
wake_up_new_task(task_t
* p
, unsigned long clone_flags
)
1344 unsigned long flags
;
1346 runqueue_t
*rq
, *this_rq
;
1348 rq
= task_rq_lock(p
, &flags
);
1350 this_cpu
= smp_processor_id();
1352 BUG_ON(p
->state
!= TASK_RUNNING
);
1354 schedstat_inc(rq
, wunt_cnt
);
1356 * We decrease the sleep average of forking parents
1357 * and children as well, to keep max-interactive tasks
1358 * from forking tasks that are max-interactive. The parent
1359 * (current) is done further down, under its lock.
1361 p
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(p
) *
1362 CHILD_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1364 p
->interactive_credit
= 0;
1366 p
->prio
= effective_prio(p
);
1368 if (likely(cpu
== this_cpu
)) {
1369 if (!(clone_flags
& CLONE_VM
)) {
1371 * The VM isn't cloned, so we're in a good position to
1372 * do child-runs-first in anticipation of an exec. This
1373 * usually avoids a lot of COW overhead.
1375 if (unlikely(!current
->array
))
1376 __activate_task(p
, rq
);
1378 p
->prio
= current
->prio
;
1379 list_add_tail(&p
->run_list
, ¤t
->run_list
);
1380 p
->array
= current
->array
;
1381 p
->array
->nr_active
++;
1386 /* Run child last */
1387 __activate_task(p
, rq
);
1389 * We skip the following code due to cpu == this_cpu
1391 * task_rq_unlock(rq, &flags);
1392 * this_rq = task_rq_lock(current, &flags);
1396 this_rq
= cpu_rq(this_cpu
);
1399 * Not the local CPU - must adjust timestamp. This should
1400 * get optimised away in the !CONFIG_SMP case.
1402 p
->timestamp
= (p
->timestamp
- this_rq
->timestamp_last_tick
)
1403 + rq
->timestamp_last_tick
;
1404 __activate_task(p
, rq
);
1405 if (TASK_PREEMPTS_CURR(p
, rq
))
1406 resched_task(rq
->curr
);
1408 schedstat_inc(rq
, wunt_moved
);
1410 * Parent and child are on different CPUs, now get the
1411 * parent runqueue to update the parent's ->sleep_avg:
1413 task_rq_unlock(rq
, &flags
);
1414 this_rq
= task_rq_lock(current
, &flags
);
1416 current
->sleep_avg
= JIFFIES_TO_NS(CURRENT_BONUS(current
) *
1417 PARENT_PENALTY
/ 100 * MAX_SLEEP_AVG
/ MAX_BONUS
);
1418 task_rq_unlock(this_rq
, &flags
);
1422 * Potentially available exiting-child timeslices are
1423 * retrieved here - this way the parent does not get
1424 * penalized for creating too many threads.
1426 * (this cannot be used to 'generate' timeslices
1427 * artificially, because any timeslice recovered here
1428 * was given away by the parent in the first place.)
1430 void fastcall
sched_exit(task_t
* p
)
1432 unsigned long flags
;
1436 * If the child was a (relative-) CPU hog then decrease
1437 * the sleep_avg of the parent as well.
1439 rq
= task_rq_lock(p
->parent
, &flags
);
1440 if (p
->first_time_slice
) {
1441 p
->parent
->time_slice
+= p
->time_slice
;
1442 if (unlikely(p
->parent
->time_slice
> task_timeslice(p
)))
1443 p
->parent
->time_slice
= task_timeslice(p
);
1445 if (p
->sleep_avg
< p
->parent
->sleep_avg
)
1446 p
->parent
->sleep_avg
= p
->parent
->sleep_avg
/
1447 (EXIT_WEIGHT
+ 1) * EXIT_WEIGHT
+ p
->sleep_avg
/
1449 task_rq_unlock(rq
, &flags
);
1453 * finish_task_switch - clean up after a task-switch
1454 * @prev: the thread we just switched away from.
1456 * We enter this with the runqueue still locked, and finish_arch_switch()
1457 * will unlock it along with doing any other architecture-specific cleanup
1460 * Note that we may have delayed dropping an mm in context_switch(). If
1461 * so, we finish that here outside of the runqueue lock. (Doing it
1462 * with the lock held can cause deadlocks; see schedule() for
1465 static void finish_task_switch(task_t
*prev
)
1467 runqueue_t
*rq
= this_rq();
1468 struct mm_struct
*mm
= rq
->prev_mm
;
1469 unsigned long prev_task_flags
;
1474 * A task struct has one reference for the use as "current".
1475 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1476 * schedule one last time. The schedule call will never return,
1477 * and the scheduled task must drop that reference.
1478 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1479 * still held, otherwise prev could be scheduled on another cpu, die
1480 * there before we look at prev->state, and then the reference would
1482 * Manfred Spraul <manfred@colorfullife.com>
1484 prev_task_flags
= prev
->flags
;
1485 finish_arch_switch(rq
, prev
);
1488 if (unlikely(prev_task_flags
& PF_DEAD
))
1489 put_task_struct(prev
);
1493 * schedule_tail - first thing a freshly forked thread must call.
1494 * @prev: the thread we just switched away from.
1496 asmlinkage
void schedule_tail(task_t
*prev
)
1498 finish_task_switch(prev
);
1500 if (current
->set_child_tid
)
1501 put_user(current
->pid
, current
->set_child_tid
);
1505 * context_switch - switch to the new MM and the new
1506 * thread's register state.
1509 task_t
* context_switch(runqueue_t
*rq
, task_t
*prev
, task_t
*next
)
1511 struct mm_struct
*mm
= next
->mm
;
1512 struct mm_struct
*oldmm
= prev
->active_mm
;
1514 if (unlikely(!mm
)) {
1515 next
->active_mm
= oldmm
;
1516 atomic_inc(&oldmm
->mm_count
);
1517 enter_lazy_tlb(oldmm
, next
);
1519 switch_mm(oldmm
, mm
, next
);
1521 if (unlikely(!prev
->mm
)) {
1522 prev
->active_mm
= NULL
;
1523 WARN_ON(rq
->prev_mm
);
1524 rq
->prev_mm
= oldmm
;
1527 /* Here we just switch the register state and the stack. */
1528 switch_to(prev
, next
, prev
);
1534 * nr_running, nr_uninterruptible and nr_context_switches:
1536 * externally visible scheduler statistics: current number of runnable
1537 * threads, current number of uninterruptible-sleeping threads, total
1538 * number of context switches performed since bootup.
1540 unsigned long nr_running(void)
1542 unsigned long i
, sum
= 0;
1544 for_each_online_cpu(i
)
1545 sum
+= cpu_rq(i
)->nr_running
;
1550 unsigned long nr_uninterruptible(void)
1552 unsigned long i
, sum
= 0;
1555 sum
+= cpu_rq(i
)->nr_uninterruptible
;
1560 unsigned long long nr_context_switches(void)
1562 unsigned long long i
, sum
= 0;
1565 sum
+= cpu_rq(i
)->nr_switches
;
1570 unsigned long nr_iowait(void)
1572 unsigned long i
, sum
= 0;
1575 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
1583 * double_rq_lock - safely lock two runqueues
1585 * Note this does not disable interrupts like task_rq_lock,
1586 * you need to do so manually before calling.
1588 static void double_rq_lock(runqueue_t
*rq1
, runqueue_t
*rq2
)
1591 spin_lock(&rq1
->lock
);
1594 spin_lock(&rq1
->lock
);
1595 spin_lock(&rq2
->lock
);
1597 spin_lock(&rq2
->lock
);
1598 spin_lock(&rq1
->lock
);
1604 * double_rq_unlock - safely unlock two runqueues
1606 * Note this does not restore interrupts like task_rq_unlock,
1607 * you need to do so manually after calling.
1609 static void double_rq_unlock(runqueue_t
*rq1
, runqueue_t
*rq2
)
1611 spin_unlock(&rq1
->lock
);
1613 spin_unlock(&rq2
->lock
);
1617 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1619 static void double_lock_balance(runqueue_t
*this_rq
, runqueue_t
*busiest
)
1621 if (unlikely(!spin_trylock(&busiest
->lock
))) {
1622 if (busiest
< this_rq
) {
1623 spin_unlock(&this_rq
->lock
);
1624 spin_lock(&busiest
->lock
);
1625 spin_lock(&this_rq
->lock
);
1627 spin_lock(&busiest
->lock
);
1632 * find_idlest_cpu - find the least busy runqueue.
1634 static int find_idlest_cpu(struct task_struct
*p
, int this_cpu
,
1635 struct sched_domain
*sd
)
1637 unsigned long load
, min_load
, this_load
;
1642 min_load
= ULONG_MAX
;
1644 cpus_and(mask
, sd
->span
, cpu_online_map
);
1645 cpus_and(mask
, mask
, p
->cpus_allowed
);
1647 for_each_cpu_mask(i
, mask
) {
1648 load
= target_load(i
);
1650 if (load
< min_load
) {
1654 /* break out early on an idle CPU: */
1660 /* add +1 to account for the new task */
1661 this_load
= source_load(this_cpu
) + SCHED_LOAD_SCALE
;
1664 * Would with the addition of the new task to the
1665 * current CPU there be an imbalance between this
1666 * CPU and the idlest CPU?
1668 * Use half of the balancing threshold - new-context is
1669 * a good opportunity to balance.
1671 if (min_load
*(100 + (sd
->imbalance_pct
-100)/2) < this_load
*100)
1678 * If dest_cpu is allowed for this process, migrate the task to it.
1679 * This is accomplished by forcing the cpu_allowed mask to only
1680 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1681 * the cpu_allowed mask is restored.
1683 static void sched_migrate_task(task_t
*p
, int dest_cpu
)
1685 migration_req_t req
;
1687 unsigned long flags
;
1689 rq
= task_rq_lock(p
, &flags
);
1690 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
1691 || unlikely(cpu_is_offline(dest_cpu
)))
1694 schedstat_inc(rq
, smt_cnt
);
1695 /* force the process onto the specified CPU */
1696 if (migrate_task(p
, dest_cpu
, &req
)) {
1697 /* Need to wait for migration thread (might exit: take ref). */
1698 struct task_struct
*mt
= rq
->migration_thread
;
1699 get_task_struct(mt
);
1700 task_rq_unlock(rq
, &flags
);
1701 wake_up_process(mt
);
1702 put_task_struct(mt
);
1703 wait_for_completion(&req
.done
);
1707 task_rq_unlock(rq
, &flags
);
1711 * sched_exec(): find the highest-level, exec-balance-capable
1712 * domain and try to migrate the task to the least loaded CPU.
1714 * execve() is a valuable balancing opportunity, because at this point
1715 * the task has the smallest effective memory and cache footprint.
1717 void sched_exec(void)
1719 struct sched_domain
*tmp
, *sd
= NULL
;
1720 int new_cpu
, this_cpu
= get_cpu();
1722 schedstat_inc(this_rq(), sbe_cnt
);
1723 /* Prefer the current CPU if there's only this task running */
1724 if (this_rq()->nr_running
<= 1)
1727 for_each_domain(this_cpu
, tmp
)
1728 if (tmp
->flags
& SD_BALANCE_EXEC
)
1732 schedstat_inc(sd
, sbe_attempts
);
1733 new_cpu
= find_idlest_cpu(current
, this_cpu
, sd
);
1734 if (new_cpu
!= this_cpu
) {
1735 schedstat_inc(sd
, sbe_pushed
);
1737 sched_migrate_task(current
, new_cpu
);
1746 * pull_task - move a task from a remote runqueue to the local runqueue.
1747 * Both runqueues must be locked.
1750 void pull_task(runqueue_t
*src_rq
, prio_array_t
*src_array
, task_t
*p
,
1751 runqueue_t
*this_rq
, prio_array_t
*this_array
, int this_cpu
)
1753 dequeue_task(p
, src_array
);
1754 src_rq
->nr_running
--;
1755 set_task_cpu(p
, this_cpu
);
1756 this_rq
->nr_running
++;
1757 enqueue_task(p
, this_array
);
1758 p
->timestamp
= (p
->timestamp
- src_rq
->timestamp_last_tick
)
1759 + this_rq
->timestamp_last_tick
;
1761 * Note that idle threads have a prio of MAX_PRIO, for this test
1762 * to be always true for them.
1764 if (TASK_PREEMPTS_CURR(p
, this_rq
))
1765 resched_task(this_rq
->curr
);
1769 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1772 int can_migrate_task(task_t
*p
, runqueue_t
*rq
, int this_cpu
,
1773 struct sched_domain
*sd
, enum idle_type idle
)
1776 * We do not migrate tasks that are:
1777 * 1) running (obviously), or
1778 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1779 * 3) are cache-hot on their current CPU.
1781 if (task_running(rq
, p
))
1783 if (!cpu_isset(this_cpu
, p
->cpus_allowed
))
1786 /* Aggressive migration if we've failed balancing */
1787 if (idle
== NEWLY_IDLE
||
1788 sd
->nr_balance_failed
< sd
->cache_nice_tries
) {
1789 if (task_hot(p
, rq
->timestamp_last_tick
, sd
))
1797 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1798 * as part of a balancing operation within "domain". Returns the number of
1801 * Called with both runqueues locked.
1803 static int move_tasks(runqueue_t
*this_rq
, int this_cpu
, runqueue_t
*busiest
,
1804 unsigned long max_nr_move
, struct sched_domain
*sd
,
1805 enum idle_type idle
)
1807 prio_array_t
*array
, *dst_array
;
1808 struct list_head
*head
, *curr
;
1809 int idx
, pulled
= 0;
1812 if (max_nr_move
<= 0 || busiest
->nr_running
<= 1)
1816 * We first consider expired tasks. Those will likely not be
1817 * executed in the near future, and they are most likely to
1818 * be cache-cold, thus switching CPUs has the least effect
1821 if (busiest
->expired
->nr_active
) {
1822 array
= busiest
->expired
;
1823 dst_array
= this_rq
->expired
;
1825 array
= busiest
->active
;
1826 dst_array
= this_rq
->active
;
1830 /* Start searching at priority 0: */
1834 idx
= sched_find_first_bit(array
->bitmap
);
1836 idx
= find_next_bit(array
->bitmap
, MAX_PRIO
, idx
);
1837 if (idx
>= MAX_PRIO
) {
1838 if (array
== busiest
->expired
&& busiest
->active
->nr_active
) {
1839 array
= busiest
->active
;
1840 dst_array
= this_rq
->active
;
1846 head
= array
->queue
+ idx
;
1849 tmp
= list_entry(curr
, task_t
, run_list
);
1853 if (!can_migrate_task(tmp
, busiest
, this_cpu
, sd
, idle
)) {
1861 * Right now, this is the only place pull_task() is called,
1862 * so we can safely collect pull_task() stats here rather than
1863 * inside pull_task().
1865 schedstat_inc(this_rq
, pt_gained
[idle
]);
1866 schedstat_inc(busiest
, pt_lost
[idle
]);
1868 pull_task(busiest
, array
, tmp
, this_rq
, dst_array
, this_cpu
);
1871 /* We only want to steal up to the prescribed number of tasks. */
1872 if (pulled
< max_nr_move
) {
1883 * find_busiest_group finds and returns the busiest CPU group within the
1884 * domain. It calculates and returns the number of tasks which should be
1885 * moved to restore balance via the imbalance parameter.
1887 static struct sched_group
*
1888 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
1889 unsigned long *imbalance
, enum idle_type idle
)
1891 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1892 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
1894 max_load
= this_load
= total_load
= total_pwr
= 0;
1902 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1904 /* Tally up the load of all CPUs in the group */
1906 cpus_and(tmp
, group
->cpumask
, cpu_online_map
);
1907 if (unlikely(cpus_empty(tmp
)))
1910 for_each_cpu_mask(i
, tmp
) {
1911 /* Bias balancing toward cpus of our domain */
1913 load
= target_load(i
);
1915 load
= source_load(i
);
1924 total_load
+= avg_load
;
1925 total_pwr
+= group
->cpu_power
;
1927 /* Adjust by relative CPU power of the group */
1928 avg_load
= (avg_load
* SCHED_LOAD_SCALE
) / group
->cpu_power
;
1931 this_load
= avg_load
;
1934 } else if (avg_load
> max_load
) {
1935 max_load
= avg_load
;
1939 group
= group
->next
;
1940 } while (group
!= sd
->groups
);
1942 if (!busiest
|| this_load
>= max_load
)
1945 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
1947 if (this_load
>= avg_load
||
1948 100*max_load
<= sd
->imbalance_pct
*this_load
)
1952 * We're trying to get all the cpus to the average_load, so we don't
1953 * want to push ourselves above the average load, nor do we wish to
1954 * reduce the max loaded cpu below the average load, as either of these
1955 * actions would just result in more rebalancing later, and ping-pong
1956 * tasks around. Thus we look for the minimum possible imbalance.
1957 * Negative imbalances (*we* are more loaded than anyone else) will
1958 * be counted as no imbalance for these purposes -- we can't fix that
1959 * by pulling tasks to us. Be careful of negative numbers as they'll
1960 * appear as very large values with unsigned longs.
1962 *imbalance
= min(max_load
- avg_load
, avg_load
- this_load
);
1964 /* How much load to actually move to equalise the imbalance */
1965 *imbalance
= (*imbalance
* min(busiest
->cpu_power
, this->cpu_power
))
1968 if (*imbalance
< SCHED_LOAD_SCALE
- 1) {
1969 unsigned long pwr_now
= 0, pwr_move
= 0;
1972 if (max_load
- this_load
>= SCHED_LOAD_SCALE
*2) {
1978 * OK, we don't have enough imbalance to justify moving tasks,
1979 * however we may be able to increase total CPU power used by
1983 pwr_now
+= busiest
->cpu_power
*min(SCHED_LOAD_SCALE
, max_load
);
1984 pwr_now
+= this->cpu_power
*min(SCHED_LOAD_SCALE
, this_load
);
1985 pwr_now
/= SCHED_LOAD_SCALE
;
1987 /* Amount of load we'd subtract */
1988 tmp
= SCHED_LOAD_SCALE
*SCHED_LOAD_SCALE
/busiest
->cpu_power
;
1990 pwr_move
+= busiest
->cpu_power
*min(SCHED_LOAD_SCALE
,
1993 /* Amount of load we'd add */
1994 tmp
= SCHED_LOAD_SCALE
*SCHED_LOAD_SCALE
/this->cpu_power
;
1997 pwr_move
+= this->cpu_power
*min(SCHED_LOAD_SCALE
, this_load
+ tmp
);
1998 pwr_move
/= SCHED_LOAD_SCALE
;
2000 /* Move if we gain another 8th of a CPU worth of throughput */
2001 if (pwr_move
< pwr_now
+ SCHED_LOAD_SCALE
/ 8)
2008 /* Get rid of the scaling factor, rounding down as we divide */
2009 *imbalance
= (*imbalance
+ 1) / SCHED_LOAD_SCALE
;
2014 if (busiest
&& (idle
== NEWLY_IDLE
||
2015 (idle
== IDLE
&& max_load
> SCHED_LOAD_SCALE
)) ) {
2025 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2027 static runqueue_t
*find_busiest_queue(struct sched_group
*group
)
2030 unsigned long load
, max_load
= 0;
2031 runqueue_t
*busiest
= NULL
;
2034 cpus_and(tmp
, group
->cpumask
, cpu_online_map
);
2035 for_each_cpu_mask(i
, tmp
) {
2036 load
= source_load(i
);
2038 if (load
> max_load
) {
2040 busiest
= cpu_rq(i
);
2048 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2049 * tasks if there is an imbalance.
2051 * Called with this_rq unlocked.
2053 static int load_balance(int this_cpu
, runqueue_t
*this_rq
,
2054 struct sched_domain
*sd
, enum idle_type idle
)
2056 struct sched_group
*group
;
2057 runqueue_t
*busiest
;
2058 unsigned long imbalance
;
2061 spin_lock(&this_rq
->lock
);
2062 schedstat_inc(sd
, lb_cnt
[idle
]);
2064 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
);
2066 schedstat_inc(sd
, lb_nobusyg
[idle
]);
2070 busiest
= find_busiest_queue(group
);
2072 schedstat_inc(sd
, lb_nobusyq
[idle
]);
2077 * This should be "impossible", but since load
2078 * balancing is inherently racy and statistical,
2079 * it could happen in theory.
2081 if (unlikely(busiest
== this_rq
)) {
2086 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
2089 if (busiest
->nr_running
> 1) {
2091 * Attempt to move tasks. If find_busiest_group has found
2092 * an imbalance but busiest->nr_running <= 1, the group is
2093 * still unbalanced. nr_moved simply stays zero, so it is
2094 * correctly treated as an imbalance.
2096 double_lock_balance(this_rq
, busiest
);
2097 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2098 imbalance
, sd
, idle
);
2099 spin_unlock(&busiest
->lock
);
2101 spin_unlock(&this_rq
->lock
);
2104 schedstat_inc(sd
, lb_failed
[idle
]);
2105 sd
->nr_balance_failed
++;
2107 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
2110 spin_lock(&busiest
->lock
);
2111 if (!busiest
->active_balance
) {
2112 busiest
->active_balance
= 1;
2113 busiest
->push_cpu
= this_cpu
;
2116 spin_unlock(&busiest
->lock
);
2118 wake_up_process(busiest
->migration_thread
);
2121 * We've kicked active balancing, reset the failure
2124 sd
->nr_balance_failed
= sd
->cache_nice_tries
;
2127 sd
->nr_balance_failed
= 0;
2129 /* We were unbalanced, so reset the balancing interval */
2130 sd
->balance_interval
= sd
->min_interval
;
2135 spin_unlock(&this_rq
->lock
);
2137 /* tune up the balancing interval */
2138 if (sd
->balance_interval
< sd
->max_interval
)
2139 sd
->balance_interval
*= 2;
2145 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2146 * tasks if there is an imbalance.
2148 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2149 * this_rq is locked.
2151 static int load_balance_newidle(int this_cpu
, runqueue_t
*this_rq
,
2152 struct sched_domain
*sd
)
2154 struct sched_group
*group
;
2155 runqueue_t
*busiest
= NULL
;
2156 unsigned long imbalance
;
2159 schedstat_inc(sd
, lb_cnt
[NEWLY_IDLE
]);
2160 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, NEWLY_IDLE
);
2162 schedstat_inc(sd
, lb_nobusyg
[NEWLY_IDLE
]);
2166 busiest
= find_busiest_queue(group
);
2167 if (!busiest
|| busiest
== this_rq
) {
2168 schedstat_inc(sd
, lb_nobusyq
[NEWLY_IDLE
]);
2172 /* Attempt to move tasks */
2173 double_lock_balance(this_rq
, busiest
);
2175 schedstat_add(sd
, lb_imbalance
[NEWLY_IDLE
], imbalance
);
2176 nr_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2177 imbalance
, sd
, NEWLY_IDLE
);
2179 schedstat_inc(sd
, lb_failed
[NEWLY_IDLE
]);
2181 spin_unlock(&busiest
->lock
);
2188 * idle_balance is called by schedule() if this_cpu is about to become
2189 * idle. Attempts to pull tasks from other CPUs.
2191 static inline void idle_balance(int this_cpu
, runqueue_t
*this_rq
)
2193 struct sched_domain
*sd
;
2195 for_each_domain(this_cpu
, sd
) {
2196 if (sd
->flags
& SD_BALANCE_NEWIDLE
) {
2197 if (load_balance_newidle(this_cpu
, this_rq
, sd
)) {
2198 /* We've pulled tasks over so stop searching */
2206 * active_load_balance is run by migration threads. It pushes a running
2207 * task off the cpu. It can be required to correctly have at least 1 task
2208 * running on each physical CPU where possible, and not have a physical /
2209 * logical imbalance.
2211 * Called with busiest locked.
2213 static void active_load_balance(runqueue_t
*busiest
, int busiest_cpu
)
2215 struct sched_domain
*sd
;
2216 struct sched_group
*group
, *busy_group
;
2219 schedstat_inc(busiest
, alb_cnt
);
2220 if (busiest
->nr_running
<= 1)
2223 for_each_domain(busiest_cpu
, sd
)
2224 if (cpu_isset(busiest
->push_cpu
, sd
->span
))
2230 while (!cpu_isset(busiest_cpu
, group
->cpumask
))
2231 group
= group
->next
;
2240 if (group
== busy_group
)
2243 cpus_and(tmp
, group
->cpumask
, cpu_online_map
);
2244 if (!cpus_weight(tmp
))
2247 for_each_cpu_mask(i
, tmp
) {
2253 rq
= cpu_rq(push_cpu
);
2256 * This condition is "impossible", but since load
2257 * balancing is inherently a bit racy and statistical,
2258 * it can trigger.. Reported by Bjorn Helgaas on a
2261 if (unlikely(busiest
== rq
))
2263 double_lock_balance(busiest
, rq
);
2264 if (move_tasks(rq
, push_cpu
, busiest
, 1, sd
, IDLE
)) {
2265 schedstat_inc(busiest
, alb_lost
);
2266 schedstat_inc(rq
, alb_gained
);
2268 schedstat_inc(busiest
, alb_failed
);
2270 spin_unlock(&rq
->lock
);
2272 group
= group
->next
;
2273 } while (group
!= sd
->groups
);
2277 * rebalance_tick will get called every timer tick, on every CPU.
2279 * It checks each scheduling domain to see if it is due to be balanced,
2280 * and initiates a balancing operation if so.
2282 * Balancing parameters are set up in arch_init_sched_domains.
2285 /* Don't have all balancing operations going off at once */
2286 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2288 static void rebalance_tick(int this_cpu
, runqueue_t
*this_rq
,
2289 enum idle_type idle
)
2291 unsigned long old_load
, this_load
;
2292 unsigned long j
= jiffies
+ CPU_OFFSET(this_cpu
);
2293 struct sched_domain
*sd
;
2295 /* Update our load */
2296 old_load
= this_rq
->cpu_load
;
2297 this_load
= this_rq
->nr_running
* SCHED_LOAD_SCALE
;
2299 * Round up the averaging division if load is increasing. This
2300 * prevents us from getting stuck on 9 if the load is 10, for
2303 if (this_load
> old_load
)
2305 this_rq
->cpu_load
= (old_load
+ this_load
) / 2;
2307 for_each_domain(this_cpu
, sd
) {
2308 unsigned long interval
= sd
->balance_interval
;
2311 interval
*= sd
->busy_factor
;
2313 /* scale ms to jiffies */
2314 interval
= msecs_to_jiffies(interval
);
2315 if (unlikely(!interval
))
2318 if (j
- sd
->last_balance
>= interval
) {
2319 if (load_balance(this_cpu
, this_rq
, sd
, idle
)) {
2320 /* We've pulled tasks over so no longer idle */
2323 sd
->last_balance
+= interval
;
2329 * on UP we do not need to balance between CPUs:
2331 static inline void rebalance_tick(int cpu
, runqueue_t
*rq
, enum idle_type idle
)
2334 static inline void idle_balance(int cpu
, runqueue_t
*rq
)
2339 static inline int wake_priority_sleeper(runqueue_t
*rq
)
2342 #ifdef CONFIG_SCHED_SMT
2343 spin_lock(&rq
->lock
);
2345 * If an SMT sibling task has been put to sleep for priority
2346 * reasons reschedule the idle task to see if it can now run.
2348 if (rq
->nr_running
) {
2349 resched_task(rq
->idle
);
2352 spin_unlock(&rq
->lock
);
2357 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
2359 EXPORT_PER_CPU_SYMBOL(kstat
);
2362 * We place interactive tasks back into the active array, if possible.
2364 * To guarantee that this does not starve expired tasks we ignore the
2365 * interactivity of a task if the first expired task had to wait more
2366 * than a 'reasonable' amount of time. This deadline timeout is
2367 * load-dependent, as the frequency of array switched decreases with
2368 * increasing number of running tasks. We also ignore the interactivity
2369 * if a better static_prio task has expired:
2371 #define EXPIRED_STARVING(rq) \
2372 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2373 (jiffies - (rq)->expired_timestamp >= \
2374 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2375 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2378 * This function gets called by the timer code, with HZ frequency.
2379 * We call it with interrupts disabled.
2381 * It also gets called by the fork code, when changing the parent's
2384 void scheduler_tick(int user_ticks
, int sys_ticks
)
2386 int cpu
= smp_processor_id();
2387 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
2388 runqueue_t
*rq
= this_rq();
2389 task_t
*p
= current
;
2391 rq
->timestamp_last_tick
= sched_clock();
2393 if (rcu_pending(cpu
))
2394 rcu_check_callbacks(cpu
, user_ticks
);
2396 /* note: this timer irq context must be accounted for as well */
2397 if (hardirq_count() - HARDIRQ_OFFSET
) {
2398 cpustat
->irq
+= sys_ticks
;
2400 } else if (softirq_count()) {
2401 cpustat
->softirq
+= sys_ticks
;
2405 if (p
== rq
->idle
) {
2406 if (atomic_read(&rq
->nr_iowait
) > 0)
2407 cpustat
->iowait
+= sys_ticks
;
2409 cpustat
->idle
+= sys_ticks
;
2410 if (wake_priority_sleeper(rq
))
2412 rebalance_tick(cpu
, rq
, IDLE
);
2415 if (TASK_NICE(p
) > 0)
2416 cpustat
->nice
+= user_ticks
;
2418 cpustat
->user
+= user_ticks
;
2419 cpustat
->system
+= sys_ticks
;
2421 /* Task might have expired already, but not scheduled off yet */
2422 if (p
->array
!= rq
->active
) {
2423 set_tsk_need_resched(p
);
2426 spin_lock(&rq
->lock
);
2428 * The task was running during this tick - update the
2429 * time slice counter. Note: we do not update a thread's
2430 * priority until it either goes to sleep or uses up its
2431 * timeslice. This makes it possible for interactive tasks
2432 * to use up their timeslices at their highest priority levels.
2436 * RR tasks need a special form of timeslice management.
2437 * FIFO tasks have no timeslices.
2439 if ((p
->policy
== SCHED_RR
) && !--p
->time_slice
) {
2440 p
->time_slice
= task_timeslice(p
);
2441 p
->first_time_slice
= 0;
2442 set_tsk_need_resched(p
);
2444 /* put it at the end of the queue: */
2445 dequeue_task(p
, rq
->active
);
2446 enqueue_task(p
, rq
->active
);
2450 if (!--p
->time_slice
) {
2451 dequeue_task(p
, rq
->active
);
2452 set_tsk_need_resched(p
);
2453 p
->prio
= effective_prio(p
);
2454 p
->time_slice
= task_timeslice(p
);
2455 p
->first_time_slice
= 0;
2457 if (!rq
->expired_timestamp
)
2458 rq
->expired_timestamp
= jiffies
;
2459 if (!TASK_INTERACTIVE(p
) || EXPIRED_STARVING(rq
)) {
2460 enqueue_task(p
, rq
->expired
);
2461 if (p
->static_prio
< rq
->best_expired_prio
)
2462 rq
->best_expired_prio
= p
->static_prio
;
2464 enqueue_task(p
, rq
->active
);
2467 * Prevent a too long timeslice allowing a task to monopolize
2468 * the CPU. We do this by splitting up the timeslice into
2471 * Note: this does not mean the task's timeslices expire or
2472 * get lost in any way, they just might be preempted by
2473 * another task of equal priority. (one with higher
2474 * priority would have preempted this task already.) We
2475 * requeue this task to the end of the list on this priority
2476 * level, which is in essence a round-robin of tasks with
2479 * This only applies to tasks in the interactive
2480 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2482 if (TASK_INTERACTIVE(p
) && !((task_timeslice(p
) -
2483 p
->time_slice
) % TIMESLICE_GRANULARITY(p
)) &&
2484 (p
->time_slice
>= TIMESLICE_GRANULARITY(p
)) &&
2485 (p
->array
== rq
->active
)) {
2487 dequeue_task(p
, rq
->active
);
2488 set_tsk_need_resched(p
);
2489 p
->prio
= effective_prio(p
);
2490 enqueue_task(p
, rq
->active
);
2494 spin_unlock(&rq
->lock
);
2496 rebalance_tick(cpu
, rq
, NOT_IDLE
);
2499 #ifdef CONFIG_SCHED_SMT
2500 static inline void wake_sleeping_dependent(int this_cpu
, runqueue_t
*this_rq
)
2502 struct sched_domain
*sd
= this_rq
->sd
;
2503 cpumask_t sibling_map
;
2506 if (!(sd
->flags
& SD_SHARE_CPUPOWER
))
2510 * Unlock the current runqueue because we have to lock in
2511 * CPU order to avoid deadlocks. Caller knows that we might
2512 * unlock. We keep IRQs disabled.
2514 spin_unlock(&this_rq
->lock
);
2516 cpus_and(sibling_map
, sd
->span
, cpu_online_map
);
2518 for_each_cpu_mask(i
, sibling_map
)
2519 spin_lock(&cpu_rq(i
)->lock
);
2521 * We clear this CPU from the mask. This both simplifies the
2522 * inner loop and keps this_rq locked when we exit:
2524 cpu_clear(this_cpu
, sibling_map
);
2526 for_each_cpu_mask(i
, sibling_map
) {
2527 runqueue_t
*smt_rq
= cpu_rq(i
);
2530 * If an SMT sibling task is sleeping due to priority
2531 * reasons wake it up now.
2533 if (smt_rq
->curr
== smt_rq
->idle
&& smt_rq
->nr_running
)
2534 resched_task(smt_rq
->idle
);
2537 for_each_cpu_mask(i
, sibling_map
)
2538 spin_unlock(&cpu_rq(i
)->lock
);
2540 * We exit with this_cpu's rq still held and IRQs
2545 static inline int dependent_sleeper(int this_cpu
, runqueue_t
*this_rq
)
2547 struct sched_domain
*sd
= this_rq
->sd
;
2548 cpumask_t sibling_map
;
2549 prio_array_t
*array
;
2553 if (!(sd
->flags
& SD_SHARE_CPUPOWER
))
2557 * The same locking rules and details apply as for
2558 * wake_sleeping_dependent():
2560 spin_unlock(&this_rq
->lock
);
2561 cpus_and(sibling_map
, sd
->span
, cpu_online_map
);
2562 for_each_cpu_mask(i
, sibling_map
)
2563 spin_lock(&cpu_rq(i
)->lock
);
2564 cpu_clear(this_cpu
, sibling_map
);
2567 * Establish next task to be run - it might have gone away because
2568 * we released the runqueue lock above:
2570 if (!this_rq
->nr_running
)
2572 array
= this_rq
->active
;
2573 if (!array
->nr_active
)
2574 array
= this_rq
->expired
;
2575 BUG_ON(!array
->nr_active
);
2577 p
= list_entry(array
->queue
[sched_find_first_bit(array
->bitmap
)].next
,
2580 for_each_cpu_mask(i
, sibling_map
) {
2581 runqueue_t
*smt_rq
= cpu_rq(i
);
2582 task_t
*smt_curr
= smt_rq
->curr
;
2585 * If a user task with lower static priority than the
2586 * running task on the SMT sibling is trying to schedule,
2587 * delay it till there is proportionately less timeslice
2588 * left of the sibling task to prevent a lower priority
2589 * task from using an unfair proportion of the
2590 * physical cpu's resources. -ck
2592 if (((smt_curr
->time_slice
* (100 - sd
->per_cpu_gain
) / 100) >
2593 task_timeslice(p
) || rt_task(smt_curr
)) &&
2594 p
->mm
&& smt_curr
->mm
&& !rt_task(p
))
2598 * Reschedule a lower priority task on the SMT sibling,
2599 * or wake it up if it has been put to sleep for priority
2602 if ((((p
->time_slice
* (100 - sd
->per_cpu_gain
) / 100) >
2603 task_timeslice(smt_curr
) || rt_task(p
)) &&
2604 smt_curr
->mm
&& p
->mm
&& !rt_task(smt_curr
)) ||
2605 (smt_curr
== smt_rq
->idle
&& smt_rq
->nr_running
))
2606 resched_task(smt_curr
);
2609 for_each_cpu_mask(i
, sibling_map
)
2610 spin_unlock(&cpu_rq(i
)->lock
);
2614 static inline void wake_sleeping_dependent(int this_cpu
, runqueue_t
*this_rq
)
2618 static inline int dependent_sleeper(int this_cpu
, runqueue_t
*this_rq
)
2625 * schedule() is the main scheduler function.
2627 asmlinkage
void __sched
schedule(void)
2630 task_t
*prev
, *next
;
2632 prio_array_t
*array
;
2633 struct list_head
*queue
;
2634 unsigned long long now
;
2635 unsigned long run_time
;
2639 * Test if we are atomic. Since do_exit() needs to call into
2640 * schedule() atomically, we ignore that path for now.
2641 * Otherwise, whine if we are scheduling when we should not be.
2643 if (likely(!(current
->state
& (TASK_DEAD
| TASK_ZOMBIE
)))) {
2644 if (unlikely(in_atomic())) {
2645 printk(KERN_ERR
"bad: scheduling while atomic!\n");
2650 #if 0 // mask by Victor Yu. 05-26-2005
2652 #else // add by Victor Yu. 05-26-2005
2653 need_resched_victor
:
2660 * The idle thread is not allowed to schedule!
2661 * Remove this check after it has been exercised a bit.
2663 if (unlikely(current
== rq
->idle
) && current
->state
!= TASK_RUNNING
) {
2664 printk(KERN_ERR
"bad: scheduling from the idle thread!\n");
2668 release_kernel_lock(prev
);
2669 schedstat_inc(rq
, sched_cnt
);
2670 now
= sched_clock();
2671 if (likely(now
- prev
->timestamp
< NS_MAX_SLEEP_AVG
))
2672 run_time
= now
- prev
->timestamp
;
2674 run_time
= NS_MAX_SLEEP_AVG
;
2677 * Tasks with interactive credits get charged less run_time
2678 * at high sleep_avg to delay them losing their interactive
2681 if (HIGH_CREDIT(prev
))
2682 run_time
/= (CURRENT_BONUS(prev
) ? : 1);
2684 spin_lock_irq(&rq
->lock
);
2687 * if entering off of a kernel preemption go straight
2688 * to picking the next task.
2690 switch_count
= &prev
->nivcsw
;
2691 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
2692 switch_count
= &prev
->nvcsw
;
2693 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
2694 unlikely(signal_pending(prev
))))
2695 prev
->state
= TASK_RUNNING
;
2697 deactivate_task(prev
, rq
);
2700 cpu
= smp_processor_id();
2701 if (unlikely(!rq
->nr_running
)) {
2703 idle_balance(cpu
, rq
);
2704 if (!rq
->nr_running
) {
2706 rq
->expired_timestamp
= 0;
2707 wake_sleeping_dependent(cpu
, rq
);
2709 * wake_sleeping_dependent() might have released
2710 * the runqueue, so break out if we got new
2713 if (!rq
->nr_running
) {
2718 if (dependent_sleeper(cpu
, rq
)) {
2719 schedstat_inc(rq
, sched_goidle
);
2724 * dependent_sleeper() releases and reacquires the runqueue
2725 * lock, hence go into the idle loop if the rq went
2728 if (unlikely(!rq
->nr_running
)) {
2734 if (unlikely(!array
->nr_active
)) {
2736 * Switch the active and expired arrays.
2738 schedstat_inc(rq
, sched_switch
);
2739 rq
->active
= rq
->expired
;
2740 rq
->expired
= array
;
2742 rq
->expired_timestamp
= 0;
2743 rq
->best_expired_prio
= MAX_PRIO
;
2745 schedstat_inc(rq
, sched_noswitch
);
2747 idx
= sched_find_first_bit(array
->bitmap
);
2748 queue
= array
->queue
+ idx
;
2749 next
= list_entry(queue
->next
, task_t
, run_list
);
2751 if (!rt_task(next
) && next
->activated
> 0) {
2752 unsigned long long delta
= now
- next
->timestamp
;
2754 if (next
->activated
== 1)
2755 delta
= delta
* (ON_RUNQUEUE_WEIGHT
* 128 / 100) / 128;
2757 array
= next
->array
;
2758 dequeue_task(next
, array
);
2759 recalc_task_prio(next
, next
->timestamp
+ delta
);
2760 enqueue_task(next
, array
);
2762 next
->activated
= 0;
2765 clear_tsk_need_resched(prev
);
2766 rcu_qsctr_inc(task_cpu(prev
));
2768 prev
->sleep_avg
-= run_time
;
2769 if ((long)prev
->sleep_avg
<= 0) {
2770 prev
->sleep_avg
= 0;
2771 if (!(HIGH_CREDIT(prev
) || LOW_CREDIT(prev
)))
2772 prev
->interactive_credit
--;
2774 prev
->timestamp
= prev
->last_ran
= now
;
2776 sched_info_switch(prev
, next
);
2777 if (likely(prev
!= next
)) {
2778 next
->timestamp
= now
;
2783 prepare_arch_switch(rq
, next
);
2784 prev
= context_switch(rq
, prev
, next
);
2787 finish_task_switch(prev
);
2789 spin_unlock_irq(&rq
->lock
);
2792 reacquire_kernel_lock(current
);
2793 preempt_enable_no_resched();
2794 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
))) {
2795 #if 0 // mask by Victor Yu. 05-26-2005
2797 #else // add by Victor Yu. 05-26-2005
2798 goto need_resched_victor
;
2803 EXPORT_SYMBOL(schedule
);
2805 #ifdef CONFIG_PREEMPT
2807 * this is is the entry point to schedule() from in-kernel preemption
2808 * off of preempt_enable. Kernel preemptions off return from interrupt
2809 * occur there and call schedule directly.
2811 asmlinkage
void __sched
preempt_schedule(void)
2813 struct thread_info
*ti
= current_thread_info();
2816 * If there is a non-zero preempt_count or interrupts are disabled,
2817 * we do not want to preempt the current task. Just return..
2819 if (unlikely(ti
->preempt_count
|| irqs_disabled()))
2823 ti
->preempt_count
= PREEMPT_ACTIVE
;
2825 ti
->preempt_count
= 0;
2827 /* we could miss a preemption opportunity between schedule and now */
2829 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
2833 EXPORT_SYMBOL(preempt_schedule
);
2834 #endif /* CONFIG_PREEMPT */
2836 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
, void *key
)
2838 task_t
*p
= curr
->task
;
2839 return try_to_wake_up(p
, mode
, sync
);
2842 EXPORT_SYMBOL(default_wake_function
);
2845 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2846 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2847 * number) then we wake all the non-exclusive tasks and one exclusive task.
2849 * There are circumstances in which we can try to wake a task which has already
2850 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2851 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2853 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
2854 int nr_exclusive
, int sync
, void *key
)
2856 struct list_head
*tmp
, *next
;
2858 list_for_each_safe(tmp
, next
, &q
->task_list
) {
2861 curr
= list_entry(tmp
, wait_queue_t
, task_list
);
2862 flags
= curr
->flags
;
2863 if (curr
->func(curr
, mode
, sync
, key
) &&
2864 (flags
& WQ_FLAG_EXCLUSIVE
) &&
2871 * __wake_up - wake up threads blocked on a waitqueue.
2873 * @mode: which threads
2874 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2876 void fastcall
__wake_up(wait_queue_head_t
*q
, unsigned int mode
,
2877 int nr_exclusive
, void *key
)
2879 unsigned long flags
;
2881 spin_lock_irqsave(&q
->lock
, flags
);
2882 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
2883 spin_unlock_irqrestore(&q
->lock
, flags
);
2886 EXPORT_SYMBOL(__wake_up
);
2889 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2891 void fastcall
__wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
2893 __wake_up_common(q
, mode
, 1, 0, NULL
);
2897 * __wake_up - sync- wake up threads blocked on a waitqueue.
2899 * @mode: which threads
2900 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2902 * The sync wakeup differs that the waker knows that it will schedule
2903 * away soon, so while the target thread will be woken up, it will not
2904 * be migrated to another CPU - ie. the two threads are 'synchronized'
2905 * with each other. This can prevent needless bouncing between CPUs.
2907 * On UP it can prevent extra preemption.
2909 void fastcall
__wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
2911 unsigned long flags
;
2917 if (unlikely(!nr_exclusive
))
2920 spin_lock_irqsave(&q
->lock
, flags
);
2921 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
2922 spin_unlock_irqrestore(&q
->lock
, flags
);
2924 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
2926 void fastcall
complete(struct completion
*x
)
2928 unsigned long flags
;
2930 spin_lock_irqsave(&x
->wait
.lock
, flags
);
2932 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
2934 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
2936 EXPORT_SYMBOL(complete
);
2938 void fastcall
complete_all(struct completion
*x
)
2940 unsigned long flags
;
2942 spin_lock_irqsave(&x
->wait
.lock
, flags
);
2943 x
->done
+= UINT_MAX
/2;
2944 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
2946 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
2948 EXPORT_SYMBOL(complete_all
);
2950 void fastcall __sched
wait_for_completion(struct completion
*x
)
2953 spin_lock_irq(&x
->wait
.lock
);
2955 DECLARE_WAITQUEUE(wait
, current
);
2957 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
2958 __add_wait_queue_tail(&x
->wait
, &wait
);
2960 __set_current_state(TASK_UNINTERRUPTIBLE
);
2961 spin_unlock_irq(&x
->wait
.lock
);
2963 spin_lock_irq(&x
->wait
.lock
);
2965 __remove_wait_queue(&x
->wait
, &wait
);
2968 spin_unlock_irq(&x
->wait
.lock
);
2970 EXPORT_SYMBOL(wait_for_completion
);
2972 #define SLEEP_ON_VAR \
2973 unsigned long flags; \
2974 wait_queue_t wait; \
2975 init_waitqueue_entry(&wait, current);
2977 #define SLEEP_ON_HEAD \
2978 spin_lock_irqsave(&q->lock,flags); \
2979 __add_wait_queue(q, &wait); \
2980 spin_unlock(&q->lock);
2982 #define SLEEP_ON_TAIL \
2983 spin_lock_irq(&q->lock); \
2984 __remove_wait_queue(q, &wait); \
2985 spin_unlock_irqrestore(&q->lock, flags);
2987 void fastcall __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
2991 current
->state
= TASK_INTERRUPTIBLE
;
2998 EXPORT_SYMBOL(interruptible_sleep_on
);
3000 long fastcall __sched
interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3004 current
->state
= TASK_INTERRUPTIBLE
;
3007 timeout
= schedule_timeout(timeout
);
3013 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
3015 void fastcall __sched
sleep_on(wait_queue_head_t
*q
)
3019 current
->state
= TASK_UNINTERRUPTIBLE
;
3026 EXPORT_SYMBOL(sleep_on
);
3028 long fastcall __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
3032 current
->state
= TASK_UNINTERRUPTIBLE
;
3035 timeout
= schedule_timeout(timeout
);
3041 EXPORT_SYMBOL(sleep_on_timeout
);
3043 void set_user_nice(task_t
*p
, long nice
)
3045 unsigned long flags
;
3046 prio_array_t
*array
;
3048 int old_prio
, new_prio
, delta
;
3050 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
3053 * We have to be careful, if called from sys_setpriority(),
3054 * the task might be in the middle of scheduling on another CPU.
3056 rq
= task_rq_lock(p
, &flags
);
3058 * The RT priorities are set via setscheduler(), but we still
3059 * allow the 'normal' nice value to be set - but as expected
3060 * it wont have any effect on scheduling until the task is
3064 p
->static_prio
= NICE_TO_PRIO(nice
);
3069 dequeue_task(p
, array
);
3072 new_prio
= NICE_TO_PRIO(nice
);
3073 delta
= new_prio
- old_prio
;
3074 p
->static_prio
= NICE_TO_PRIO(nice
);
3078 enqueue_task(p
, array
);
3080 * If the task increased its priority or is running and
3081 * lowered its priority, then reschedule its CPU:
3083 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
3084 resched_task(rq
->curr
);
3087 task_rq_unlock(rq
, &flags
);
3090 EXPORT_SYMBOL(set_user_nice
);
3092 #ifdef __ARCH_WANT_SYS_NICE
3095 * sys_nice - change the priority of the current process.
3096 * @increment: priority increment
3098 * sys_setpriority is a more generic, but much slower function that
3099 * does similar things.
3101 asmlinkage
long sys_nice(int increment
)
3107 * Setpriority might change our priority at the same moment.
3108 * We don't have to worry. Conceptually one call occurs first
3109 * and we have a single winner.
3111 if (increment
< 0) {
3112 if (!capable(CAP_SYS_NICE
))
3114 if (increment
< -40)
3120 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
3126 retval
= security_task_setnice(current
, nice
);
3130 set_user_nice(current
, nice
);
3137 * task_prio - return the priority value of a given task.
3138 * @p: the task in question.
3140 * This is the priority value as seen by users in /proc.
3141 * RT tasks are offset by -200. Normal tasks are centered
3142 * around 0, value goes from -16 to +15.
3144 int task_prio(const task_t
*p
)
3146 return p
->prio
- MAX_RT_PRIO
;
3150 * task_nice - return the nice value of a given task.
3151 * @p: the task in question.
3153 int task_nice(const task_t
*p
)
3155 return TASK_NICE(p
);
3158 EXPORT_SYMBOL(task_nice
);
3161 * idle_cpu - is a given cpu idle currently?
3162 * @cpu: the processor in question.
3164 int idle_cpu(int cpu
)
3166 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
3169 EXPORT_SYMBOL_GPL(idle_cpu
);
3172 * find_process_by_pid - find a process with a matching PID value.
3173 * @pid: the pid in question.
3175 static inline task_t
*find_process_by_pid(pid_t pid
)
3177 return pid
? find_task_by_pid(pid
) : current
;
3180 /* Actually do priority change: must hold rq lock. */
3181 static void __setscheduler(struct task_struct
*p
, int policy
, int prio
)
3185 p
->rt_priority
= prio
;
3186 if (policy
!= SCHED_NORMAL
)
3187 p
->prio
= MAX_USER_RT_PRIO
-1 - p
->rt_priority
;
3189 p
->prio
= p
->static_prio
;
3193 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3195 static int setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
3197 struct sched_param lp
;
3198 int retval
= -EINVAL
;
3200 prio_array_t
*array
;
3201 unsigned long flags
;
3205 if (!param
|| pid
< 0)
3209 if (copy_from_user(&lp
, param
, sizeof(struct sched_param
)))
3213 * We play safe to avoid deadlocks.
3215 read_lock_irq(&tasklist_lock
);
3217 p
= find_process_by_pid(pid
);
3221 goto out_unlock_tasklist
;
3224 * To be able to change p->policy safely, the apropriate
3225 * runqueue lock must be held.
3227 rq
= task_rq_lock(p
, &flags
);
3233 if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
3234 policy
!= SCHED_NORMAL
)
3237 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3240 * Valid priorities for SCHED_FIFO and SCHED_RR are
3241 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3244 if (lp
.sched_priority
< 0 || lp
.sched_priority
> MAX_USER_RT_PRIO
-1)
3246 if ((policy
== SCHED_NORMAL
) != (lp
.sched_priority
== 0))
3250 if ((policy
== SCHED_FIFO
|| policy
== SCHED_RR
) &&
3251 !capable(CAP_SYS_NICE
))
3253 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
3254 !capable(CAP_SYS_NICE
))
3257 retval
= security_task_setscheduler(p
, policy
, &lp
);
3263 deactivate_task(p
, task_rq(p
));
3266 __setscheduler(p
, policy
, lp
.sched_priority
);
3268 __activate_task(p
, task_rq(p
));
3270 * Reschedule if we are currently running on this runqueue and
3271 * our priority decreased, or if we are not currently running on
3272 * this runqueue and our priority is higher than the current's
3274 if (task_running(rq
, p
)) {
3275 if (p
->prio
> oldprio
)
3276 resched_task(rq
->curr
);
3277 } else if (TASK_PREEMPTS_CURR(p
, rq
))
3278 resched_task(rq
->curr
);
3282 task_rq_unlock(rq
, &flags
);
3283 out_unlock_tasklist
:
3284 read_unlock_irq(&tasklist_lock
);
3291 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3292 * @pid: the pid in question.
3293 * @policy: new policy
3294 * @param: structure containing the new RT priority.
3296 asmlinkage
long sys_sched_setscheduler(pid_t pid
, int policy
,
3297 struct sched_param __user
*param
)
3299 return setscheduler(pid
, policy
, param
);
3303 * sys_sched_setparam - set/change the RT priority of a thread
3304 * @pid: the pid in question.
3305 * @param: structure containing the new RT priority.
3307 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
3309 return setscheduler(pid
, -1, param
);
3313 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3314 * @pid: the pid in question.
3316 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
3318 int retval
= -EINVAL
;
3325 read_lock(&tasklist_lock
);
3326 p
= find_process_by_pid(pid
);
3328 retval
= security_task_getscheduler(p
);
3332 read_unlock(&tasklist_lock
);
3339 * sys_sched_getscheduler - get the RT priority of a thread
3340 * @pid: the pid in question.
3341 * @param: structure containing the RT priority.
3343 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
3345 struct sched_param lp
;
3346 int retval
= -EINVAL
;
3349 if (!param
|| pid
< 0)
3352 read_lock(&tasklist_lock
);
3353 p
= find_process_by_pid(pid
);
3358 retval
= security_task_getscheduler(p
);
3362 lp
.sched_priority
= p
->rt_priority
;
3363 read_unlock(&tasklist_lock
);
3366 * This one might sleep, we cannot do it with a spinlock held ...
3368 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
3374 read_unlock(&tasklist_lock
);
3378 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
3384 read_lock(&tasklist_lock
);
3386 p
= find_process_by_pid(pid
);
3388 read_unlock(&tasklist_lock
);
3389 unlock_cpu_hotplug();
3394 * It is not safe to call set_cpus_allowed with the
3395 * tasklist_lock held. We will bump the task_struct's
3396 * usage count and then drop tasklist_lock.
3399 read_unlock(&tasklist_lock
);
3402 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
3403 !capable(CAP_SYS_NICE
))
3406 retval
= set_cpus_allowed(p
, new_mask
);
3410 unlock_cpu_hotplug();
3414 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
3415 cpumask_t
*new_mask
)
3417 if (len
< sizeof(cpumask_t
)) {
3418 memset(new_mask
, 0, sizeof(cpumask_t
));
3419 } else if (len
> sizeof(cpumask_t
)) {
3420 len
= sizeof(cpumask_t
);
3422 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
3426 * sys_sched_setaffinity - set the cpu affinity of a process
3427 * @pid: pid of the process
3428 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3429 * @user_mask_ptr: user-space pointer to the new cpu mask
3431 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
3432 unsigned long __user
*user_mask_ptr
)
3437 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
3441 return sched_setaffinity(pid
, new_mask
);
3445 * Represents all cpu's present in the system
3446 * In systems capable of hotplug, this map could dynamically grow
3447 * as new cpu's are detected in the system via any platform specific
3448 * method, such as ACPI for e.g.
3451 cpumask_t cpu_present_map
;
3452 EXPORT_SYMBOL(cpu_present_map
);
3455 cpumask_t cpu_online_map
= CPU_MASK_ALL
;
3456 cpumask_t cpu_possible_map
= CPU_MASK_ALL
;
3459 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
3465 read_lock(&tasklist_lock
);
3468 p
= find_process_by_pid(pid
);
3473 cpus_and(*mask
, p
->cpus_allowed
, cpu_possible_map
);
3476 read_unlock(&tasklist_lock
);
3477 unlock_cpu_hotplug();
3485 * sys_sched_getaffinity - get the cpu affinity of a process
3486 * @pid: pid of the process
3487 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3488 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3490 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
3491 unsigned long __user
*user_mask_ptr
)
3496 if (len
< sizeof(cpumask_t
))
3499 ret
= sched_getaffinity(pid
, &mask
);
3503 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
3506 return sizeof(cpumask_t
);
3510 * sys_sched_yield - yield the current processor to other threads.
3512 * this function yields the current CPU by moving the calling thread
3513 * to the expired array. If there are no other threads running on this
3514 * CPU then this function will return.
3516 asmlinkage
long sys_sched_yield(void)
3518 runqueue_t
*rq
= this_rq_lock();
3519 prio_array_t
*array
= current
->array
;
3520 prio_array_t
*target
= rq
->expired
;
3522 schedstat_inc(rq
, yld_cnt
);
3524 * We implement yielding by moving the task into the expired
3527 * (special rule: RT tasks will just roundrobin in the active
3530 if (rt_task(current
))
3531 target
= rq
->active
;
3533 if (current
->array
->nr_active
== 1) {
3534 schedstat_inc(rq
, yld_act_empty
);
3535 if (!rq
->expired
->nr_active
)
3536 schedstat_inc(rq
, yld_both_empty
);
3537 } else if (!rq
->expired
->nr_active
)
3538 schedstat_inc(rq
, yld_exp_empty
);
3540 dequeue_task(current
, array
);
3541 enqueue_task(current
, target
);
3544 * Since we are going to call schedule() anyway, there's
3545 * no need to preempt or enable interrupts:
3547 _raw_spin_unlock(&rq
->lock
);
3548 preempt_enable_no_resched();
3555 void __sched
__cond_resched(void)
3557 set_current_state(TASK_RUNNING
);
3561 EXPORT_SYMBOL(__cond_resched
);
3564 * yield - yield the current processor to other threads.
3566 * this is a shortcut for kernel-space yielding - it marks the
3567 * thread runnable and calls sys_sched_yield().
3569 void __sched
yield(void)
3571 set_current_state(TASK_RUNNING
);
3575 EXPORT_SYMBOL(yield
);
3578 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3579 * that process accounting knows that this is a task in IO wait state.
3581 * But don't do that if it is a deliberate, throttling IO wait (this task
3582 * has set its backing_dev_info: the queue against which it should throttle)
3584 void __sched
io_schedule(void)
3586 struct runqueue
*rq
= this_rq();
3588 atomic_inc(&rq
->nr_iowait
);
3590 atomic_dec(&rq
->nr_iowait
);
3593 EXPORT_SYMBOL(io_schedule
);
3595 long __sched
io_schedule_timeout(long timeout
)
3597 struct runqueue
*rq
= this_rq();
3600 atomic_inc(&rq
->nr_iowait
);
3601 ret
= schedule_timeout(timeout
);
3602 atomic_dec(&rq
->nr_iowait
);
3607 * sys_sched_get_priority_max - return maximum RT priority.
3608 * @policy: scheduling class.
3610 * this syscall returns the maximum rt_priority that can be used
3611 * by a given scheduling class.
3613 asmlinkage
long sys_sched_get_priority_max(int policy
)
3620 ret
= MAX_USER_RT_PRIO
-1;
3630 * sys_sched_get_priority_min - return minimum RT priority.
3631 * @policy: scheduling class.
3633 * this syscall returns the minimum rt_priority that can be used
3634 * by a given scheduling class.
3636 asmlinkage
long sys_sched_get_priority_min(int policy
)
3652 * sys_sched_rr_get_interval - return the default timeslice of a process.
3653 * @pid: pid of the process.
3654 * @interval: userspace pointer to the timeslice value.
3656 * this syscall writes the default timeslice value of a given process
3657 * into the user-space timespec buffer. A value of '0' means infinity.
3660 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
3662 int retval
= -EINVAL
;
3670 read_lock(&tasklist_lock
);
3671 p
= find_process_by_pid(pid
);
3675 retval
= security_task_getscheduler(p
);
3679 jiffies_to_timespec(p
->policy
& SCHED_FIFO
?
3680 0 : task_timeslice(p
), &t
);
3681 read_unlock(&tasklist_lock
);
3682 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
3686 read_unlock(&tasklist_lock
);
3690 static inline struct task_struct
*eldest_child(struct task_struct
*p
)
3692 if (list_empty(&p
->children
)) return NULL
;
3693 return list_entry(p
->children
.next
,struct task_struct
,sibling
);
3696 static inline struct task_struct
*older_sibling(struct task_struct
*p
)
3698 if (p
->sibling
.prev
==&p
->parent
->children
) return NULL
;
3699 return list_entry(p
->sibling
.prev
,struct task_struct
,sibling
);
3702 static inline struct task_struct
*younger_sibling(struct task_struct
*p
)
3704 if (p
->sibling
.next
==&p
->parent
->children
) return NULL
;
3705 return list_entry(p
->sibling
.next
,struct task_struct
,sibling
);
3708 static void show_task(task_t
* p
)
3712 unsigned long free
= 0;
3713 static const char *stat_nam
[] = { "R", "S", "D", "T", "t", "Z", "X" };
3715 printk("%-13.13s ", p
->comm
);
3716 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
3717 if (state
< ARRAY_SIZE(stat_nam
))
3718 printk(stat_nam
[state
]);
3721 #if (BITS_PER_LONG == 32)
3722 if (state
== TASK_RUNNING
)
3723 printk(" running ");
3725 printk(" %08lX ", thread_saved_pc(p
));
3727 if (state
== TASK_RUNNING
)
3728 printk(" running task ");
3730 printk(" %016lx ", thread_saved_pc(p
));
3732 #ifdef CONFIG_DEBUG_STACK_USAGE
3734 unsigned long * n
= (unsigned long *) (p
->thread_info
+1);
3737 free
= (unsigned long) n
- (unsigned long)(p
->thread_info
+1);
3740 printk("%5lu %5d %6d ", free
, p
->pid
, p
->parent
->pid
);
3741 if ((relative
= eldest_child(p
)))
3742 printk("%5d ", relative
->pid
);
3745 if ((relative
= younger_sibling(p
)))
3746 printk("%7d", relative
->pid
);
3749 if ((relative
= older_sibling(p
)))
3750 printk(" %5d", relative
->pid
);
3754 printk(" (L-TLB)\n");
3756 printk(" (NOTLB)\n");
3758 if (state
!= TASK_RUNNING
)
3759 show_stack(p
, NULL
);
3762 void show_state(void)
3766 #if (BITS_PER_LONG == 32)
3769 printk(" task PC pid father child younger older\n");
3773 printk(" task PC pid father child younger older\n");
3775 read_lock(&tasklist_lock
);
3776 do_each_thread(g
, p
) {
3778 * reset the NMI-timeout, listing all files on a slow
3779 * console might take alot of time:
3781 touch_nmi_watchdog();
3783 } while_each_thread(g
, p
);
3785 read_unlock(&tasklist_lock
);
3788 void __devinit
init_idle(task_t
*idle
, int cpu
)
3790 runqueue_t
*rq
= cpu_rq(cpu
);
3791 unsigned long flags
;
3793 idle
->sleep_avg
= 0;
3794 idle
->interactive_credit
= 0;
3796 idle
->prio
= MAX_PRIO
;
3797 idle
->state
= TASK_RUNNING
;
3798 set_task_cpu(idle
, cpu
);
3800 spin_lock_irqsave(&rq
->lock
, flags
);
3801 rq
->curr
= rq
->idle
= idle
;
3802 set_tsk_need_resched(idle
);
3803 spin_unlock_irqrestore(&rq
->lock
, flags
);
3805 /* Set the preempt count _outside_ the spinlocks! */
3806 #ifdef CONFIG_PREEMPT
3807 idle
->thread_info
->preempt_count
= (idle
->lock_depth
>= 0);
3809 idle
->thread_info
->preempt_count
= 0;
3814 * In a system that switches off the HZ timer nohz_cpu_mask
3815 * indicates which cpus entered this state. This is used
3816 * in the rcu update to wait only for active cpus. For system
3817 * which do not switch off the HZ timer nohz_cpu_mask should
3818 * always be CPU_MASK_NONE.
3820 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
3824 * This is how migration works:
3826 * 1) we queue a migration_req_t structure in the source CPU's
3827 * runqueue and wake up that CPU's migration thread.
3828 * 2) we down() the locked semaphore => thread blocks.
3829 * 3) migration thread wakes up (implicitly it forces the migrated
3830 * thread off the CPU)
3831 * 4) it gets the migration request and checks whether the migrated
3832 * task is still in the wrong runqueue.
3833 * 5) if it's in the wrong runqueue then the migration thread removes
3834 * it and puts it into the right queue.
3835 * 6) migration thread up()s the semaphore.
3836 * 7) we wake up and the migration is done.
3840 * Change a given task's CPU affinity. Migrate the thread to a
3841 * proper CPU and schedule it away if the CPU it's executing on
3842 * is removed from the allowed bitmask.
3844 * NOTE: the caller must have a valid reference to the task, the
3845 * task must not exit() & deallocate itself prematurely. The
3846 * call is not atomic; no spinlocks may be held.
3848 int set_cpus_allowed(task_t
*p
, cpumask_t new_mask
)
3850 unsigned long flags
;
3852 migration_req_t req
;
3855 rq
= task_rq_lock(p
, &flags
);
3856 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
3861 p
->cpus_allowed
= new_mask
;
3862 /* Can the task run on the task's current CPU? If so, we're done */
3863 if (cpu_isset(task_cpu(p
), new_mask
))
3866 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
3867 /* Need help from migration thread: drop lock and wait. */
3868 task_rq_unlock(rq
, &flags
);
3869 wake_up_process(rq
->migration_thread
);
3870 wait_for_completion(&req
.done
);
3871 tlb_migrate_finish(p
->mm
);
3875 task_rq_unlock(rq
, &flags
);
3879 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
3882 * Move (not current) task off this cpu, onto dest cpu. We're doing
3883 * this because either it can't run here any more (set_cpus_allowed()
3884 * away from this CPU, or CPU going down), or because we're
3885 * attempting to rebalance this task on exec (sched_exec).
3887 * So we race with normal scheduler movements, but that's OK, as long
3888 * as the task is no longer on this CPU.
3890 static void __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
3892 runqueue_t
*rq_dest
, *rq_src
;
3894 if (unlikely(cpu_is_offline(dest_cpu
)))
3897 rq_src
= cpu_rq(src_cpu
);
3898 rq_dest
= cpu_rq(dest_cpu
);
3900 double_rq_lock(rq_src
, rq_dest
);
3901 /* Already moved. */
3902 if (task_cpu(p
) != src_cpu
)
3904 /* Affinity changed (again). */
3905 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
3908 set_task_cpu(p
, dest_cpu
);
3911 * Sync timestamp with rq_dest's before activating.
3912 * The same thing could be achieved by doing this step
3913 * afterwards, and pretending it was a local activate.
3914 * This way is cleaner and logically correct.
3916 p
->timestamp
= p
->timestamp
- rq_src
->timestamp_last_tick
3917 + rq_dest
->timestamp_last_tick
;
3918 deactivate_task(p
, rq_src
);
3919 activate_task(p
, rq_dest
, 0);
3920 if (TASK_PREEMPTS_CURR(p
, rq_dest
))
3921 resched_task(rq_dest
->curr
);
3925 double_rq_unlock(rq_src
, rq_dest
);
3929 * migration_thread - this is a highprio system thread that performs
3930 * thread migration by bumping thread off CPU then 'pushing' onto
3933 static int migration_thread(void * data
)
3936 int cpu
= (long)data
;
3939 BUG_ON(rq
->migration_thread
!= current
);
3941 set_current_state(TASK_INTERRUPTIBLE
);
3942 while (!kthread_should_stop()) {
3943 struct list_head
*head
;
3944 migration_req_t
*req
;
3946 if (current
->flags
& PF_FREEZE
)
3947 refrigerator(PF_FREEZE
);
3949 spin_lock_irq(&rq
->lock
);
3951 if (cpu_is_offline(cpu
)) {
3952 spin_unlock_irq(&rq
->lock
);
3956 if (rq
->active_balance
) {
3957 active_load_balance(rq
, cpu
);
3958 rq
->active_balance
= 0;
3961 head
= &rq
->migration_queue
;
3963 if (list_empty(head
)) {
3964 spin_unlock_irq(&rq
->lock
);
3966 set_current_state(TASK_INTERRUPTIBLE
);
3969 req
= list_entry(head
->next
, migration_req_t
, list
);
3970 list_del_init(head
->next
);
3972 if (req
->type
== REQ_MOVE_TASK
) {
3973 spin_unlock(&rq
->lock
);
3974 __migrate_task(req
->task
, smp_processor_id(),
3977 } else if (req
->type
== REQ_SET_DOMAIN
) {
3979 spin_unlock_irq(&rq
->lock
);
3981 spin_unlock_irq(&rq
->lock
);
3985 complete(&req
->done
);
3987 __set_current_state(TASK_RUNNING
);
3991 /* Wait for kthread_stop */
3992 set_current_state(TASK_INTERRUPTIBLE
);
3993 while (!kthread_should_stop()) {
3995 set_current_state(TASK_INTERRUPTIBLE
);
3997 __set_current_state(TASK_RUNNING
);
4001 #ifdef CONFIG_HOTPLUG_CPU
4002 /* Figure out where task on dead CPU should go, use force if neccessary. */
4003 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*tsk
)
4009 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
4010 cpus_and(mask
, mask
, tsk
->cpus_allowed
);
4011 dest_cpu
= any_online_cpu(mask
);
4013 /* On any allowed CPU? */
4014 if (dest_cpu
== NR_CPUS
)
4015 dest_cpu
= any_online_cpu(tsk
->cpus_allowed
);
4017 /* No more Mr. Nice Guy. */
4018 if (dest_cpu
== NR_CPUS
) {
4019 cpus_setall(tsk
->cpus_allowed
);
4020 dest_cpu
= any_online_cpu(tsk
->cpus_allowed
);
4023 * Don't tell them about moving exiting tasks or
4024 * kernel threads (both mm NULL), since they never
4027 if (tsk
->mm
&& printk_ratelimit())
4028 printk(KERN_INFO
"process %d (%s) no "
4029 "longer affine to cpu%d\n",
4030 tsk
->pid
, tsk
->comm
, dead_cpu
);
4032 __migrate_task(tsk
, dead_cpu
, dest_cpu
);
4035 /* Run through task list and migrate tasks from the dead cpu. */
4036 static void migrate_live_tasks(int src_cpu
)
4038 struct task_struct
*tsk
, *t
;
4040 write_lock_irq(&tasklist_lock
);
4042 do_each_thread(t
, tsk
) {
4046 if (task_cpu(tsk
) == src_cpu
)
4047 move_task_off_dead_cpu(src_cpu
, tsk
);
4048 } while_each_thread(t
, tsk
);
4050 write_unlock_irq(&tasklist_lock
);
4053 /* Schedules idle task to be the next runnable task on current CPU.
4054 * It does so by boosting its priority to highest possible and adding it to
4055 * the _front_ of runqueue. Used by CPU offline code.
4057 void sched_idle_next(void)
4059 int cpu
= smp_processor_id();
4060 runqueue_t
*rq
= this_rq();
4061 struct task_struct
*p
= rq
->idle
;
4062 unsigned long flags
;
4064 /* cpu has to be offline */
4065 BUG_ON(cpu_online(cpu
));
4067 /* Strictly not necessary since rest of the CPUs are stopped by now
4068 * and interrupts disabled on current cpu.
4070 spin_lock_irqsave(&rq
->lock
, flags
);
4072 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
4073 /* Add idle task to _front_ of it's priority queue */
4074 __activate_idle_task(p
, rq
);
4076 spin_unlock_irqrestore(&rq
->lock
, flags
);
4079 static void migrate_dead(unsigned int dead_cpu
, task_t
*tsk
)
4081 struct runqueue
*rq
= cpu_rq(dead_cpu
);
4083 /* Must be exiting, otherwise would be on tasklist. */
4084 BUG_ON(tsk
->state
!= TASK_ZOMBIE
&& tsk
->state
!= TASK_DEAD
);
4086 /* Cannot have done final schedule yet: would have vanished. */
4087 BUG_ON(tsk
->flags
& PF_DEAD
);
4089 get_task_struct(tsk
);
4092 * Drop lock around migration; if someone else moves it,
4093 * that's OK. No task can be added to this CPU, so iteration is
4096 spin_unlock_irq(&rq
->lock
);
4097 move_task_off_dead_cpu(dead_cpu
, tsk
);
4098 spin_lock_irq(&rq
->lock
);
4100 put_task_struct(tsk
);
4103 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4104 static void migrate_dead_tasks(unsigned int dead_cpu
)
4107 struct runqueue
*rq
= cpu_rq(dead_cpu
);
4109 for (arr
= 0; arr
< 2; arr
++) {
4110 for (i
= 0; i
< MAX_PRIO
; i
++) {
4111 struct list_head
*list
= &rq
->arrays
[arr
].queue
[i
];
4112 while (!list_empty(list
))
4113 migrate_dead(dead_cpu
,
4114 list_entry(list
->next
, task_t
,
4119 #endif /* CONFIG_HOTPLUG_CPU */
4122 * migration_call - callback that gets triggered when a CPU is added.
4123 * Here we can start up the necessary migration thread for the new CPU.
4125 static int migration_call(struct notifier_block
*nfb
, unsigned long action
,
4128 int cpu
= (long)hcpu
;
4129 struct task_struct
*p
;
4130 struct runqueue
*rq
;
4131 unsigned long flags
;
4134 case CPU_UP_PREPARE
:
4135 p
= kthread_create(migration_thread
, hcpu
, "migration/%d",cpu
);
4138 p
->flags
|= PF_NOFREEZE
;
4139 kthread_bind(p
, cpu
);
4140 /* Must be high prio: stop_machine expects to yield to it. */
4141 rq
= task_rq_lock(p
, &flags
);
4142 __setscheduler(p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
4143 task_rq_unlock(rq
, &flags
);
4144 cpu_rq(cpu
)->migration_thread
= p
;
4147 /* Strictly unneccessary, as first user will wake it. */
4148 wake_up_process(cpu_rq(cpu
)->migration_thread
);
4150 #ifdef CONFIG_HOTPLUG_CPU
4151 case CPU_UP_CANCELED
:
4152 /* Unbind it from offline cpu so it can run. Fall thru. */
4153 kthread_bind(cpu_rq(cpu
)->migration_thread
,smp_processor_id());
4154 kthread_stop(cpu_rq(cpu
)->migration_thread
);
4155 cpu_rq(cpu
)->migration_thread
= NULL
;
4158 migrate_live_tasks(cpu
);
4160 kthread_stop(rq
->migration_thread
);
4161 rq
->migration_thread
= NULL
;
4162 /* Idle task back to normal (off runqueue, low prio) */
4163 rq
= task_rq_lock(rq
->idle
, &flags
);
4164 deactivate_task(rq
->idle
, rq
);
4165 rq
->idle
->static_prio
= MAX_PRIO
;
4166 __setscheduler(rq
->idle
, SCHED_NORMAL
, 0);
4167 migrate_dead_tasks(cpu
);
4168 task_rq_unlock(rq
, &flags
);
4169 BUG_ON(rq
->nr_running
!= 0);
4171 /* No need to migrate the tasks: it was best-effort if
4172 * they didn't do lock_cpu_hotplug(). Just wake up
4173 * the requestors. */
4174 spin_lock_irq(&rq
->lock
);
4175 while (!list_empty(&rq
->migration_queue
)) {
4176 migration_req_t
*req
;
4177 req
= list_entry(rq
->migration_queue
.next
,
4178 migration_req_t
, list
);
4179 BUG_ON(req
->type
!= REQ_MOVE_TASK
);
4180 list_del_init(&req
->list
);
4181 complete(&req
->done
);
4183 spin_unlock_irq(&rq
->lock
);
4190 /* Register at highest priority so that task migration (migrate_all_tasks)
4191 * happens before everything else.
4193 static struct notifier_block __devinitdata migration_notifier
= {
4194 .notifier_call
= migration_call
,
4198 int __init
migration_init(void)
4200 void *cpu
= (void *)(long)smp_processor_id();
4201 /* Start one for boot CPU. */
4202 migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
4203 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
4204 register_cpu_notifier(&migration_notifier
);
4210 * The 'big kernel lock'
4212 * This spinlock is taken and released recursively by lock_kernel()
4213 * and unlock_kernel(). It is transparently dropped and reaquired
4214 * over schedule(). It is used to protect legacy code that hasn't
4215 * been migrated to a proper locking design yet.
4217 * Don't use in new code.
4219 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4221 spinlock_t kernel_flag __cacheline_aligned_in_smp
= SPIN_LOCK_UNLOCKED
;
4222 EXPORT_SYMBOL(kernel_flag
);
4225 /* Attach the domain 'sd' to 'cpu' as its base domain */
4226 static void cpu_attach_domain(struct sched_domain
*sd
, int cpu
)
4228 migration_req_t req
;
4229 unsigned long flags
;
4230 runqueue_t
*rq
= cpu_rq(cpu
);
4235 spin_lock_irqsave(&rq
->lock
, flags
);
4237 if (cpu
== smp_processor_id() || !cpu_online(cpu
)) {
4240 init_completion(&req
.done
);
4241 req
.type
= REQ_SET_DOMAIN
;
4243 list_add(&req
.list
, &rq
->migration_queue
);
4247 spin_unlock_irqrestore(&rq
->lock
, flags
);
4250 wake_up_process(rq
->migration_thread
);
4251 wait_for_completion(&req
.done
);
4254 unlock_cpu_hotplug();
4258 * To enable disjoint top-level NUMA domains, define SD_NODES_PER_DOMAIN
4259 * in arch code. That defines the number of nearby nodes in a node's top
4260 * level scheduling domain.
4262 #if defined(CONFIG_NUMA) && defined(SD_NODES_PER_DOMAIN)
4264 * find_next_best_node - find the next node to include in a sched_domain
4265 * @node: node whose sched_domain we're building
4266 * @used_nodes: nodes already in the sched_domain
4268 * Find the next node to include in a given scheduling domain. Simply
4269 * finds the closest node not already in the @used_nodes map.
4271 * Should use nodemask_t.
4273 static int __init
find_next_best_node(int node
, unsigned long *used_nodes
)
4275 int i
, n
, val
, min_val
, best_node
= 0;
4279 for (i
= 0; i
< numnodes
; i
++) {
4280 /* Start at @node */
4281 n
= (node
+ i
) % numnodes
;
4283 /* Skip already used nodes */
4284 if (test_bit(n
, used_nodes
))
4287 /* Simple min distance search */
4288 val
= node_distance(node
, i
);
4290 if (val
< min_val
) {
4296 set_bit(best_node
, used_nodes
);
4301 * sched_domain_node_span - get a cpumask for a node's sched_domain
4302 * @node: node whose cpumask we're constructing
4303 * @size: number of nodes to include in this span
4305 * Given a node, construct a good cpumask for its sched_domain to span. It
4306 * should be one that prevents unnecessary balancing, but also spreads tasks
4309 cpumask_t __init
sched_domain_node_span(int node
)
4313 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
4316 bitmap_zero(used_nodes
, MAX_NUMNODES
);
4318 for (i
= 0; i
< SD_NODES_PER_DOMAIN
; i
++) {
4319 int next_node
= find_next_best_node(node
, used_nodes
);
4322 nodemask
= node_to_cpumask(next_node
);
4323 cpus_or(span
, span
, nodemask
);
4328 #else /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4329 cpumask_t __init
sched_domain_node_span(int node
)
4331 return cpu_possible_map
;
4333 #endif /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4335 #ifdef CONFIG_SCHED_SMT
4336 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
4337 static struct sched_group sched_group_cpus
[NR_CPUS
];
4338 __init
static int cpu_to_cpu_group(int cpu
)
4344 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
4345 static struct sched_group sched_group_phys
[NR_CPUS
];
4346 __init
static int cpu_to_phys_group(int cpu
)
4348 #ifdef CONFIG_SCHED_SMT
4349 return first_cpu(cpu_sibling_map
[cpu
]);
4357 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
4358 static struct sched_group sched_group_nodes
[MAX_NUMNODES
];
4359 __init
static int cpu_to_node_group(int cpu
)
4361 return cpu_to_node(cpu
);
4365 /* Groups for isolated scheduling domains */
4366 static struct sched_group sched_group_isolated
[NR_CPUS
];
4368 /* cpus with isolated domains */
4369 cpumask_t __initdata cpu_isolated_map
= CPU_MASK_NONE
;
4371 __init
static int cpu_to_isolated_group(int cpu
)
4376 /* Setup the mask of cpus configured for isolated domains */
4377 static int __init
isolated_cpu_setup(char *str
)
4379 int ints
[NR_CPUS
], i
;
4381 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
4382 cpus_clear(cpu_isolated_map
);
4383 for (i
= 1; i
<= ints
[0]; i
++)
4384 cpu_set(ints
[i
], cpu_isolated_map
);
4388 __setup ("isolcpus=", isolated_cpu_setup
);
4391 * init_sched_build_groups takes an array of groups, the cpumask we wish
4392 * to span, and a pointer to a function which identifies what group a CPU
4393 * belongs to. The return value of group_fn must be a valid index into the
4394 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4395 * keep track of groups covered with a cpumask_t).
4397 * init_sched_build_groups will build a circular linked list of the groups
4398 * covered by the given span, and will set each group's ->cpumask correctly,
4399 * and ->cpu_power to 0.
4401 __init
static void init_sched_build_groups(struct sched_group groups
[],
4402 cpumask_t span
, int (*group_fn
)(int cpu
))
4404 struct sched_group
*first
= NULL
, *last
= NULL
;
4405 cpumask_t covered
= CPU_MASK_NONE
;
4408 for_each_cpu_mask(i
, span
) {
4409 int group
= group_fn(i
);
4410 struct sched_group
*sg
= &groups
[group
];
4413 if (cpu_isset(i
, covered
))
4416 sg
->cpumask
= CPU_MASK_NONE
;
4419 for_each_cpu_mask(j
, span
) {
4420 if (group_fn(j
) != group
)
4423 cpu_set(j
, covered
);
4424 cpu_set(j
, sg
->cpumask
);
4435 __init
static void arch_init_sched_domains(void)
4438 cpumask_t cpu_default_map
;
4441 * Setup mask for cpus without special case scheduling requirements.
4442 * For now this just excludes isolated cpus, but could be used to
4443 * exclude other special cases in the future.
4445 cpus_complement(cpu_default_map
, cpu_isolated_map
);
4446 cpus_and(cpu_default_map
, cpu_default_map
, cpu_possible_map
);
4448 /* Set up domains */
4451 struct sched_domain
*sd
= NULL
, *p
;
4452 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
4454 cpus_and(nodemask
, nodemask
, cpu_default_map
);
4457 * Set up isolated domains.
4458 * Unlike those of other cpus, the domains and groups are
4459 * single level, and span a single cpu.
4461 if (cpu_isset(i
, cpu_isolated_map
)) {
4462 #ifdef CONFIG_SCHED_SMT
4463 sd
= &per_cpu(cpu_domains
, i
);
4465 sd
= &per_cpu(phys_domains
, i
);
4467 group
= cpu_to_isolated_group(i
);
4469 cpu_set(i
, sd
->span
);
4470 sd
->balance_interval
= INT_MAX
; /* Don't balance */
4471 sd
->flags
= 0; /* Avoid WAKE_ */
4472 sd
->groups
= &sched_group_isolated
[group
];
4473 printk(KERN_INFO
"Setting up cpu %d isolated.\n", i
);
4474 /* Single level, so continue with next cpu */
4479 sd
= &per_cpu(node_domains
, i
);
4480 group
= cpu_to_node_group(i
);
4482 /* FIXME: should be multilevel, in arch code */
4483 sd
->span
= sched_domain_node_span(i
);
4484 cpus_and(sd
->span
, sd
->span
, cpu_default_map
);
4485 sd
->groups
= &sched_group_nodes
[group
];
4489 sd
= &per_cpu(phys_domains
, i
);
4490 group
= cpu_to_phys_group(i
);
4493 sd
->span
= nodemask
;
4495 sd
->span
= cpu_possible_map
;
4498 sd
->groups
= &sched_group_phys
[group
];
4500 #ifdef CONFIG_SCHED_SMT
4502 sd
= &per_cpu(cpu_domains
, i
);
4503 group
= cpu_to_cpu_group(i
);
4504 *sd
= SD_SIBLING_INIT
;
4505 sd
->span
= cpu_sibling_map
[i
];
4506 cpus_and(sd
->span
, sd
->span
, cpu_default_map
);
4508 sd
->groups
= &sched_group_cpus
[group
];
4512 #ifdef CONFIG_SCHED_SMT
4513 /* Set up CPU (sibling) groups */
4515 cpumask_t this_sibling_map
= cpu_sibling_map
[i
];
4516 cpus_and(this_sibling_map
, this_sibling_map
, cpu_default_map
);
4517 if (i
!= first_cpu(this_sibling_map
))
4520 init_sched_build_groups(sched_group_cpus
, this_sibling_map
,
4525 /* Set up isolated groups */
4526 for_each_cpu_mask(i
, cpu_isolated_map
) {
4530 init_sched_build_groups(sched_group_isolated
, mask
,
4531 &cpu_to_isolated_group
);
4535 /* Set up physical groups */
4536 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
4537 cpumask_t nodemask
= node_to_cpumask(i
);
4539 cpus_and(nodemask
, nodemask
, cpu_default_map
);
4540 if (cpus_empty(nodemask
))
4543 init_sched_build_groups(sched_group_phys
, nodemask
,
4544 &cpu_to_phys_group
);
4547 init_sched_build_groups(sched_group_phys
, cpu_possible_map
,
4548 &cpu_to_phys_group
);
4552 /* Set up node groups */
4553 init_sched_build_groups(sched_group_nodes
, cpu_default_map
,
4554 &cpu_to_node_group
);
4557 /* Calculate CPU power for physical packages and nodes */
4558 for_each_cpu_mask(i
, cpu_default_map
) {
4560 struct sched_domain
*sd
;
4561 #ifdef CONFIG_SCHED_SMT
4562 sd
= &per_cpu(cpu_domains
, i
);
4563 power
= SCHED_LOAD_SCALE
;
4564 sd
->groups
->cpu_power
= power
;
4567 sd
= &per_cpu(phys_domains
, i
);
4568 power
= SCHED_LOAD_SCALE
+ SCHED_LOAD_SCALE
*
4569 (cpus_weight(sd
->groups
->cpumask
)-1) / 10;
4570 sd
->groups
->cpu_power
= power
;
4573 if (i
== first_cpu(sd
->groups
->cpumask
)) {
4574 /* Only add "power" once for each physical package. */
4575 sd
= &per_cpu(node_domains
, i
);
4576 sd
->groups
->cpu_power
+= power
;
4581 /* Attach the domains */
4583 struct sched_domain
*sd
;
4584 #ifdef CONFIG_SCHED_SMT
4585 sd
= &per_cpu(cpu_domains
, i
);
4587 sd
= &per_cpu(phys_domains
, i
);
4589 cpu_attach_domain(sd
, i
);
4593 #undef SCHED_DOMAIN_DEBUG
4594 #ifdef SCHED_DOMAIN_DEBUG
4595 void sched_domain_debug(void)
4600 runqueue_t
*rq
= cpu_rq(i
);
4601 struct sched_domain
*sd
;
4606 printk(KERN_DEBUG
"CPU%d: %s\n",
4607 i
, (cpu_online(i
) ? " online" : "offline"));
4612 struct sched_group
*group
= sd
->groups
;
4613 cpumask_t groupmask
;
4615 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
4616 cpus_clear(groupmask
);
4619 for (j
= 0; j
< level
+ 1; j
++)
4621 printk("domain %d: span %s\n", level
, str
);
4623 if (!cpu_isset(i
, sd
->span
))
4624 printk(KERN_DEBUG
"ERROR domain->span does not contain CPU%d\n", i
);
4625 if (!cpu_isset(i
, group
->cpumask
))
4626 printk(KERN_DEBUG
"ERROR domain->groups does not contain CPU%d\n", i
);
4627 if (!group
->cpu_power
)
4628 printk(KERN_DEBUG
"ERROR domain->cpu_power not set\n");
4631 for (j
= 0; j
< level
+ 2; j
++)
4636 printk(" ERROR: NULL");
4640 if (!cpus_weight(group
->cpumask
))
4641 printk(" ERROR empty group:");
4643 if (cpus_intersects(groupmask
, group
->cpumask
))
4644 printk(" ERROR repeated CPUs:");
4646 cpus_or(groupmask
, groupmask
, group
->cpumask
);
4648 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
4651 group
= group
->next
;
4652 } while (group
!= sd
->groups
);
4655 if (!cpus_equal(sd
->span
, groupmask
))
4656 printk(KERN_DEBUG
"ERROR groups don't span domain->span\n");
4662 if (!cpus_subset(groupmask
, sd
->span
))
4663 printk(KERN_DEBUG
"ERROR parent span is not a superset of domain->span\n");
4670 #define sched_domain_debug() {}
4673 void __init
sched_init_smp(void)
4675 arch_init_sched_domains();
4676 sched_domain_debug();
4679 void __init
sched_init_smp(void)
4682 #endif /* CONFIG_SMP */
4684 int in_sched_functions(unsigned long addr
)
4686 /* Linker adds these: start and end of __sched functions */
4687 extern char __sched_text_start
[], __sched_text_end
[];
4688 return in_lock_functions(addr
) ||
4689 (addr
>= (unsigned long)__sched_text_start
4690 && addr
< (unsigned long)__sched_text_end
);
4693 void __init
sched_init(void)
4699 /* Set up an initial dummy domain for early boot */
4700 static struct sched_domain sched_domain_init
;
4701 static struct sched_group sched_group_init
;
4703 memset(&sched_domain_init
, 0, sizeof(struct sched_domain
));
4704 sched_domain_init
.span
= CPU_MASK_ALL
;
4705 sched_domain_init
.groups
= &sched_group_init
;
4706 sched_domain_init
.last_balance
= jiffies
;
4707 sched_domain_init
.balance_interval
= INT_MAX
; /* Don't balance */
4708 sched_domain_init
.busy_factor
= 1;
4710 memset(&sched_group_init
, 0, sizeof(struct sched_group
));
4711 sched_group_init
.cpumask
= CPU_MASK_ALL
;
4712 sched_group_init
.next
= &sched_group_init
;
4713 sched_group_init
.cpu_power
= SCHED_LOAD_SCALE
;
4716 for (i
= 0; i
< NR_CPUS
; i
++) {
4717 prio_array_t
*array
;
4720 spin_lock_init(&rq
->lock
);
4721 rq
->active
= rq
->arrays
;
4722 rq
->expired
= rq
->arrays
+ 1;
4723 rq
->best_expired_prio
= MAX_PRIO
;
4726 rq
->sd
= &sched_domain_init
;
4728 rq
->active_balance
= 0;
4730 rq
->migration_thread
= NULL
;
4731 INIT_LIST_HEAD(&rq
->migration_queue
);
4733 atomic_set(&rq
->nr_iowait
, 0);
4735 for (j
= 0; j
< 2; j
++) {
4736 array
= rq
->arrays
+ j
;
4737 for (k
= 0; k
< MAX_PRIO
; k
++) {
4738 INIT_LIST_HEAD(array
->queue
+ k
);
4739 __clear_bit(k
, array
->bitmap
);
4741 // delimiter for bitsearch
4742 __set_bit(MAX_PRIO
, array
->bitmap
);
4747 * The boot idle thread does lazy MMU switching as well:
4749 atomic_inc(&init_mm
.mm_count
);
4750 enter_lazy_tlb(&init_mm
, current
);
4753 * Make us the idle thread. Technically, schedule() should not be
4754 * called from this thread, however somewhere below it might be,
4755 * but because we are the idle thread, we just pick up running again
4756 * when this runqueue becomes "idle".
4758 init_idle(current
, smp_processor_id());
4761 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4762 void __might_sleep(char *file
, int line
)
4764 #if defined(in_atomic)
4765 static unsigned long prev_jiffy
; /* ratelimiting */
4767 if ((in_atomic() || irqs_disabled()) &&
4768 system_state
== SYSTEM_RUNNING
) {
4769 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
4771 prev_jiffy
= jiffies
;
4772 printk(KERN_ERR
"Debug: sleeping function called from invalid"
4773 " context at %s:%d\n", file
, line
);
4774 printk("in_atomic():%d, irqs_disabled():%d\n",
4775 in_atomic(), irqs_disabled());
4780 EXPORT_SYMBOL(__might_sleep
);