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
21 #include <linux/module.h>
22 #include <linux/nmi.h>
23 #include <linux/init.h>
24 #include <asm/uaccess.h>
25 #include <linux/highmem.h>
26 #include <linux/smp_lock.h>
27 #include <asm/mmu_context.h>
28 #include <linux/interrupt.h>
29 #include <linux/completion.h>
30 #include <linux/kernel_stat.h>
31 #include <linux/security.h>
32 #include <linux/notifier.h>
33 #include <linux/profile.h>
34 #include <linux/suspend.h>
35 #include <linux/blkdev.h>
36 #include <linux/delay.h>
37 #include <linux/smp.h>
38 #include <linux/timer.h>
39 #include <linux/rcupdate.h>
40 #include <linux/cpu.h>
41 #include <linux/percpu.h>
42 #include <linux/kthread.h>
43 #include <linux/seq_file.h>
44 #include <linux/syscalls.h>
45 #include <linux/times.h>
46 #include <linux/vserver/sched.h>
47 #include <linux/vs_base.h>
48 #include <linux/vs_context.h>
49 #include <linux/vs_cvirt.h>
52 #include <asm/unistd.h>
53 #include <linux/vs_context.h>
54 #include <linux/vs_cvirt.h>
55 #include <linux/vs_sched.h>
58 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
60 #define cpu_to_node_mask(cpu) (cpu_online_map)
63 /* used to soft spin in sched while dump is in progress */
64 unsigned long dump_oncpu;
65 EXPORT_SYMBOL(dump_oncpu);
68 * Convert user-nice values [ -20 ... 0 ... 19 ]
69 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
72 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
73 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
74 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
77 * 'User priority' is the nice value converted to something we
78 * can work with better when scaling various scheduler parameters,
79 * it's a [ 0 ... 39 ] range.
81 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
82 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
83 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
86 * Some helpers for converting nanosecond timing to jiffy resolution
88 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
89 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
92 * These are the 'tuning knobs' of the scheduler:
94 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
95 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
96 * Timeslices get refilled after they expire.
98 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
99 #define DEF_TIMESLICE (100 * HZ / 1000)
100 #define ON_RUNQUEUE_WEIGHT 30
101 #define CHILD_PENALTY 95
102 #define PARENT_PENALTY 100
103 #define EXIT_WEIGHT 3
104 #define PRIO_BONUS_RATIO 25
105 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
106 #define INTERACTIVE_DELTA 2
107 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
108 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
109 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
110 #define CREDIT_LIMIT 100
113 * If a task is 'interactive' then we reinsert it in the active
114 * array after it has expired its current timeslice. (it will not
115 * continue to run immediately, it will still roundrobin with
116 * other interactive tasks.)
118 * This part scales the interactivity limit depending on niceness.
120 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
121 * Here are a few examples of different nice levels:
123 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
124 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
125 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
126 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
127 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
129 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
130 * priority range a task can explore, a value of '1' means the
131 * task is rated interactive.)
133 * Ie. nice +19 tasks can never get 'interactive' enough to be
134 * reinserted into the active array. And only heavily CPU-hog nice -20
135 * tasks will be expired. Default nice 0 tasks are somewhere between,
136 * it takes some effort for them to get interactive, but it's not
140 #define CURRENT_BONUS(p) \
141 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
145 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
146 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
149 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
150 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
153 #define SCALE(v1,v1_max,v2_max) \
154 (v1) * (v2_max) / (v1_max)
157 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
159 #define TASK_INTERACTIVE(p) \
160 ((p)->prio <= (p)->static_prio - DELTA(p))
162 #define INTERACTIVE_SLEEP(p) \
163 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
164 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
166 #define HIGH_CREDIT(p) \
167 ((p)->interactive_credit > CREDIT_LIMIT)
169 #define LOW_CREDIT(p) \
170 ((p)->interactive_credit < -CREDIT_LIMIT)
172 #ifdef CONFIG_CKRM_CPU_SCHEDULE
174 * if belong to different class, compare class priority
175 * otherwise compare task priority
177 #define TASK_PREEMPTS_CURR(p, rq) \
178 ( ((p)->cpu_class != (rq)->curr->cpu_class) \
179 && ((rq)->curr != (rq)->idle) && ((p) != (rq)->idle )) \
180 ? class_preempts_curr((p),(rq)->curr) \
181 : ((p)->prio < (rq)->curr->prio)
183 #define TASK_PREEMPTS_CURR(p, rq) \
184 ((p)->prio < (rq)->curr->prio)
188 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
189 * to time slice values: [800ms ... 100ms ... 5ms]
191 * The higher a thread's priority, the bigger timeslices
192 * it gets during one round of execution. But even the lowest
193 * priority thread gets MIN_TIMESLICE worth of execution time.
196 #define SCALE_PRIO(x, prio) \
197 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
199 unsigned int task_timeslice(task_t *p)
201 if (p->static_prio < NICE_TO_PRIO(0))
202 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
204 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
206 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
207 < (long long) (sd)->cache_hot_time)
210 * These are the runqueue data structures:
213 typedef struct runqueue runqueue_t;
214 #include <linux/ckrm_classqueue.h>
215 #include <linux/ckrm_sched.h>
218 * This is the main, per-CPU runqueue data structure.
220 * Locking rule: those places that want to lock multiple runqueues
221 * (such as the load balancing or the thread migration code), lock
222 * acquire operations must be ordered by ascending &runqueue.
228 * nr_running and cpu_load should be in the same cacheline because
229 * remote CPUs use both these fields when doing load calculation.
231 unsigned long nr_running;
233 unsigned long cpu_load;
235 unsigned long long nr_switches;
238 * This is part of a global counter where only the total sum
239 * over all CPUs matters. A task can increase this counter on
240 * one CPU and if it got migrated afterwards it may decrease
241 * it on another CPU. Always updated under the runqueue lock:
243 unsigned long nr_uninterruptible;
245 unsigned long expired_timestamp;
246 unsigned long long timestamp_last_tick;
248 struct mm_struct *prev_mm;
249 #ifdef CONFIG_CKRM_CPU_SCHEDULE
250 struct classqueue_struct classqueue;
251 ckrm_load_t ckrm_load;
253 prio_array_t *active, *expired, arrays[2];
255 int best_expired_prio;
259 struct sched_domain *sd;
261 /* For active balancing */
265 task_t *migration_thread;
266 struct list_head migration_queue;
268 #ifdef CONFIG_VSERVER_HARDCPU
269 struct list_head hold_queue;
273 #ifdef CONFIG_SCHEDSTATS
275 struct sched_info rq_sched_info;
277 /* sys_sched_yield() stats */
278 unsigned long yld_exp_empty;
279 unsigned long yld_act_empty;
280 unsigned long yld_both_empty;
281 unsigned long yld_cnt;
283 /* schedule() stats */
284 unsigned long sched_noswitch;
285 unsigned long sched_switch;
286 unsigned long sched_cnt;
287 unsigned long sched_goidle;
289 /* pull_task() stats */
290 unsigned long pt_gained[MAX_IDLE_TYPES];
291 unsigned long pt_lost[MAX_IDLE_TYPES];
293 /* active_load_balance() stats */
294 unsigned long alb_cnt;
295 unsigned long alb_lost;
296 unsigned long alb_gained;
297 unsigned long alb_failed;
299 /* try_to_wake_up() stats */
300 unsigned long ttwu_cnt;
301 unsigned long ttwu_attempts;
302 unsigned long ttwu_moved;
304 /* wake_up_new_task() stats */
305 unsigned long wunt_cnt;
306 unsigned long wunt_moved;
308 /* sched_migrate_task() stats */
309 unsigned long smt_cnt;
311 /* sched_balance_exec() stats */
312 unsigned long sbe_cnt;
316 static DEFINE_PER_CPU(struct runqueue, runqueues);
318 #define for_each_domain(cpu, domain) \
319 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
321 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
322 #define this_rq() (&__get_cpu_var(runqueues))
323 #define task_rq(p) cpu_rq(task_cpu(p))
324 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
327 * Default context-switch locking:
329 #ifndef prepare_arch_switch
330 # define prepare_arch_switch(rq, next) do { } while (0)
331 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
332 # define task_running(rq, p) ((rq)->curr == (p))
336 * task_rq_lock - lock the runqueue a given task resides on and disable
337 * interrupts. Note the ordering: we can safely lookup the task_rq without
338 * explicitly disabling preemption.
340 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
346 local_irq_save(*flags);
348 spin_lock(&rq->lock);
349 if (unlikely(rq != task_rq(p))) {
350 spin_unlock_irqrestore(&rq->lock, *flags);
351 goto repeat_lock_task;
356 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
359 spin_unlock_irqrestore(&rq->lock, *flags);
362 #ifdef CONFIG_SCHEDSTATS
364 * bump this up when changing the output format or the meaning of an existing
365 * format, so that tools can adapt (or abort)
367 #define SCHEDSTAT_VERSION 10
369 static int show_schedstat(struct seq_file *seq, void *v)
372 enum idle_type itype;
374 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
375 seq_printf(seq, "timestamp %lu\n", jiffies);
376 for_each_online_cpu(cpu) {
377 runqueue_t *rq = cpu_rq(cpu);
379 struct sched_domain *sd;
383 /* runqueue-specific stats */
385 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
386 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
387 cpu, rq->yld_both_empty,
388 rq->yld_act_empty, rq->yld_exp_empty,
389 rq->yld_cnt, rq->sched_noswitch,
390 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
391 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
393 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
394 rq->wunt_cnt, rq->wunt_moved,
395 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
396 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
398 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES; itype++)
399 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
401 seq_printf(seq, "\n");
404 /* domain-specific stats */
405 for_each_domain(cpu, sd) {
406 char mask_str[NR_CPUS];
408 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
409 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
410 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
412 seq_printf(seq, " %lu %lu %lu %lu %lu",
414 sd->lb_failed[itype],
415 sd->lb_imbalance[itype],
416 sd->lb_nobusyq[itype],
417 sd->lb_nobusyg[itype]);
419 seq_printf(seq, " %lu %lu %lu %lu\n",
420 sd->sbe_pushed, sd->sbe_attempts,
421 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
428 static int schedstat_open(struct inode *inode, struct file *file)
430 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
431 char *buf = kmalloc(size, GFP_KERNEL);
437 res = single_open(file, show_schedstat, NULL);
439 m = file->private_data;
447 struct file_operations proc_schedstat_operations = {
448 .open = schedstat_open,
451 .release = single_release,
454 # define schedstat_inc(rq, field) rq->field++;
455 # define schedstat_add(rq, field, amt) rq->field += amt;
456 #else /* !CONFIG_SCHEDSTATS */
457 # define schedstat_inc(rq, field) do { } while (0);
458 # define schedstat_add(rq, field, amt) do { } while (0);
462 * rq_lock - lock a given runqueue and disable interrupts.
464 static runqueue_t *this_rq_lock(void)
471 spin_lock(&rq->lock);
476 static inline void rq_unlock(runqueue_t *rq)
479 spin_unlock_irq(&rq->lock);
482 #ifdef CONFIG_SCHEDSTATS
484 * Called when a process is dequeued from the active array and given
485 * the cpu. We should note that with the exception of interactive
486 * tasks, the expired queue will become the active queue after the active
487 * queue is empty, without explicitly dequeuing and requeuing tasks in the
488 * expired queue. (Interactive tasks may be requeued directly to the
489 * active queue, thus delaying tasks in the expired queue from running;
490 * see scheduler_tick()).
492 * This function is only called from sched_info_arrive(), rather than
493 * dequeue_task(). Even though a task may be queued and dequeued multiple
494 * times as it is shuffled about, we're really interested in knowing how
495 * long it was from the *first* time it was queued to the time that it
498 static inline void sched_info_dequeued(task_t *t)
500 t->sched_info.last_queued = 0;
504 * Called when a task finally hits the cpu. We can now calculate how
505 * long it was waiting to run. We also note when it began so that we
506 * can keep stats on how long its timeslice is.
508 static inline void sched_info_arrive(task_t *t)
510 unsigned long now = jiffies, diff = 0;
511 struct runqueue *rq = task_rq(t);
513 if (t->sched_info.last_queued)
514 diff = now - t->sched_info.last_queued;
515 sched_info_dequeued(t);
516 t->sched_info.run_delay += diff;
517 t->sched_info.last_arrival = now;
518 t->sched_info.pcnt++;
523 rq->rq_sched_info.run_delay += diff;
524 rq->rq_sched_info.pcnt++;
528 * Called when a process is queued into either the active or expired
529 * array. The time is noted and later used to determine how long we
530 * had to wait for us to reach the cpu. Since the expired queue will
531 * become the active queue after active queue is empty, without dequeuing
532 * and requeuing any tasks, we are interested in queuing to either. It
533 * is unusual but not impossible for tasks to be dequeued and immediately
534 * requeued in the same or another array: this can happen in sched_yield(),
535 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
538 * This function is only called from enqueue_task(), but also only updates
539 * the timestamp if it is already not set. It's assumed that
540 * sched_info_dequeued() will clear that stamp when appropriate.
542 static inline void sched_info_queued(task_t *t)
544 if (!t->sched_info.last_queued)
545 t->sched_info.last_queued = jiffies;
549 * Called when a process ceases being the active-running process, either
550 * voluntarily or involuntarily. Now we can calculate how long we ran.
552 static inline void sched_info_depart(task_t *t)
554 struct runqueue *rq = task_rq(t);
555 unsigned long diff = jiffies - t->sched_info.last_arrival;
557 t->sched_info.cpu_time += diff;
560 rq->rq_sched_info.cpu_time += diff;
564 * Called when tasks are switched involuntarily due, typically, to expiring
565 * their time slice. (This may also be called when switching to or from
566 * the idle task.) We are only called when prev != next.
568 static inline void sched_info_switch(task_t *prev, task_t *next)
570 struct runqueue *rq = task_rq(prev);
573 * prev now departs the cpu. It's not interesting to record
574 * stats about how efficient we were at scheduling the idle
577 if (prev != rq->idle)
578 sched_info_depart(prev);
580 if (next != rq->idle)
581 sched_info_arrive(next);
584 #define sched_info_queued(t) do { } while (0)
585 #define sched_info_switch(t, next) do { } while (0)
586 #endif /* CONFIG_SCHEDSTATS */
588 #ifdef CONFIG_CKRM_CPU_SCHEDULE
589 static inline ckrm_lrq_t *rq_get_next_class(struct runqueue *rq)
591 cq_node_t *node = classqueue_get_head(&rq->classqueue);
592 return ((node) ? class_list_entry(node) : NULL);
596 * return the cvt of the current running class
597 * if no current running class, return 0
598 * assume cpu is valid (cpu_online(cpu) == 1)
600 CVT_t get_local_cur_cvt(int cpu)
602 ckrm_lrq_t * lrq = rq_get_next_class(cpu_rq(cpu));
605 return lrq->local_cvt;
610 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
613 struct task_struct *next;
616 int cpu = smp_processor_id();
618 // it is guaranteed be the ( rq->nr_running > 0 ) check in
619 // schedule that a task will be found.
622 queue = rq_get_next_class(rq);
625 array = queue->active;
626 if (unlikely(!array->nr_active)) {
627 queue->active = queue->expired;
628 queue->expired = array;
629 queue->expired_timestamp = 0;
631 schedstat_inc(rq, sched_switch);
632 if (queue->active->nr_active)
633 set_top_priority(queue,
634 find_first_bit(queue->active->bitmap, MAX_PRIO));
636 classqueue_dequeue(queue->classqueue,
637 &queue->classqueue_linkobj);
638 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
640 goto retry_next_class;
642 schedstat_inc(rq, sched_noswitch);
643 // BUG_ON(!array->nr_active);
645 idx = queue->top_priority;
646 // BUG_ON (idx == MAX_PRIO);
647 next = task_list_entry(array->queue[idx].next);
650 #else /*! CONFIG_CKRM_CPU_SCHEDULE*/
651 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
654 struct list_head *queue;
658 if (unlikely(!array->nr_active)) {
660 * Switch the active and expired arrays.
662 schedstat_inc(rq, sched_switch);
663 rq->active = rq->expired;
666 rq->expired_timestamp = 0;
667 rq->best_expired_prio = MAX_PRIO;
669 schedstat_inc(rq, sched_noswitch);
671 idx = sched_find_first_bit(array->bitmap);
672 queue = array->queue + idx;
673 return list_entry(queue->next, task_t, run_list);
676 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
677 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
678 static inline void init_cpu_classes(void) { }
679 #define rq_ckrm_load(rq) NULL
680 static inline void ckrm_sched_tick(int j,int this_cpu,void* name) {}
681 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
684 * Adding/removing a task to/from a priority array:
686 static void dequeue_task(struct task_struct *p, prio_array_t *array)
689 list_del(&p->run_list);
690 if (list_empty(array->queue + p->prio))
691 __clear_bit(p->prio, array->bitmap);
692 class_dequeue_task(p,array);
695 static void enqueue_task(struct task_struct *p, prio_array_t *array)
697 sched_info_queued(p);
698 list_add_tail(&p->run_list, array->queue + p->prio);
699 __set_bit(p->prio, array->bitmap);
702 class_enqueue_task(p,array);
706 * Used by the migration code - we pull tasks from the head of the
707 * remote queue so we want these tasks to show up at the head of the
710 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
712 list_add(&p->run_list, array->queue + p->prio);
713 __set_bit(p->prio, array->bitmap);
716 class_enqueue_task(p,array);
720 * effective_prio - return the priority that is based on the static
721 * priority but is modified by bonuses/penalties.
723 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
724 * into the -5 ... 0 ... +5 bonus/penalty range.
726 * We use 25% of the full 0...39 priority range so that:
728 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
729 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
731 * Both properties are important to certain workloads.
733 static int effective_prio(task_t *p)
740 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
742 prio = p->static_prio - bonus;
743 #ifdef CONFIG_VSERVER_HARDCPU
744 if (task_vx_flags(p, VXF_SCHED_PRIO, 0))
745 prio += effective_vavavoom(p, MAX_USER_PRIO);
747 if (prio < MAX_RT_PRIO)
749 if (prio > MAX_PRIO-1)
755 * __activate_task - move a task to the runqueue.
757 static inline void __activate_task(task_t *p, runqueue_t *rq)
759 enqueue_task(p, rq_active(p,rq));
764 * __activate_idle_task - move idle task to the _front_ of runqueue.
766 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
768 enqueue_task_head(p, rq_active(p,rq));
772 static void recalc_task_prio(task_t *p, unsigned long long now)
774 unsigned long long __sleep_time = now - p->timestamp;
775 unsigned long sleep_time;
777 if (__sleep_time > NS_MAX_SLEEP_AVG)
778 sleep_time = NS_MAX_SLEEP_AVG;
780 sleep_time = (unsigned long)__sleep_time;
782 if (likely(sleep_time > 0)) {
784 * User tasks that sleep a long time are categorised as
785 * idle and will get just interactive status to stay active &
786 * prevent them suddenly becoming cpu hogs and starving
789 if (p->mm && p->activated != -1 &&
790 sleep_time > INTERACTIVE_SLEEP(p)) {
791 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
794 p->interactive_credit++;
797 * The lower the sleep avg a task has the more
798 * rapidly it will rise with sleep time.
800 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
803 * Tasks with low interactive_credit are limited to
804 * one timeslice worth of sleep avg bonus.
807 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
808 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
811 * Non high_credit tasks waking from uninterruptible
812 * sleep are limited in their sleep_avg rise as they
813 * are likely to be cpu hogs waiting on I/O
815 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
816 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
818 else if (p->sleep_avg + sleep_time >=
819 INTERACTIVE_SLEEP(p)) {
820 p->sleep_avg = INTERACTIVE_SLEEP(p);
826 * This code gives a bonus to interactive tasks.
828 * The boost works by updating the 'average sleep time'
829 * value here, based on ->timestamp. The more time a
830 * task spends sleeping, the higher the average gets -
831 * and the higher the priority boost gets as well.
833 p->sleep_avg += sleep_time;
835 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
836 p->sleep_avg = NS_MAX_SLEEP_AVG;
838 p->interactive_credit++;
843 p->prio = effective_prio(p);
847 * activate_task - move a task to the runqueue and do priority recalculation
849 * Update all the scheduling statistics stuff. (sleep average
850 * calculation, priority modifiers, etc.)
852 static void activate_task(task_t *p, runqueue_t *rq, int local)
854 unsigned long long now;
859 /* Compensate for drifting sched_clock */
860 runqueue_t *this_rq = this_rq();
861 now = (now - this_rq->timestamp_last_tick)
862 + rq->timestamp_last_tick;
866 recalc_task_prio(p, now);
869 * This checks to make sure it's not an uninterruptible task
870 * that is now waking up.
874 * Tasks which were woken up by interrupts (ie. hw events)
875 * are most likely of interactive nature. So we give them
876 * the credit of extending their sleep time to the period
877 * of time they spend on the runqueue, waiting for execution
878 * on a CPU, first time around:
884 * Normal first-time wakeups get a credit too for
885 * on-runqueue time, but it will be weighted down:
893 __activate_task(p, rq);
897 * deactivate_task - remove a task from the runqueue.
899 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
902 dequeue_task(p, p->array);
908 void deactivate_task(struct task_struct *p, runqueue_t *rq)
910 vx_deactivate_task(p);
911 __deactivate_task(p, rq);
915 * resched_task - mark a task 'to be rescheduled now'.
917 * On UP this means the setting of the need_resched flag, on SMP it
918 * might also involve a cross-CPU call to trigger the scheduler on
922 static void resched_task(task_t *p)
924 int need_resched, nrpolling;
926 BUG_ON(!spin_is_locked(&task_rq(p)->lock));
928 /* minimise the chance of sending an interrupt to poll_idle() */
929 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
930 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
931 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
933 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
934 smp_send_reschedule(task_cpu(p));
937 static inline void resched_task(task_t *p)
939 set_tsk_need_resched(p);
944 * task_curr - is this task currently executing on a CPU?
945 * @p: the task in question.
947 inline int task_curr(const task_t *p)
949 return cpu_curr(task_cpu(p)) == p;
959 struct list_head list;
960 enum request_type type;
962 /* For REQ_MOVE_TASK */
966 /* For REQ_SET_DOMAIN */
967 struct sched_domain *sd;
969 struct completion done;
973 * The task's runqueue lock must be held.
974 * Returns true if you have to wait for migration thread.
976 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
978 runqueue_t *rq = task_rq(p);
981 * If the task is not on a runqueue (and not running), then
982 * it is sufficient to simply update the task's cpu field.
984 if (!p->array && !task_running(rq, p)) {
985 set_task_cpu(p, dest_cpu);
989 init_completion(&req->done);
990 req->type = REQ_MOVE_TASK;
992 req->dest_cpu = dest_cpu;
993 list_add(&req->list, &rq->migration_queue);
998 * wait_task_inactive - wait for a thread to unschedule.
1000 * The caller must ensure that the task *will* unschedule sometime soon,
1001 * else this function might spin for a *long* time. This function can't
1002 * be called with interrupts off, or it may introduce deadlock with
1003 * smp_call_function() if an IPI is sent by the same process we are
1004 * waiting to become inactive.
1006 void wait_task_inactive(task_t * p)
1008 unsigned long flags;
1013 rq = task_rq_lock(p, &flags);
1014 /* Must be off runqueue entirely, not preempted. */
1015 if (unlikely(p->array)) {
1016 /* If it's preempted, we yield. It could be a while. */
1017 preempted = !task_running(rq, p);
1018 task_rq_unlock(rq, &flags);
1024 task_rq_unlock(rq, &flags);
1028 * kick_process - kick a running thread to enter/exit the kernel
1029 * @p: the to-be-kicked thread
1031 * Cause a process which is running on another CPU to enter
1032 * kernel-mode, without any delay. (to get signals handled.)
1034 void kick_process(task_t *p)
1040 if ((cpu != smp_processor_id()) && task_curr(p))
1041 smp_send_reschedule(cpu);
1046 * Return a low guess at the load of a migration-source cpu.
1048 * We want to under-estimate the load of migration sources, to
1049 * balance conservatively.
1051 static inline unsigned long source_load(int cpu)
1053 runqueue_t *rq = cpu_rq(cpu);
1054 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1056 return min(rq->cpu_load, load_now);
1060 * Return a high guess at the load of a migration-target cpu
1062 static inline unsigned long target_load(int cpu)
1064 runqueue_t *rq = cpu_rq(cpu);
1065 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1067 return max(rq->cpu_load, load_now);
1073 * wake_idle() is useful especially on SMT architectures to wake a
1074 * task onto an idle sibling if we would otherwise wake it onto a
1077 * Returns the CPU we should wake onto.
1079 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1080 static int wake_idle(int cpu, task_t *p)
1083 runqueue_t *rq = cpu_rq(cpu);
1084 struct sched_domain *sd;
1091 if (!(sd->flags & SD_WAKE_IDLE))
1094 cpus_and(tmp, sd->span, p->cpus_allowed);
1096 for_each_cpu_mask(i, tmp) {
1104 static inline int wake_idle(int cpu, task_t *p)
1111 * try_to_wake_up - wake up a thread
1112 * @p: the to-be-woken-up thread
1113 * @state: the mask of task states that can be woken
1114 * @sync: do a synchronous wakeup?
1116 * Put it on the run-queue if it's not already there. The "current"
1117 * thread is always on the run-queue (except when the actual
1118 * re-schedule is in progress), and as such you're allowed to do
1119 * the simpler "current->state = TASK_RUNNING" to mark yourself
1120 * runnable without the overhead of this.
1122 * returns failure only if the task is already active.
1124 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1126 int cpu, this_cpu, success = 0;
1127 unsigned long flags;
1131 unsigned long load, this_load;
1132 struct sched_domain *sd;
1136 rq = task_rq_lock(p, &flags);
1137 schedstat_inc(rq, ttwu_cnt);
1138 old_state = p->state;
1139 if (!(old_state & state))
1146 this_cpu = smp_processor_id();
1149 if (unlikely(task_running(rq, p)))
1154 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1157 load = source_load(cpu);
1158 this_load = target_load(this_cpu);
1161 * If sync wakeup then subtract the (maximum possible) effect of
1162 * the currently running task from the load of the current CPU:
1165 this_load -= SCHED_LOAD_SCALE;
1167 /* Don't pull the task off an idle CPU to a busy one */
1168 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1171 new_cpu = this_cpu; /* Wake to this CPU if we can */
1174 * Scan domains for affine wakeup and passive balancing
1177 for_each_domain(this_cpu, sd) {
1178 unsigned int imbalance;
1180 * Start passive balancing when half the imbalance_pct
1183 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1185 if ((sd->flags & SD_WAKE_AFFINE) &&
1186 !task_hot(p, rq->timestamp_last_tick, sd)) {
1188 * This domain has SD_WAKE_AFFINE and p is cache cold
1191 if (cpu_isset(cpu, sd->span)) {
1192 schedstat_inc(sd, ttwu_wake_affine);
1195 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1196 imbalance*this_load <= 100*load) {
1198 * This domain has SD_WAKE_BALANCE and there is
1201 if (cpu_isset(cpu, sd->span)) {
1202 schedstat_inc(sd, ttwu_wake_balance);
1208 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1210 schedstat_inc(rq, ttwu_attempts);
1211 new_cpu = wake_idle(new_cpu, p);
1212 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
1213 schedstat_inc(rq, ttwu_moved);
1214 set_task_cpu(p, new_cpu);
1215 task_rq_unlock(rq, &flags);
1216 /* might preempt at this point */
1217 rq = task_rq_lock(p, &flags);
1218 old_state = p->state;
1219 if (!(old_state & state))
1224 this_cpu = smp_processor_id();
1229 #endif /* CONFIG_SMP */
1230 if (old_state == TASK_UNINTERRUPTIBLE) {
1231 rq->nr_uninterruptible--;
1233 * Tasks on involuntary sleep don't earn
1234 * sleep_avg beyond just interactive state.
1240 * Sync wakeups (i.e. those types of wakeups where the waker
1241 * has indicated that it will leave the CPU in short order)
1242 * don't trigger a preemption, if the woken up task will run on
1243 * this cpu. (in this case the 'I will reschedule' promise of
1244 * the waker guarantees that the freshly woken up task is going
1245 * to be considered on this CPU.)
1247 activate_task(p, rq, cpu == this_cpu);
1248 /* this is to get the accounting behind the load update */
1249 if (old_state == TASK_UNINTERRUPTIBLE)
1250 vx_uninterruptible_dec(p);
1251 if (!sync || cpu != this_cpu) {
1252 if (TASK_PREEMPTS_CURR(p, rq))
1253 resched_task(rq->curr);
1258 p->state = TASK_RUNNING;
1260 task_rq_unlock(rq, &flags);
1265 int fastcall wake_up_process(task_t * p)
1267 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1268 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1271 EXPORT_SYMBOL(wake_up_process);
1273 int fastcall wake_up_state(task_t *p, unsigned int state)
1275 return try_to_wake_up(p, state, 0);
1279 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1280 struct sched_domain *sd);
1284 * Perform scheduler related setup for a newly forked process p.
1285 * p is forked by current.
1287 void fastcall sched_fork(task_t *p)
1290 * We mark the process as running here, but have not actually
1291 * inserted it onto the runqueue yet. This guarantees that
1292 * nobody will actually run it, and a signal or other external
1293 * event cannot wake it up and insert it on the runqueue either.
1295 p->state = TASK_RUNNING;
1296 INIT_LIST_HEAD(&p->run_list);
1298 spin_lock_init(&p->switch_lock);
1299 #ifdef CONFIG_SCHEDSTATS
1300 memset(&p->sched_info, 0, sizeof(p->sched_info));
1302 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1303 cpu_demand_event(&p->demand_stat,CPU_DEMAND_INIT,0);
1305 #ifdef CONFIG_PREEMPT
1307 * During context-switch we hold precisely one spinlock, which
1308 * schedule_tail drops. (in the common case it's this_rq()->lock,
1309 * but it also can be p->switch_lock.) So we compensate with a count
1310 * of 1. Also, we want to start with kernel preemption disabled.
1312 p->thread_info->preempt_count = 1;
1315 * Share the timeslice between parent and child, thus the
1316 * total amount of pending timeslices in the system doesn't change,
1317 * resulting in more scheduling fairness.
1319 local_irq_disable();
1320 p->time_slice = (current->time_slice + 1) >> 1;
1322 * The remainder of the first timeslice might be recovered by
1323 * the parent if the child exits early enough.
1325 p->first_time_slice = 1;
1326 current->time_slice >>= 1;
1327 p->timestamp = sched_clock();
1328 if (unlikely(!current->time_slice)) {
1330 * This case is rare, it happens when the parent has only
1331 * a single jiffy left from its timeslice. Taking the
1332 * runqueue lock is not a problem.
1334 current->time_slice = 1;
1336 scheduler_tick(0, 0);
1344 * wake_up_new_task - wake up a newly created task for the first time.
1346 * This function will do some initial scheduler statistics housekeeping
1347 * that must be done for every newly created context, then puts the task
1348 * on the runqueue and wakes it.
1350 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1352 unsigned long flags;
1354 runqueue_t *rq, *this_rq;
1356 rq = task_rq_lock(p, &flags);
1358 this_cpu = smp_processor_id();
1360 BUG_ON(p->state != TASK_RUNNING);
1362 schedstat_inc(rq, wunt_cnt);
1364 * We decrease the sleep average of forking parents
1365 * and children as well, to keep max-interactive tasks
1366 * from forking tasks that are max-interactive. The parent
1367 * (current) is done further down, under its lock.
1369 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1370 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1372 p->interactive_credit = 0;
1374 p->prio = effective_prio(p);
1376 vx_activate_task(p);
1377 if (likely(cpu == this_cpu)) {
1378 if (!(clone_flags & CLONE_VM)) {
1380 * The VM isn't cloned, so we're in a good position to
1381 * do child-runs-first in anticipation of an exec. This
1382 * usually avoids a lot of COW overhead.
1384 if (unlikely(!current->array))
1385 __activate_task(p, rq);
1387 p->prio = current->prio;
1388 list_add_tail(&p->run_list, ¤t->run_list);
1389 p->array = current->array;
1390 p->array->nr_active++;
1392 class_enqueue_task(p,p->array);
1396 /* Run child last */
1397 __activate_task(p, rq);
1399 * We skip the following code due to cpu == this_cpu
1401 * task_rq_unlock(rq, &flags);
1402 * this_rq = task_rq_lock(current, &flags);
1406 this_rq = cpu_rq(this_cpu);
1409 * Not the local CPU - must adjust timestamp. This should
1410 * get optimised away in the !CONFIG_SMP case.
1412 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1413 + rq->timestamp_last_tick;
1414 __activate_task(p, rq);
1415 if (TASK_PREEMPTS_CURR(p, rq))
1416 resched_task(rq->curr);
1418 schedstat_inc(rq, wunt_moved);
1420 * Parent and child are on different CPUs, now get the
1421 * parent runqueue to update the parent's ->sleep_avg:
1423 task_rq_unlock(rq, &flags);
1424 this_rq = task_rq_lock(current, &flags);
1426 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1427 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1428 task_rq_unlock(this_rq, &flags);
1432 * Potentially available exiting-child timeslices are
1433 * retrieved here - this way the parent does not get
1434 * penalized for creating too many threads.
1436 * (this cannot be used to 'generate' timeslices
1437 * artificially, because any timeslice recovered here
1438 * was given away by the parent in the first place.)
1440 void fastcall sched_exit(task_t * p)
1442 unsigned long flags;
1446 * If the child was a (relative-) CPU hog then decrease
1447 * the sleep_avg of the parent as well.
1449 rq = task_rq_lock(p->parent, &flags);
1450 if (p->first_time_slice) {
1451 p->parent->time_slice += p->time_slice;
1452 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1453 p->parent->time_slice = task_timeslice(p);
1455 if (p->sleep_avg < p->parent->sleep_avg)
1456 p->parent->sleep_avg = p->parent->sleep_avg /
1457 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1459 task_rq_unlock(rq, &flags);
1463 * finish_task_switch - clean up after a task-switch
1464 * @prev: the thread we just switched away from.
1466 * We enter this with the runqueue still locked, and finish_arch_switch()
1467 * will unlock it along with doing any other architecture-specific cleanup
1470 * Note that we may have delayed dropping an mm in context_switch(). If
1471 * so, we finish that here outside of the runqueue lock. (Doing it
1472 * with the lock held can cause deadlocks; see schedule() for
1475 static void finish_task_switch(task_t *prev)
1476 __releases(rq->lock)
1478 runqueue_t *rq = this_rq();
1479 struct mm_struct *mm = rq->prev_mm;
1480 unsigned long prev_task_flags;
1485 * A task struct has one reference for the use as "current".
1486 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1487 * calls schedule one last time. The schedule call will never return,
1488 * and the scheduled task must drop that reference.
1489 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1490 * still held, otherwise prev could be scheduled on another cpu, die
1491 * there before we look at prev->state, and then the reference would
1493 * Manfred Spraul <manfred@colorfullife.com>
1495 prev_task_flags = prev->flags;
1496 finish_arch_switch(rq, prev);
1499 if (unlikely(prev_task_flags & PF_DEAD))
1500 put_task_struct(prev);
1504 * schedule_tail - first thing a freshly forked thread must call.
1505 * @prev: the thread we just switched away from.
1507 asmlinkage void schedule_tail(task_t *prev)
1508 __releases(rq->lock)
1510 finish_task_switch(prev);
1512 if (current->set_child_tid)
1513 put_user(current->pid, current->set_child_tid);
1517 * context_switch - switch to the new MM and the new
1518 * thread's register state.
1521 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1523 struct mm_struct *mm = next->mm;
1524 struct mm_struct *oldmm = prev->active_mm;
1526 if (unlikely(!mm)) {
1527 next->active_mm = oldmm;
1528 atomic_inc(&oldmm->mm_count);
1529 enter_lazy_tlb(oldmm, next);
1531 switch_mm(oldmm, mm, next);
1533 if (unlikely(!prev->mm)) {
1534 prev->active_mm = NULL;
1535 WARN_ON(rq->prev_mm);
1536 rq->prev_mm = oldmm;
1539 /* Here we just switch the register state and the stack. */
1540 switch_to(prev, next, prev);
1546 * nr_running, nr_uninterruptible and nr_context_switches:
1548 * externally visible scheduler statistics: current number of runnable
1549 * threads, current number of uninterruptible-sleeping threads, total
1550 * number of context switches performed since bootup.
1552 unsigned long nr_running(void)
1554 unsigned long i, sum = 0;
1556 for_each_online_cpu(i)
1557 sum += cpu_rq(i)->nr_running;
1562 unsigned long nr_uninterruptible(void)
1564 unsigned long i, sum = 0;
1567 sum += cpu_rq(i)->nr_uninterruptible;
1570 * Since we read the counters lockless, it might be slightly
1571 * inaccurate. Do not allow it to go below zero though:
1573 if (unlikely((long)sum < 0))
1579 unsigned long long nr_context_switches(void)
1581 unsigned long long i, sum = 0;
1584 sum += cpu_rq(i)->nr_switches;
1589 unsigned long nr_iowait(void)
1591 unsigned long i, sum = 0;
1594 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1602 * double_rq_lock - safely lock two runqueues
1604 * Note this does not disable interrupts like task_rq_lock,
1605 * you need to do so manually before calling.
1607 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1608 __acquires(rq1->lock)
1609 __acquires(rq2->lock)
1612 spin_lock(&rq1->lock);
1613 __acquire(rq2->lock); /* Fake it out ;) */
1616 spin_lock(&rq1->lock);
1617 spin_lock(&rq2->lock);
1619 spin_lock(&rq2->lock);
1620 spin_lock(&rq1->lock);
1626 * double_rq_unlock - safely unlock two runqueues
1628 * Note this does not restore interrupts like task_rq_unlock,
1629 * you need to do so manually after calling.
1631 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1632 __releases(rq1->lock)
1633 __releases(rq2->lock)
1635 spin_unlock(&rq1->lock);
1637 spin_unlock(&rq2->lock);
1639 __release(rq2->lock);
1643 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1645 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1646 __releases(this_rq->lock)
1647 __acquires(busiest->lock)
1648 __acquires(this_rq->lock)
1650 if (unlikely(!spin_trylock(&busiest->lock))) {
1651 if (busiest < this_rq) {
1652 spin_unlock(&this_rq->lock);
1653 spin_lock(&busiest->lock);
1654 spin_lock(&this_rq->lock);
1656 spin_lock(&busiest->lock);
1661 * find_idlest_cpu - find the least busy runqueue.
1663 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1664 struct sched_domain *sd)
1666 unsigned long load, min_load, this_load;
1671 min_load = ULONG_MAX;
1673 cpus_and(mask, sd->span, p->cpus_allowed);
1675 for_each_cpu_mask(i, mask) {
1676 load = target_load(i);
1678 if (load < min_load) {
1682 /* break out early on an idle CPU: */
1688 /* add +1 to account for the new task */
1689 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1692 * Would with the addition of the new task to the
1693 * current CPU there be an imbalance between this
1694 * CPU and the idlest CPU?
1696 * Use half of the balancing threshold - new-context is
1697 * a good opportunity to balance.
1699 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1706 * If dest_cpu is allowed for this process, migrate the task to it.
1707 * This is accomplished by forcing the cpu_allowed mask to only
1708 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1709 * the cpu_allowed mask is restored.
1711 static void sched_migrate_task(task_t *p, int dest_cpu)
1713 migration_req_t req;
1715 unsigned long flags;
1717 rq = task_rq_lock(p, &flags);
1718 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1719 || unlikely(cpu_is_offline(dest_cpu)))
1722 schedstat_inc(rq, smt_cnt);
1723 /* force the process onto the specified CPU */
1724 if (migrate_task(p, dest_cpu, &req)) {
1725 /* Need to wait for migration thread (might exit: take ref). */
1726 struct task_struct *mt = rq->migration_thread;
1727 get_task_struct(mt);
1728 task_rq_unlock(rq, &flags);
1729 wake_up_process(mt);
1730 put_task_struct(mt);
1731 wait_for_completion(&req.done);
1735 task_rq_unlock(rq, &flags);
1739 * sched_exec(): find the highest-level, exec-balance-capable
1740 * domain and try to migrate the task to the least loaded CPU.
1742 * execve() is a valuable balancing opportunity, because at this point
1743 * the task has the smallest effective memory and cache footprint.
1745 void sched_exec(void)
1747 struct sched_domain *tmp, *sd = NULL;
1748 int new_cpu, this_cpu = get_cpu();
1750 schedstat_inc(this_rq(), sbe_cnt);
1751 /* Prefer the current CPU if there's only this task running */
1752 if (this_rq()->nr_running <= 1)
1755 for_each_domain(this_cpu, tmp)
1756 if (tmp->flags & SD_BALANCE_EXEC)
1760 schedstat_inc(sd, sbe_attempts);
1761 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1762 if (new_cpu != this_cpu) {
1763 schedstat_inc(sd, sbe_pushed);
1765 sched_migrate_task(current, new_cpu);
1774 * pull_task - move a task from a remote runqueue to the local runqueue.
1775 * Both runqueues must be locked.
1778 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1779 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1781 dequeue_task(p, src_array);
1782 src_rq->nr_running--;
1783 set_task_cpu(p, this_cpu);
1784 this_rq->nr_running++;
1785 enqueue_task(p, this_array);
1786 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1787 + this_rq->timestamp_last_tick;
1789 * Note that idle threads have a prio of MAX_PRIO, for this test
1790 * to be always true for them.
1792 if (TASK_PREEMPTS_CURR(p, this_rq))
1793 resched_task(this_rq->curr);
1797 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1800 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1801 struct sched_domain *sd, enum idle_type idle)
1804 * We do not migrate tasks that are:
1805 * 1) running (obviously), or
1806 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1807 * 3) are cache-hot on their current CPU.
1809 if (task_running(rq, p))
1811 if (!cpu_isset(this_cpu, p->cpus_allowed))
1814 /* Aggressive migration if we've failed balancing */
1815 if (idle == NEWLY_IDLE ||
1816 sd->nr_balance_failed < sd->cache_nice_tries) {
1817 if (task_hot(p, rq->timestamp_last_tick, sd))
1824 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1825 static inline int ckrm_preferred_task(task_t *tmp,long min, long max,
1826 int phase, enum idle_type idle)
1828 long pressure = task_load(tmp);
1833 if ((idle == NOT_IDLE) && ! phase && (pressure <= min))
1839 * move tasks for a specic local class
1840 * return number of tasks pulled
1842 static inline int ckrm_cls_move_tasks(ckrm_lrq_t* src_lrq,ckrm_lrq_t*dst_lrq,
1843 runqueue_t *this_rq,
1844 runqueue_t *busiest,
1845 struct sched_domain *sd,
1847 enum idle_type idle,
1848 long* pressure_imbalance)
1850 prio_array_t *array, *dst_array;
1851 struct list_head *head, *curr;
1856 long pressure_min, pressure_max;
1857 /*hzheng: magic : 90% balance is enough*/
1858 long balance_min = *pressure_imbalance / 10;
1860 * we don't want to migrate tasks that will reverse the balance
1861 * or the tasks that make too small difference
1863 #define CKRM_BALANCE_MAX_RATIO 100
1864 #define CKRM_BALANCE_MIN_RATIO 1
1868 * We first consider expired tasks. Those will likely not be
1869 * executed in the near future, and they are most likely to
1870 * be cache-cold, thus switching CPUs has the least effect
1873 if (src_lrq->expired->nr_active) {
1874 array = src_lrq->expired;
1875 dst_array = dst_lrq->expired;
1877 array = src_lrq->active;
1878 dst_array = dst_lrq->active;
1882 /* Start searching at priority 0: */
1886 idx = sched_find_first_bit(array->bitmap);
1888 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1889 if (idx >= MAX_PRIO) {
1890 if (array == src_lrq->expired && src_lrq->active->nr_active) {
1891 array = src_lrq->active;
1892 dst_array = dst_lrq->active;
1895 if ((! phase) && (! pulled) && (idle != IDLE))
1896 goto start; //try again
1898 goto out; //finished search for this lrq
1901 head = array->queue + idx;
1904 tmp = list_entry(curr, task_t, run_list);
1908 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1915 pressure_min = *pressure_imbalance * CKRM_BALANCE_MIN_RATIO/100;
1916 pressure_max = *pressure_imbalance * CKRM_BALANCE_MAX_RATIO/100;
1918 * skip the tasks that will reverse the balance too much
1920 if (ckrm_preferred_task(tmp,pressure_min,pressure_max,phase,idle)) {
1921 *pressure_imbalance -= task_load(tmp);
1922 pull_task(busiest, array, tmp,
1923 this_rq, dst_array, this_cpu);
1926 if (*pressure_imbalance <= balance_min)
1938 static inline long ckrm_rq_imbalance(runqueue_t *this_rq,runqueue_t *dst_rq)
1942 * make sure after balance, imbalance' > - imbalance/2
1943 * we don't want the imbalance be reversed too much
1945 imbalance = pid_get_pressure(rq_ckrm_load(dst_rq),0)
1946 - pid_get_pressure(rq_ckrm_load(this_rq),1);
1952 * try to balance the two runqueues
1954 * Called with both runqueues locked.
1955 * if move_tasks is called, it will try to move at least one task over
1957 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1958 unsigned long max_nr_move, struct sched_domain *sd,
1959 enum idle_type idle)
1961 struct ckrm_cpu_class *clsptr,*vip_cls = NULL;
1962 ckrm_lrq_t* src_lrq,*dst_lrq;
1963 long pressure_imbalance, pressure_imbalance_old;
1964 int src_cpu = task_cpu(busiest->curr);
1965 struct list_head *list;
1969 imbalance = ckrm_rq_imbalance(this_rq,busiest);
1971 if ((idle == NOT_IDLE && imbalance <= 0) || busiest->nr_running <= 1)
1974 //try to find the vip class
1975 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1976 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1978 if (! lrq_nr_running(src_lrq))
1981 if (! vip_cls || cpu_class_weight(vip_cls) < cpu_class_weight(clsptr) )
1988 * do search from the most significant class
1989 * hopefully, less tasks will be migrated this way
1998 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1999 if (! lrq_nr_running(src_lrq))
2002 dst_lrq = get_ckrm_lrq(clsptr,this_cpu);
2004 //how much pressure for this class should be transferred
2005 pressure_imbalance = src_lrq->lrq_load * imbalance/src_lrq->local_weight;
2006 if (pulled && ! pressure_imbalance)
2009 pressure_imbalance_old = pressure_imbalance;
2013 ckrm_cls_move_tasks(src_lrq,dst_lrq,
2017 &pressure_imbalance);
2020 * hzheng: 2 is another magic number
2021 * stop balancing if the imbalance is less than 25% of the orig
2023 if (pressure_imbalance <= (pressure_imbalance_old >> 2))
2027 imbalance *= pressure_imbalance / pressure_imbalance_old;
2030 list = clsptr->links.next;
2031 if (list == &active_cpu_classes)
2033 clsptr = list_entry(list, typeof(*clsptr), links);
2034 if (clsptr != vip_cls)
2041 * ckrm_check_balance - is load balancing necessary?
2042 * return 0 if load balancing is not necessary
2043 * otherwise return the average load of the system
2044 * also, update nr_group
2047 * no load balancing if it's load is over average
2048 * no load balancing if it's load is far more than the min
2050 * read the status of all the runqueues
2052 static unsigned long ckrm_check_balance(struct sched_domain *sd, int this_cpu,
2053 enum idle_type idle, int* nr_group)
2055 struct sched_group *group = sd->groups;
2056 unsigned long min_load, max_load, avg_load;
2057 unsigned long total_load, this_load, total_pwr;
2059 max_load = this_load = total_load = total_pwr = 0;
2060 min_load = 0xFFFFFFFF;
2069 /* Tally up the load of all CPUs in the group */
2070 cpus_and(tmp, group->cpumask, cpu_online_map);
2071 if (unlikely(cpus_empty(tmp)))
2075 local_group = cpu_isset(this_cpu, group->cpumask);
2077 for_each_cpu_mask(i, tmp) {
2078 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),local_group);
2086 total_load += avg_load;
2087 total_pwr += group->cpu_power;
2089 /* Adjust by relative CPU power of the group */
2090 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2093 this_load = avg_load;
2095 } else if (avg_load > max_load) {
2096 max_load = avg_load;
2098 if (avg_load < min_load) {
2099 min_load = avg_load;
2102 group = group->next;
2103 *nr_group = *nr_group + 1;
2104 } while (group != sd->groups);
2106 if (!max_load || this_load >= max_load)
2109 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2111 /* hzheng: debugging: 105 is a magic number
2112 * 100*max_load <= sd->imbalance_pct*this_load)
2113 * should use imbalance_pct instead
2115 if (this_load > avg_load
2116 || 100*max_load < 105*this_load
2117 || 100*min_load < 70*this_load
2127 * any group that has above average load is considered busy
2128 * find the busiest queue from any of busy group
2131 ckrm_find_busy_queue(struct sched_domain *sd, int this_cpu,
2132 unsigned long avg_load, enum idle_type idle,
2135 struct sched_group *group;
2136 runqueue_t * busiest=NULL;
2140 rand = get_ckrm_rand(nr_group);
2144 unsigned long load,total_load,max_load;
2147 runqueue_t * grp_busiest;
2149 cpus_and(tmp, group->cpumask, cpu_online_map);
2150 if (unlikely(cpus_empty(tmp)))
2151 goto find_nextgroup;
2156 for_each_cpu_mask(i, tmp) {
2157 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),0);
2159 if (load > max_load) {
2161 grp_busiest = cpu_rq(i);
2165 total_load = (total_load * SCHED_LOAD_SCALE) / group->cpu_power;
2166 if (total_load > avg_load) {
2167 busiest = grp_busiest;
2168 if (nr_group >= rand)
2172 group = group->next;
2174 } while (group != sd->groups);
2180 * load_balance - pressure based load balancing algorithm used by ckrm
2182 static int ckrm_load_balance(int this_cpu, runqueue_t *this_rq,
2183 struct sched_domain *sd, enum idle_type idle)
2185 runqueue_t *busiest;
2186 unsigned long avg_load;
2187 int nr_moved,nr_group;
2189 avg_load = ckrm_check_balance(sd, this_cpu, idle, &nr_group);
2193 busiest = ckrm_find_busy_queue(sd,this_cpu,avg_load,idle,nr_group);
2197 * This should be "impossible", but since load
2198 * balancing is inherently racy and statistical,
2199 * it could happen in theory.
2201 if (unlikely(busiest == this_rq)) {
2207 if (busiest->nr_running > 1) {
2209 * Attempt to move tasks. If find_busiest_group has found
2210 * an imbalance but busiest->nr_running <= 1, the group is
2211 * still unbalanced. nr_moved simply stays zero, so it is
2212 * correctly treated as an imbalance.
2214 double_lock_balance(this_rq, busiest);
2215 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2217 spin_unlock(&busiest->lock);
2219 adjust_local_weight();
2224 sd->nr_balance_failed ++;
2226 sd->nr_balance_failed = 0;
2228 /* We were unbalanced, so reset the balancing interval */
2229 sd->balance_interval = sd->min_interval;
2234 /* tune up the balancing interval */
2235 if (sd->balance_interval < sd->max_interval)
2236 sd->balance_interval *= 2;
2242 * this_rq->lock is already held
2244 static inline int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2245 struct sched_domain *sd)
2248 read_lock(&class_list_lock);
2249 ret = ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2250 read_unlock(&class_list_lock);
2254 static inline int load_balance(int this_cpu, runqueue_t *this_rq,
2255 struct sched_domain *sd, enum idle_type idle)
2259 spin_lock(&this_rq->lock);
2260 read_lock(&class_list_lock);
2261 ret= ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2262 read_unlock(&class_list_lock);
2263 spin_unlock(&this_rq->lock);
2266 #else /*! CONFIG_CKRM_CPU_SCHEDULE */
2268 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
2269 * as part of a balancing operation within "domain". Returns the number of
2272 * Called with both runqueues locked.
2274 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
2275 unsigned long max_nr_move, struct sched_domain *sd,
2276 enum idle_type idle)
2278 prio_array_t *array, *dst_array;
2279 struct list_head *head, *curr;
2280 int idx, pulled = 0;
2283 if (max_nr_move <= 0 || busiest->nr_running <= 1)
2287 * We first consider expired tasks. Those will likely not be
2288 * executed in the near future, and they are most likely to
2289 * be cache-cold, thus switching CPUs has the least effect
2292 if (busiest->expired->nr_active) {
2293 array = busiest->expired;
2294 dst_array = this_rq->expired;
2296 array = busiest->active;
2297 dst_array = this_rq->active;
2301 /* Start searching at priority 0: */
2305 idx = sched_find_first_bit(array->bitmap);
2307 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2308 if (idx >= MAX_PRIO) {
2309 if (array == busiest->expired && busiest->active->nr_active) {
2310 array = busiest->active;
2311 dst_array = this_rq->active;
2317 head = array->queue + idx;
2320 tmp = list_entry(curr, task_t, run_list);
2324 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
2332 * Right now, this is the only place pull_task() is called,
2333 * so we can safely collect pull_task() stats here rather than
2334 * inside pull_task().
2336 schedstat_inc(this_rq, pt_gained[idle]);
2337 schedstat_inc(busiest, pt_lost[idle]);
2339 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2342 /* We only want to steal up to the prescribed number of tasks. */
2343 if (pulled < max_nr_move) {
2354 * find_busiest_group finds and returns the busiest CPU group within the
2355 * domain. It calculates and returns the number of tasks which should be
2356 * moved to restore balance via the imbalance parameter.
2358 static struct sched_group *
2359 find_busiest_group(struct sched_domain *sd, int this_cpu,
2360 unsigned long *imbalance, enum idle_type idle)
2362 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2363 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2365 max_load = this_load = total_load = total_pwr = 0;
2372 local_group = cpu_isset(this_cpu, group->cpumask);
2374 /* Tally up the load of all CPUs in the group */
2377 for_each_cpu_mask(i, group->cpumask) {
2378 /* Bias balancing toward cpus of our domain */
2380 load = target_load(i);
2382 load = source_load(i);
2391 total_load += avg_load;
2392 total_pwr += group->cpu_power;
2394 /* Adjust by relative CPU power of the group */
2395 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2398 this_load = avg_load;
2401 } else if (avg_load > max_load) {
2402 max_load = avg_load;
2406 group = group->next;
2407 } while (group != sd->groups);
2409 if (!busiest || this_load >= max_load)
2412 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2414 if (this_load >= avg_load ||
2415 100*max_load <= sd->imbalance_pct*this_load)
2419 * We're trying to get all the cpus to the average_load, so we don't
2420 * want to push ourselves above the average load, nor do we wish to
2421 * reduce the max loaded cpu below the average load, as either of these
2422 * actions would just result in more rebalancing later, and ping-pong
2423 * tasks around. Thus we look for the minimum possible imbalance.
2424 * Negative imbalances (*we* are more loaded than anyone else) will
2425 * be counted as no imbalance for these purposes -- we can't fix that
2426 * by pulling tasks to us. Be careful of negative numbers as they'll
2427 * appear as very large values with unsigned longs.
2429 *imbalance = min(max_load - avg_load, avg_load - this_load);
2431 /* How much load to actually move to equalise the imbalance */
2432 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
2435 if (*imbalance < SCHED_LOAD_SCALE - 1) {
2436 unsigned long pwr_now = 0, pwr_move = 0;
2439 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2445 * OK, we don't have enough imbalance to justify moving tasks,
2446 * however we may be able to increase total CPU power used by
2450 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2451 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2452 pwr_now /= SCHED_LOAD_SCALE;
2454 /* Amount of load we'd subtract */
2455 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2457 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2460 /* Amount of load we'd add */
2461 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2464 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2465 pwr_move /= SCHED_LOAD_SCALE;
2467 /* Move if we gain another 8th of a CPU worth of throughput */
2468 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2475 /* Get rid of the scaling factor, rounding down as we divide */
2476 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2481 if (busiest && (idle == NEWLY_IDLE ||
2482 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2492 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2494 static runqueue_t *find_busiest_queue(struct sched_group *group)
2496 unsigned long load, max_load = 0;
2497 runqueue_t *busiest = NULL;
2500 for_each_cpu_mask(i, group->cpumask) {
2501 load = source_load(i);
2503 if (load > max_load) {
2505 busiest = cpu_rq(i);
2513 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2514 * tasks if there is an imbalance.
2516 * Called with this_rq unlocked.
2518 static int load_balance(int this_cpu, runqueue_t *this_rq,
2519 struct sched_domain *sd, enum idle_type idle)
2521 struct sched_group *group;
2522 runqueue_t *busiest;
2523 unsigned long imbalance;
2526 spin_lock(&this_rq->lock);
2527 schedstat_inc(sd, lb_cnt[idle]);
2529 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2531 schedstat_inc(sd, lb_nobusyg[idle]);
2535 busiest = find_busiest_queue(group);
2537 schedstat_inc(sd, lb_nobusyq[idle]);
2542 * This should be "impossible", but since load
2543 * balancing is inherently racy and statistical,
2544 * it could happen in theory.
2546 if (unlikely(busiest == this_rq)) {
2551 schedstat_add(sd, lb_imbalance[idle], imbalance);
2554 if (busiest->nr_running > 1) {
2556 * Attempt to move tasks. If find_busiest_group has found
2557 * an imbalance but busiest->nr_running <= 1, the group is
2558 * still unbalanced. nr_moved simply stays zero, so it is
2559 * correctly treated as an imbalance.
2561 double_lock_balance(this_rq, busiest);
2562 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2563 imbalance, sd, idle);
2564 spin_unlock(&busiest->lock);
2566 spin_unlock(&this_rq->lock);
2569 schedstat_inc(sd, lb_failed[idle]);
2570 sd->nr_balance_failed++;
2572 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2575 spin_lock(&busiest->lock);
2576 if (!busiest->active_balance) {
2577 busiest->active_balance = 1;
2578 busiest->push_cpu = this_cpu;
2581 spin_unlock(&busiest->lock);
2583 wake_up_process(busiest->migration_thread);
2586 * We've kicked active balancing, reset the failure
2589 sd->nr_balance_failed = sd->cache_nice_tries;
2593 * We were unbalanced, but unsuccessful in move_tasks(),
2594 * so bump the balance_interval to lessen the lock contention.
2596 if (sd->balance_interval < sd->max_interval)
2597 sd->balance_interval++;
2599 sd->nr_balance_failed = 0;
2601 /* We were unbalanced, so reset the balancing interval */
2602 sd->balance_interval = sd->min_interval;
2608 spin_unlock(&this_rq->lock);
2610 /* tune up the balancing interval */
2611 if (sd->balance_interval < sd->max_interval)
2612 sd->balance_interval *= 2;
2618 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2619 * tasks if there is an imbalance.
2621 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2622 * this_rq is locked.
2624 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2625 struct sched_domain *sd)
2627 struct sched_group *group;
2628 runqueue_t *busiest = NULL;
2629 unsigned long imbalance;
2632 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2633 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2635 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2639 busiest = find_busiest_queue(group);
2640 if (!busiest || busiest == this_rq) {
2641 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2645 /* Attempt to move tasks */
2646 double_lock_balance(this_rq, busiest);
2648 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2649 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2650 imbalance, sd, NEWLY_IDLE);
2652 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2654 spin_unlock(&busiest->lock);
2659 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2663 * idle_balance is called by schedule() if this_cpu is about to become
2664 * idle. Attempts to pull tasks from other CPUs.
2666 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2668 struct sched_domain *sd;
2670 for_each_domain(this_cpu, sd) {
2671 if (sd->flags & SD_BALANCE_NEWIDLE) {
2672 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2673 /* We've pulled tasks over so stop searching */
2680 #ifdef CONFIG_SCHED_SMT
2681 static int cpu_and_siblings_are_idle(int cpu)
2684 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
2693 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
2698 * active_load_balance is run by migration threads. It pushes running tasks
2699 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2700 * running on each physical CPU where possible, and avoids physical /
2701 * logical imbalances.
2703 * Called with busiest_rq locked.
2705 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2707 struct sched_domain *sd;
2708 struct sched_group *cpu_group;
2709 cpumask_t visited_cpus;
2711 schedstat_inc(busiest_rq, alb_cnt);
2713 * Search for suitable CPUs to push tasks to in successively higher
2714 * domains with SD_LOAD_BALANCE set.
2716 visited_cpus = CPU_MASK_NONE;
2717 for_each_domain(busiest_cpu, sd) {
2718 if (!(sd->flags & SD_LOAD_BALANCE) || busiest_rq->nr_running <= 1)
2719 break; /* no more domains to search or no more tasks to move */
2721 cpu_group = sd->groups;
2722 do { /* sched_groups should either use list_heads or be merged into the domains structure */
2723 int cpu, target_cpu = -1;
2724 runqueue_t *target_rq;
2726 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2727 if (cpu_isset(cpu, visited_cpus) || cpu == busiest_cpu ||
2728 !cpu_and_siblings_are_idle(cpu)) {
2729 cpu_set(cpu, visited_cpus);
2735 if (target_cpu == -1)
2736 goto next_group; /* failed to find a suitable target cpu in this domain */
2738 target_rq = cpu_rq(target_cpu);
2741 * This condition is "impossible", if it occurs we need to fix it
2742 * Reported by Bjorn Helgaas on a 128-cpu setup.
2744 BUG_ON(busiest_rq == target_rq);
2746 /* move a task from busiest_rq to target_rq */
2747 double_lock_balance(busiest_rq, target_rq);
2748 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE)) {
2749 schedstat_inc(busiest_rq, alb_lost);
2750 schedstat_inc(target_rq, alb_gained);
2752 schedstat_inc(busiest_rq, alb_failed);
2754 spin_unlock(&target_rq->lock);
2756 cpu_group = cpu_group->next;
2757 } while (cpu_group != sd->groups && busiest_rq->nr_running > 1);
2762 * rebalance_tick will get called every timer tick, on every CPU.
2764 * It checks each scheduling domain to see if it is due to be balanced,
2765 * and initiates a balancing operation if so.
2767 * Balancing parameters are set up in arch_init_sched_domains.
2770 /* Don't have all balancing operations going off at once */
2771 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2773 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2774 enum idle_type idle)
2776 unsigned long old_load, this_load;
2777 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2778 struct sched_domain *sd;
2780 /* Update our load */
2781 old_load = this_rq->cpu_load;
2782 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2784 * Round up the averaging division if load is increasing. This
2785 * prevents us from getting stuck on 9 if the load is 10, for
2788 if (this_load > old_load)
2790 this_rq->cpu_load = (old_load + this_load) / 2;
2792 for_each_domain(this_cpu, sd) {
2793 unsigned long interval;
2795 if (!(sd->flags & SD_LOAD_BALANCE))
2798 interval = sd->balance_interval;
2799 if (idle != SCHED_IDLE)
2800 interval *= sd->busy_factor;
2802 /* scale ms to jiffies */
2803 interval = msecs_to_jiffies(interval);
2804 if (unlikely(!interval))
2807 if (j - sd->last_balance >= interval) {
2808 if (load_balance(this_cpu, this_rq, sd, idle)) {
2809 /* We've pulled tasks over so no longer idle */
2812 sd->last_balance += interval;
2818 * on UP we do not need to balance between CPUs:
2820 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2823 static inline void idle_balance(int cpu, runqueue_t *rq)
2828 static inline int wake_priority_sleeper(runqueue_t *rq)
2831 #ifdef CONFIG_SCHED_SMT
2832 spin_lock(&rq->lock);
2834 * If an SMT sibling task has been put to sleep for priority
2835 * reasons reschedule the idle task to see if it can now run.
2837 if (rq->nr_running) {
2838 resched_task(rq->idle);
2841 spin_unlock(&rq->lock);
2846 DEFINE_PER_CPU(struct kernel_stat, kstat);
2847 EXPORT_PER_CPU_SYMBOL(kstat);
2850 * We place interactive tasks back into the active array, if possible.
2852 * To guarantee that this does not starve expired tasks we ignore the
2853 * interactivity of a task if the first expired task had to wait more
2854 * than a 'reasonable' amount of time. This deadline timeout is
2855 * load-dependent, as the frequency of array switched decreases with
2856 * increasing number of running tasks. We also ignore the interactivity
2857 * if a better static_prio task has expired:
2860 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2861 #define EXPIRED_STARVING(rq) \
2862 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2863 (jiffies - (rq)->expired_timestamp >= \
2864 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2865 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2867 #define EXPIRED_STARVING(rq) \
2868 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2869 (jiffies - (rq)->expired_timestamp >= \
2870 STARVATION_LIMIT * (lrq_nr_running(rq)) + 1)))
2874 * This function gets called by the timer code, with HZ frequency.
2875 * We call it with interrupts disabled.
2877 * It also gets called by the fork code, when changing the parent's
2880 void scheduler_tick(int user_ticks, int sys_ticks)
2882 int cpu = smp_processor_id();
2883 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2884 runqueue_t *rq = this_rq();
2885 task_t *p = current;
2886 struct vx_info *vxi = p->vx_info;
2888 rq->timestamp_last_tick = sched_clock();
2890 if (rcu_pending(cpu))
2891 rcu_check_callbacks(cpu, user_ticks);
2894 vxi->sched.cpu[cpu].user_ticks += user_ticks;
2895 vxi->sched.cpu[cpu].sys_ticks += sys_ticks;
2898 /* note: this timer irq context must be accounted for as well */
2899 if (hardirq_count() - HARDIRQ_OFFSET) {
2900 cpustat->irq += sys_ticks;
2902 } else if (softirq_count()) {
2903 cpustat->softirq += sys_ticks;
2907 if (p == rq->idle) {
2908 if (atomic_read(&rq->nr_iowait) > 0)
2909 cpustat->iowait += sys_ticks;
2910 // vx_cpustat_acc(vxi, iowait, cpu, cpustat, sys_ticks);
2912 cpustat->idle += sys_ticks;
2913 // vx_cpustat_acc(vxi, idle, cpu, cpustat, sys_ticks);
2915 if (wake_priority_sleeper(rq))
2918 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
2920 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2921 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2924 rebalance_tick(cpu, rq, SCHED_IDLE);
2927 if (TASK_NICE(p) > 0)
2928 cpustat->nice += user_ticks;
2930 cpustat->user += user_ticks;
2931 cpustat->system += sys_ticks;
2933 /* Task might have expired already, but not scheduled off yet */
2934 if (p->array != rq_active(p,rq)) {
2935 set_tsk_need_resched(p);
2938 spin_lock(&rq->lock);
2940 * The task was running during this tick - update the
2941 * time slice counter. Note: we do not update a thread's
2942 * priority until it either goes to sleep or uses up its
2943 * timeslice. This makes it possible for interactive tasks
2944 * to use up their timeslices at their highest priority levels.
2948 * RR tasks need a special form of timeslice management.
2949 * FIFO tasks have no timeslices.
2951 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2952 p->time_slice = task_timeslice(p);
2953 p->first_time_slice = 0;
2954 set_tsk_need_resched(p);
2956 /* put it at the end of the queue: */
2957 dequeue_task(p, rq_active(p,rq));
2958 enqueue_task(p, rq_active(p,rq));
2962 #warning MEF: vx_need_resched incorpates standard kernel code, which it should not.
2963 if (vx_need_resched(p)) {
2964 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2965 /* Hubertus ... we can abstract this out */
2966 ckrm_lrq_t* rq = get_task_lrq(p);
2968 dequeue_task(p, rq->active);
2969 set_tsk_need_resched(p);
2970 p->prio = effective_prio(p);
2971 p->time_slice = task_timeslice(p);
2972 p->first_time_slice = 0;
2974 if (!rq->expired_timestamp)
2975 rq->expired_timestamp = jiffies;
2976 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2977 enqueue_task(p, rq->expired);
2978 if (p->static_prio < this_rq()->best_expired_prio)
2979 this_rq()->best_expired_prio = p->static_prio;
2981 enqueue_task(p, rq->active);
2984 * Prevent a too long timeslice allowing a task to monopolize
2985 * the CPU. We do this by splitting up the timeslice into
2988 * Note: this does not mean the task's timeslices expire or
2989 * get lost in any way, they just might be preempted by
2990 * another task of equal priority. (one with higher
2991 * priority would have preempted this task already.) We
2992 * requeue this task to the end of the list on this priority
2993 * level, which is in essence a round-robin of tasks with
2996 * This only applies to tasks in the interactive
2997 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2999 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3000 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3001 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3002 (p->array == rq_active(p,rq))) {
3004 dequeue_task(p, rq_active(p,rq));
3005 set_tsk_need_resched(p);
3006 p->prio = effective_prio(p);
3007 enqueue_task(p, rq_active(p,rq));
3011 spin_unlock(&rq->lock);
3013 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
3014 rebalance_tick(cpu, rq, NOT_IDLE);
3017 #ifdef CONFIG_SCHED_SMT
3018 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3020 struct sched_domain *sd = this_rq->sd;
3021 cpumask_t sibling_map;
3024 if (!(sd->flags & SD_SHARE_CPUPOWER))
3027 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3028 if (prev != rq->idle) {
3029 unsigned long long run = now - prev->timestamp;
3030 ckrm_lrq_t * lrq = get_task_lrq(prev);
3032 lrq->lrq_load -= task_load(prev);
3033 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3034 lrq->lrq_load += task_load(prev);
3036 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3037 update_local_cvt(prev, run);
3041 * Unlock the current runqueue because we have to lock in
3042 * CPU order to avoid deadlocks. Caller knows that we might
3043 * unlock. We keep IRQs disabled.
3045 spin_unlock(&this_rq->lock);
3047 sibling_map = sd->span;
3049 for_each_cpu_mask(i, sibling_map)
3050 spin_lock(&cpu_rq(i)->lock);
3052 * We clear this CPU from the mask. This both simplifies the
3053 * inner loop and keps this_rq locked when we exit:
3055 cpu_clear(this_cpu, sibling_map);
3057 for_each_cpu_mask(i, sibling_map) {
3058 runqueue_t *smt_rq = cpu_rq(i);
3061 * If an SMT sibling task is sleeping due to priority
3062 * reasons wake it up now.
3064 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
3065 resched_task(smt_rq->idle);
3068 for_each_cpu_mask(i, sibling_map)
3069 spin_unlock(&cpu_rq(i)->lock);
3071 * We exit with this_cpu's rq still held and IRQs
3076 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3078 struct sched_domain *sd = this_rq->sd;
3079 cpumask_t sibling_map;
3080 prio_array_t *array;
3084 if (!(sd->flags & SD_SHARE_CPUPOWER))
3088 * The same locking rules and details apply as for
3089 * wake_sleeping_dependent():
3091 spin_unlock(&this_rq->lock);
3092 sibling_map = sd->span;
3093 for_each_cpu_mask(i, sibling_map)
3094 spin_lock(&cpu_rq(i)->lock);
3095 cpu_clear(this_cpu, sibling_map);
3098 * Establish next task to be run - it might have gone away because
3099 * we released the runqueue lock above:
3101 if (!this_rq->nr_running)
3103 array = this_rq->active;
3104 if (!array->nr_active)
3105 array = this_rq->expired;
3106 BUG_ON(!array->nr_active);
3108 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
3111 for_each_cpu_mask(i, sibling_map) {
3112 runqueue_t *smt_rq = cpu_rq(i);
3113 task_t *smt_curr = smt_rq->curr;
3116 * If a user task with lower static priority than the
3117 * running task on the SMT sibling is trying to schedule,
3118 * delay it till there is proportionately less timeslice
3119 * left of the sibling task to prevent a lower priority
3120 * task from using an unfair proportion of the
3121 * physical cpu's resources. -ck
3123 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
3124 task_timeslice(p) || rt_task(smt_curr)) &&
3125 p->mm && smt_curr->mm && !rt_task(p))
3129 * Reschedule a lower priority task on the SMT sibling,
3130 * or wake it up if it has been put to sleep for priority
3133 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
3134 task_timeslice(smt_curr) || rt_task(p)) &&
3135 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
3136 (smt_curr == smt_rq->idle && smt_rq->nr_running))
3137 resched_task(smt_curr);
3140 for_each_cpu_mask(i, sibling_map)
3141 spin_unlock(&cpu_rq(i)->lock);
3145 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3149 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3156 * schedule() is the main scheduler function.
3158 asmlinkage void __sched schedule(void)
3161 task_t *prev, *next;
3163 prio_array_t *array;
3164 unsigned long long now;
3165 unsigned long run_time;
3166 #ifdef CONFIG_VSERVER_HARDCPU
3167 struct vx_info *vxi;
3173 * If crash dump is in progress, this other cpu's
3174 * need to wait until it completes.
3175 * NB: this code is optimized away for kernels without
3178 if (unlikely(dump_oncpu))
3179 goto dump_scheduling_disabled;
3182 * Test if we are atomic. Since do_exit() needs to call into
3183 * schedule() atomically, we ignore that path for now.
3184 * Otherwise, whine if we are scheduling when we should not be.
3186 if (likely(!(current->exit_state & (EXIT_DEAD | EXIT_ZOMBIE)))) {
3187 if (unlikely(in_atomic())) {
3188 printk(KERN_ERR "scheduling while atomic: "
3190 current->comm, preempt_count(), current->pid);
3194 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3199 release_kernel_lock(prev);
3200 need_resched_nonpreemptible:
3204 * The idle thread is not allowed to schedule!
3205 * Remove this check after it has been exercised a bit.
3207 if (unlikely(current == rq->idle) && current->state != TASK_RUNNING) {
3208 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3212 schedstat_inc(rq, sched_cnt);
3213 now = sched_clock();
3214 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
3215 run_time = now - prev->timestamp;
3217 run_time = NS_MAX_SLEEP_AVG;
3220 * Tasks with interactive credits get charged less run_time
3221 * at high sleep_avg to delay them losing their interactive
3224 if (HIGH_CREDIT(prev))
3225 run_time /= (CURRENT_BONUS(prev) ? : 1);
3227 spin_lock_irq(&rq->lock);
3229 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3230 if (prev != rq->idle) {
3231 unsigned long long run = now - prev->timestamp;
3232 ckrm_lrq_t * lrq = get_task_lrq(prev);
3234 lrq->lrq_load -= task_load(prev);
3235 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3236 lrq->lrq_load += task_load(prev);
3238 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3239 update_local_cvt(prev, run);
3243 if (unlikely(current->flags & PF_DEAD))
3244 current->state = EXIT_DEAD;
3246 * if entering off of a kernel preemption go straight
3247 * to picking the next task.
3249 switch_count = &prev->nivcsw;
3250 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3251 switch_count = &prev->nvcsw;
3252 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3253 unlikely(signal_pending(prev))))
3254 prev->state = TASK_RUNNING;
3256 if (prev->state == TASK_UNINTERRUPTIBLE) {
3257 rq->nr_uninterruptible++;
3258 vx_uninterruptible_inc(prev);
3260 deactivate_task(prev, rq);
3264 #ifdef CONFIG_VSERVER_HARDCPU
3265 if (!list_empty(&rq->hold_queue)) {
3266 struct list_head *l, *n;
3270 list_for_each_safe(l, n, &rq->hold_queue) {
3271 next = list_entry(l, task_t, run_list);
3272 if (vxi == next->vx_info)
3275 vxi = next->vx_info;
3276 ret = vx_tokens_recalc(vxi);
3277 // tokens = vx_tokens_avail(next);
3280 list_del(&next->run_list);
3281 next->state &= ~TASK_ONHOLD;
3284 array = rq->expired;
3285 next->prio = MAX_PRIO-1;
3286 enqueue_task(next, array);
3288 if (next->static_prio < rq->best_expired_prio)
3289 rq->best_expired_prio = next->static_prio;
3291 // printk("··· %8lu unhold %p [%d]\n", jiffies, next, next->prio);
3294 if ((ret < 0) && (maxidle < ret))
3298 rq->idle_tokens = -maxidle;
3303 cpu = smp_processor_id();
3304 if (unlikely(!rq->nr_running)) {
3306 idle_balance(cpu, rq);
3307 if (!rq->nr_running) {
3309 rq->expired_timestamp = 0;
3310 wake_sleeping_dependent(cpu, rq);
3312 * wake_sleeping_dependent() might have released
3313 * the runqueue, so break out if we got new
3316 if (!rq->nr_running)
3320 if (dependent_sleeper(cpu, rq)) {
3325 * dependent_sleeper() releases and reacquires the runqueue
3326 * lock, hence go into the idle loop if the rq went
3329 if (unlikely(!rq->nr_running))
3333 /* MEF: CKRM refactored code into rq_get_next_task(); make
3334 * sure that when upgrading changes are reflected into both
3335 * versions of the code.
3337 next = rq_get_next_task(rq);
3339 #ifdef CONFIG_VSERVER_HARDCPU
3340 vxi = next->vx_info;
3341 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3342 int ret = vx_tokens_recalc(vxi);
3344 if (unlikely(ret <= 0)) {
3345 if (ret && (rq->idle_tokens > -ret))
3346 rq->idle_tokens = -ret;
3347 __deactivate_task(next, rq);
3348 recalc_task_prio(next, now);
3349 // a new one on hold
3351 next->state |= TASK_ONHOLD;
3352 list_add_tail(&next->run_list, &rq->hold_queue);
3353 //printk("··· %8lu hold %p [%d]\n", jiffies, next, next->prio);
3359 if (!rt_task(next) && next->activated > 0) {
3360 unsigned long long delta = now - next->timestamp;
3362 if (next->activated == 1)
3363 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3365 array = next->array;
3366 dequeue_task(next, array);
3367 recalc_task_prio(next, next->timestamp + delta);
3368 enqueue_task(next, array);
3370 next->activated = 0;
3372 if (next == rq->idle)
3373 schedstat_inc(rq, sched_goidle);
3375 clear_tsk_need_resched(prev);
3376 rcu_qsctr_inc(task_cpu(prev));
3378 prev->sleep_avg -= run_time;
3379 if ((long)prev->sleep_avg <= 0) {
3380 prev->sleep_avg = 0;
3381 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
3382 prev->interactive_credit--;
3384 prev->timestamp = prev->last_ran = now;
3386 sched_info_switch(prev, next);
3387 if (likely(prev != next)) {
3388 next->timestamp = now;
3393 prepare_arch_switch(rq, next);
3394 prev = context_switch(rq, prev, next);
3397 finish_task_switch(prev);
3399 spin_unlock_irq(&rq->lock);
3402 if (unlikely(reacquire_kernel_lock(prev) < 0))
3403 goto need_resched_nonpreemptible;
3404 preempt_enable_no_resched();
3405 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3410 dump_scheduling_disabled:
3411 /* allow scheduling only if this is the dumping cpu */
3412 if (dump_oncpu != smp_processor_id()+1) {
3419 EXPORT_SYMBOL(schedule);
3420 #ifdef CONFIG_PREEMPT
3422 * this is is the entry point to schedule() from in-kernel preemption
3423 * off of preempt_enable. Kernel preemptions off return from interrupt
3424 * occur there and call schedule directly.
3426 asmlinkage void __sched preempt_schedule(void)
3428 struct thread_info *ti = current_thread_info();
3431 * If there is a non-zero preempt_count or interrupts are disabled,
3432 * we do not want to preempt the current task. Just return..
3434 if (unlikely(ti->preempt_count || irqs_disabled()))
3438 ti->preempt_count = PREEMPT_ACTIVE;
3440 ti->preempt_count = 0;
3442 /* we could miss a preemption opportunity between schedule and now */
3444 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3448 EXPORT_SYMBOL(preempt_schedule);
3449 #endif /* CONFIG_PREEMPT */
3451 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3453 task_t *p = curr->task;
3454 return try_to_wake_up(p, mode, sync);
3457 EXPORT_SYMBOL(default_wake_function);
3460 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3461 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3462 * number) then we wake all the non-exclusive tasks and one exclusive task.
3464 * There are circumstances in which we can try to wake a task which has already
3465 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3466 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3468 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3469 int nr_exclusive, int sync, void *key)
3471 struct list_head *tmp, *next;
3473 list_for_each_safe(tmp, next, &q->task_list) {
3476 curr = list_entry(tmp, wait_queue_t, task_list);
3477 flags = curr->flags;
3478 if (curr->func(curr, mode, sync, key) &&
3479 (flags & WQ_FLAG_EXCLUSIVE) &&
3486 * __wake_up - wake up threads blocked on a waitqueue.
3488 * @mode: which threads
3489 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3491 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3492 int nr_exclusive, void *key)
3494 unsigned long flags;
3496 spin_lock_irqsave(&q->lock, flags);
3497 __wake_up_common(q, mode, nr_exclusive, 0, key);
3498 spin_unlock_irqrestore(&q->lock, flags);
3501 EXPORT_SYMBOL(__wake_up);
3504 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3506 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3508 __wake_up_common(q, mode, 1, 0, NULL);
3512 * __wake_up - sync- wake up threads blocked on a waitqueue.
3514 * @mode: which threads
3515 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3517 * The sync wakeup differs that the waker knows that it will schedule
3518 * away soon, so while the target thread will be woken up, it will not
3519 * be migrated to another CPU - ie. the two threads are 'synchronized'
3520 * with each other. This can prevent needless bouncing between CPUs.
3522 * On UP it can prevent extra preemption.
3524 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3526 unsigned long flags;
3532 if (unlikely(!nr_exclusive))
3535 spin_lock_irqsave(&q->lock, flags);
3536 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3537 spin_unlock_irqrestore(&q->lock, flags);
3539 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3541 void fastcall complete(struct completion *x)
3543 unsigned long flags;
3545 spin_lock_irqsave(&x->wait.lock, flags);
3547 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3549 spin_unlock_irqrestore(&x->wait.lock, flags);
3551 EXPORT_SYMBOL(complete);
3553 void fastcall complete_all(struct completion *x)
3555 unsigned long flags;
3557 spin_lock_irqsave(&x->wait.lock, flags);
3558 x->done += UINT_MAX/2;
3559 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3561 spin_unlock_irqrestore(&x->wait.lock, flags);
3563 EXPORT_SYMBOL(complete_all);
3565 void fastcall __sched wait_for_completion(struct completion *x)
3568 spin_lock_irq(&x->wait.lock);
3570 DECLARE_WAITQUEUE(wait, current);
3572 wait.flags |= WQ_FLAG_EXCLUSIVE;
3573 __add_wait_queue_tail(&x->wait, &wait);
3575 __set_current_state(TASK_UNINTERRUPTIBLE);
3576 spin_unlock_irq(&x->wait.lock);
3578 spin_lock_irq(&x->wait.lock);
3580 __remove_wait_queue(&x->wait, &wait);
3583 spin_unlock_irq(&x->wait.lock);
3585 EXPORT_SYMBOL(wait_for_completion);
3587 #define SLEEP_ON_VAR \
3588 unsigned long flags; \
3589 wait_queue_t wait; \
3590 init_waitqueue_entry(&wait, current);
3592 #define SLEEP_ON_HEAD \
3593 spin_lock_irqsave(&q->lock,flags); \
3594 __add_wait_queue(q, &wait); \
3595 spin_unlock(&q->lock);
3597 #define SLEEP_ON_TAIL \
3598 spin_lock_irq(&q->lock); \
3599 __remove_wait_queue(q, &wait); \
3600 spin_unlock_irqrestore(&q->lock, flags);
3602 #define SLEEP_ON_BKLCHECK \
3603 if (unlikely(!kernel_locked()) && \
3604 sleep_on_bkl_warnings < 10) { \
3605 sleep_on_bkl_warnings++; \
3609 static int sleep_on_bkl_warnings;
3611 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3617 current->state = TASK_INTERRUPTIBLE;
3624 EXPORT_SYMBOL(interruptible_sleep_on);
3626 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3632 current->state = TASK_INTERRUPTIBLE;
3635 timeout = schedule_timeout(timeout);
3641 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3643 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3649 current->state = TASK_UNINTERRUPTIBLE;
3652 timeout = schedule_timeout(timeout);
3658 EXPORT_SYMBOL(sleep_on_timeout);
3660 void set_user_nice(task_t *p, long nice)
3662 unsigned long flags;
3663 prio_array_t *array;
3665 int old_prio, new_prio, delta;
3667 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3670 * We have to be careful, if called from sys_setpriority(),
3671 * the task might be in the middle of scheduling on another CPU.
3673 rq = task_rq_lock(p, &flags);
3675 * The RT priorities are set via setscheduler(), but we still
3676 * allow the 'normal' nice value to be set - but as expected
3677 * it wont have any effect on scheduling until the task is
3681 p->static_prio = NICE_TO_PRIO(nice);
3686 dequeue_task(p, array);
3689 new_prio = NICE_TO_PRIO(nice);
3690 delta = new_prio - old_prio;
3691 p->static_prio = NICE_TO_PRIO(nice);
3695 enqueue_task(p, array);
3697 * If the task increased its priority or is running and
3698 * lowered its priority, then reschedule its CPU:
3700 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3701 resched_task(rq->curr);
3704 task_rq_unlock(rq, &flags);
3707 EXPORT_SYMBOL(set_user_nice);
3709 #ifdef __ARCH_WANT_SYS_NICE
3712 * sys_nice - change the priority of the current process.
3713 * @increment: priority increment
3715 * sys_setpriority is a more generic, but much slower function that
3716 * does similar things.
3718 asmlinkage long sys_nice(int increment)
3724 * Setpriority might change our priority at the same moment.
3725 * We don't have to worry. Conceptually one call occurs first
3726 * and we have a single winner.
3728 if (increment < 0) {
3729 if (vx_flags(VXF_IGNEG_NICE, 0))
3731 if (!capable(CAP_SYS_NICE))
3733 if (increment < -40)
3739 nice = PRIO_TO_NICE(current->static_prio) + increment;
3745 retval = security_task_setnice(current, nice);
3749 set_user_nice(current, nice);
3756 * task_prio - return the priority value of a given task.
3757 * @p: the task in question.
3759 * This is the priority value as seen by users in /proc.
3760 * RT tasks are offset by -200. Normal tasks are centered
3761 * around 0, value goes from -16 to +15.
3763 int task_prio(const task_t *p)
3765 return p->prio - MAX_RT_PRIO;
3769 * task_nice - return the nice value of a given task.
3770 * @p: the task in question.
3772 int task_nice(const task_t *p)
3774 return TASK_NICE(p);
3778 * idle_cpu - is a given cpu idle currently?
3779 * @cpu: the processor in question.
3781 int idle_cpu(int cpu)
3783 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3786 EXPORT_SYMBOL_GPL(idle_cpu);
3789 * find_process_by_pid - find a process with a matching PID value.
3790 * @pid: the pid in question.
3792 static inline task_t *find_process_by_pid(pid_t pid)
3794 return pid ? find_task_by_pid(pid) : current;
3797 /* Actually do priority change: must hold rq lock. */
3798 static void __setscheduler(struct task_struct *p, int policy, int prio)
3802 p->rt_priority = prio;
3803 if (policy != SCHED_NORMAL)
3804 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3806 p->prio = p->static_prio;
3810 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3812 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3814 struct sched_param lp;
3815 int retval = -EINVAL;
3816 int oldprio, oldpolicy = -1;
3817 prio_array_t *array;
3818 unsigned long flags;
3822 if (!param || pid < 0)
3826 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3830 * We play safe to avoid deadlocks.
3832 read_lock_irq(&tasklist_lock);
3834 p = find_process_by_pid(pid);
3840 /* double check policy once rq lock held */
3842 policy = oldpolicy = p->policy;
3845 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3846 policy != SCHED_NORMAL)
3850 * Valid priorities for SCHED_FIFO and SCHED_RR are
3851 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3854 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3856 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3860 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3861 !capable(CAP_SYS_NICE))
3863 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3864 !capable(CAP_SYS_NICE))
3867 retval = security_task_setscheduler(p, policy, &lp);
3871 * To be able to change p->policy safely, the apropriate
3872 * runqueue lock must be held.
3874 rq = task_rq_lock(p, &flags);
3875 /* recheck policy now with rq lock held */
3876 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3877 policy = oldpolicy = -1;
3878 task_rq_unlock(rq, &flags);
3883 deactivate_task(p, task_rq(p));
3886 __setscheduler(p, policy, lp.sched_priority);
3888 vx_activate_task(p);
3889 __activate_task(p, task_rq(p));
3891 * Reschedule if we are currently running on this runqueue and
3892 * our priority decreased, or if we are not currently running on
3893 * this runqueue and our priority is higher than the current's
3895 if (task_running(rq, p)) {
3896 if (p->prio > oldprio)
3897 resched_task(rq->curr);
3898 } else if (TASK_PREEMPTS_CURR(p, rq))
3899 resched_task(rq->curr);
3901 task_rq_unlock(rq, &flags);
3903 read_unlock_irq(&tasklist_lock);
3909 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3910 * @pid: the pid in question.
3911 * @policy: new policy
3912 * @param: structure containing the new RT priority.
3914 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3915 struct sched_param __user *param)
3917 return setscheduler(pid, policy, param);
3921 * sys_sched_setparam - set/change the RT priority of a thread
3922 * @pid: the pid in question.
3923 * @param: structure containing the new RT priority.
3925 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3927 return setscheduler(pid, -1, param);
3931 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3932 * @pid: the pid in question.
3934 asmlinkage long sys_sched_getscheduler(pid_t pid)
3936 int retval = -EINVAL;
3943 read_lock(&tasklist_lock);
3944 p = find_process_by_pid(pid);
3946 retval = security_task_getscheduler(p);
3950 read_unlock(&tasklist_lock);
3957 * sys_sched_getscheduler - get the RT priority of a thread
3958 * @pid: the pid in question.
3959 * @param: structure containing the RT priority.
3961 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3963 struct sched_param lp;
3964 int retval = -EINVAL;
3967 if (!param || pid < 0)
3970 read_lock(&tasklist_lock);
3971 p = find_process_by_pid(pid);
3976 retval = security_task_getscheduler(p);
3980 lp.sched_priority = p->rt_priority;
3981 read_unlock(&tasklist_lock);
3984 * This one might sleep, we cannot do it with a spinlock held ...
3986 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3992 read_unlock(&tasklist_lock);
3996 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4002 read_lock(&tasklist_lock);
4004 p = find_process_by_pid(pid);
4006 read_unlock(&tasklist_lock);
4007 unlock_cpu_hotplug();
4012 * It is not safe to call set_cpus_allowed with the
4013 * tasklist_lock held. We will bump the task_struct's
4014 * usage count and then drop tasklist_lock.
4017 read_unlock(&tasklist_lock);
4020 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4021 !capable(CAP_SYS_NICE))
4024 retval = set_cpus_allowed(p, new_mask);
4028 unlock_cpu_hotplug();
4032 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4033 cpumask_t *new_mask)
4035 if (len < sizeof(cpumask_t)) {
4036 memset(new_mask, 0, sizeof(cpumask_t));
4037 } else if (len > sizeof(cpumask_t)) {
4038 len = sizeof(cpumask_t);
4040 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4044 * sys_sched_setaffinity - set the cpu affinity of a process
4045 * @pid: pid of the process
4046 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4047 * @user_mask_ptr: user-space pointer to the new cpu mask
4049 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4050 unsigned long __user *user_mask_ptr)
4055 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4059 return sched_setaffinity(pid, new_mask);
4063 * Represents all cpu's present in the system
4064 * In systems capable of hotplug, this map could dynamically grow
4065 * as new cpu's are detected in the system via any platform specific
4066 * method, such as ACPI for e.g.
4069 cpumask_t cpu_present_map;
4070 EXPORT_SYMBOL(cpu_present_map);
4073 cpumask_t cpu_online_map = CPU_MASK_ALL;
4074 cpumask_t cpu_possible_map = CPU_MASK_ALL;
4077 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4083 read_lock(&tasklist_lock);
4086 p = find_process_by_pid(pid);
4091 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
4094 read_unlock(&tasklist_lock);
4095 unlock_cpu_hotplug();
4103 * sys_sched_getaffinity - get the cpu affinity of a process
4104 * @pid: pid of the process
4105 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4106 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4108 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4109 unsigned long __user *user_mask_ptr)
4114 if (len < sizeof(cpumask_t))
4117 ret = sched_getaffinity(pid, &mask);
4121 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4124 return sizeof(cpumask_t);
4128 * sys_sched_yield - yield the current processor to other threads.
4130 * this function yields the current CPU by moving the calling thread
4131 * to the expired array. If there are no other threads running on this
4132 * CPU then this function will return.
4134 asmlinkage long sys_sched_yield(void)
4136 runqueue_t *rq = this_rq_lock();
4137 prio_array_t *array = current->array;
4138 prio_array_t *target = rq_expired(current,rq);
4140 schedstat_inc(rq, yld_cnt);
4142 * We implement yielding by moving the task into the expired
4145 * (special rule: RT tasks will just roundrobin in the active
4148 if (rt_task(current))
4149 target = rq_active(current,rq);
4151 #warning MEF need to fix up SCHEDSTATS code, but I hope this is fixed by the 2.6.10 CKRM patch
4152 #ifdef CONFIG_SCHEDSTATS
4153 if (current->array->nr_active == 1) {
4154 schedstat_inc(rq, yld_act_empty);
4155 if (!rq->expired->nr_active)
4156 schedstat_inc(rq, yld_both_empty);
4157 } else if (!rq->expired->nr_active)
4158 schedstat_inc(rq, yld_exp_empty);
4161 dequeue_task(current, array);
4162 enqueue_task(current, target);
4165 * Since we are going to call schedule() anyway, there's
4166 * no need to preempt or enable interrupts:
4168 __release(rq->lock);
4169 _raw_spin_unlock(&rq->lock);
4170 preempt_enable_no_resched();
4177 void __sched __cond_resched(void)
4179 set_current_state(TASK_RUNNING);
4183 EXPORT_SYMBOL(__cond_resched);
4186 * yield - yield the current processor to other threads.
4188 * this is a shortcut for kernel-space yielding - it marks the
4189 * thread runnable and calls sys_sched_yield().
4191 void __sched yield(void)
4193 set_current_state(TASK_RUNNING);
4197 EXPORT_SYMBOL(yield);
4200 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4201 * that process accounting knows that this is a task in IO wait state.
4203 * But don't do that if it is a deliberate, throttling IO wait (this task
4204 * has set its backing_dev_info: the queue against which it should throttle)
4206 void __sched io_schedule(void)
4208 struct runqueue *rq = this_rq();
4210 atomic_inc(&rq->nr_iowait);
4212 atomic_dec(&rq->nr_iowait);
4215 EXPORT_SYMBOL(io_schedule);
4217 long __sched io_schedule_timeout(long timeout)
4219 struct runqueue *rq = this_rq();
4222 atomic_inc(&rq->nr_iowait);
4223 ret = schedule_timeout(timeout);
4224 atomic_dec(&rq->nr_iowait);
4229 * sys_sched_get_priority_max - return maximum RT priority.
4230 * @policy: scheduling class.
4232 * this syscall returns the maximum rt_priority that can be used
4233 * by a given scheduling class.
4235 asmlinkage long sys_sched_get_priority_max(int policy)
4242 ret = MAX_USER_RT_PRIO-1;
4252 * sys_sched_get_priority_min - return minimum RT priority.
4253 * @policy: scheduling class.
4255 * this syscall returns the minimum rt_priority that can be used
4256 * by a given scheduling class.
4258 asmlinkage long sys_sched_get_priority_min(int policy)
4274 * sys_sched_rr_get_interval - return the default timeslice of a process.
4275 * @pid: pid of the process.
4276 * @interval: userspace pointer to the timeslice value.
4278 * this syscall writes the default timeslice value of a given process
4279 * into the user-space timespec buffer. A value of '0' means infinity.
4282 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4284 int retval = -EINVAL;
4292 read_lock(&tasklist_lock);
4293 p = find_process_by_pid(pid);
4297 retval = security_task_getscheduler(p);
4301 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4302 0 : task_timeslice(p), &t);
4303 read_unlock(&tasklist_lock);
4304 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4308 read_unlock(&tasklist_lock);
4312 static inline struct task_struct *eldest_child(struct task_struct *p)
4314 if (list_empty(&p->children)) return NULL;
4315 return list_entry(p->children.next,struct task_struct,sibling);
4318 static inline struct task_struct *older_sibling(struct task_struct *p)
4320 if (p->sibling.prev==&p->parent->children) return NULL;
4321 return list_entry(p->sibling.prev,struct task_struct,sibling);
4324 static inline struct task_struct *younger_sibling(struct task_struct *p)
4326 if (p->sibling.next==&p->parent->children) return NULL;
4327 return list_entry(p->sibling.next,struct task_struct,sibling);
4330 static void show_task(task_t * p)
4334 unsigned long free = 0;
4335 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4337 printk("%-13.13s ", p->comm);
4338 state = p->state ? __ffs(p->state) + 1 : 0;
4339 if (state < ARRAY_SIZE(stat_nam))
4340 printk(stat_nam[state]);
4343 #if (BITS_PER_LONG == 32)
4344 if (state == TASK_RUNNING)
4345 printk(" running ");
4347 printk(" %08lX ", thread_saved_pc(p));
4349 if (state == TASK_RUNNING)
4350 printk(" running task ");
4352 printk(" %016lx ", thread_saved_pc(p));
4354 #ifdef CONFIG_DEBUG_STACK_USAGE
4356 unsigned long * n = (unsigned long *) (p->thread_info+1);
4359 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4362 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4363 if ((relative = eldest_child(p)))
4364 printk("%5d ", relative->pid);
4367 if ((relative = younger_sibling(p)))
4368 printk("%7d", relative->pid);
4371 if ((relative = older_sibling(p)))
4372 printk(" %5d", relative->pid);
4376 printk(" (L-TLB)\n");
4378 printk(" (NOTLB)\n");
4380 if (state != TASK_RUNNING)
4381 show_stack(p, NULL);
4384 void show_state(void)
4388 #if (BITS_PER_LONG == 32)
4391 printk(" task PC pid father child younger older\n");
4395 printk(" task PC pid father child younger older\n");
4397 read_lock(&tasklist_lock);
4398 do_each_thread(g, p) {
4400 * reset the NMI-timeout, listing all files on a slow
4401 * console might take alot of time:
4403 touch_nmi_watchdog();
4405 } while_each_thread(g, p);
4407 read_unlock(&tasklist_lock);
4410 EXPORT_SYMBOL_GPL(show_state);
4412 void __devinit init_idle(task_t *idle, int cpu)
4414 runqueue_t *rq = cpu_rq(cpu);
4415 unsigned long flags;
4417 idle->sleep_avg = 0;
4418 idle->interactive_credit = 0;
4420 idle->prio = MAX_PRIO;
4421 idle->state = TASK_RUNNING;
4422 set_task_cpu(idle, cpu);
4424 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4425 cpu_demand_event(&(idle->demand_stat),CPU_DEMAND_INIT,0);
4426 idle->cpu_class = get_default_cpu_class();
4430 spin_lock_irqsave(&rq->lock, flags);
4431 rq->curr = rq->idle = idle;
4432 set_tsk_need_resched(idle);
4433 spin_unlock_irqrestore(&rq->lock, flags);
4435 /* Set the preempt count _outside_ the spinlocks! */
4436 #ifdef CONFIG_PREEMPT
4437 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4439 idle->thread_info->preempt_count = 0;
4444 * In a system that switches off the HZ timer nohz_cpu_mask
4445 * indicates which cpus entered this state. This is used
4446 * in the rcu update to wait only for active cpus. For system
4447 * which do not switch off the HZ timer nohz_cpu_mask should
4448 * always be CPU_MASK_NONE.
4450 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4454 * This is how migration works:
4456 * 1) we queue a migration_req_t structure in the source CPU's
4457 * runqueue and wake up that CPU's migration thread.
4458 * 2) we down() the locked semaphore => thread blocks.
4459 * 3) migration thread wakes up (implicitly it forces the migrated
4460 * thread off the CPU)
4461 * 4) it gets the migration request and checks whether the migrated
4462 * task is still in the wrong runqueue.
4463 * 5) if it's in the wrong runqueue then the migration thread removes
4464 * it and puts it into the right queue.
4465 * 6) migration thread up()s the semaphore.
4466 * 7) we wake up and the migration is done.
4470 * Change a given task's CPU affinity. Migrate the thread to a
4471 * proper CPU and schedule it away if the CPU it's executing on
4472 * is removed from the allowed bitmask.
4474 * NOTE: the caller must have a valid reference to the task, the
4475 * task must not exit() & deallocate itself prematurely. The
4476 * call is not atomic; no spinlocks may be held.
4478 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4480 unsigned long flags;
4482 migration_req_t req;
4485 rq = task_rq_lock(p, &flags);
4486 if (!cpus_intersects(new_mask, cpu_online_map)) {
4491 p->cpus_allowed = new_mask;
4492 /* Can the task run on the task's current CPU? If so, we're done */
4493 if (cpu_isset(task_cpu(p), new_mask))
4496 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4497 /* Need help from migration thread: drop lock and wait. */
4498 task_rq_unlock(rq, &flags);
4499 wake_up_process(rq->migration_thread);
4500 wait_for_completion(&req.done);
4501 tlb_migrate_finish(p->mm);
4505 task_rq_unlock(rq, &flags);
4509 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4512 * Move (not current) task off this cpu, onto dest cpu. We're doing
4513 * this because either it can't run here any more (set_cpus_allowed()
4514 * away from this CPU, or CPU going down), or because we're
4515 * attempting to rebalance this task on exec (sched_exec).
4517 * So we race with normal scheduler movements, but that's OK, as long
4518 * as the task is no longer on this CPU.
4520 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4522 runqueue_t *rq_dest, *rq_src;
4524 if (unlikely(cpu_is_offline(dest_cpu)))
4527 rq_src = cpu_rq(src_cpu);
4528 rq_dest = cpu_rq(dest_cpu);
4530 double_rq_lock(rq_src, rq_dest);
4531 /* Already moved. */
4532 if (task_cpu(p) != src_cpu)
4534 /* Affinity changed (again). */
4535 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4540 * Sync timestamp with rq_dest's before activating.
4541 * The same thing could be achieved by doing this step
4542 * afterwards, and pretending it was a local activate.
4543 * This way is cleaner and logically correct.
4545 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4546 + rq_dest->timestamp_last_tick;
4547 deactivate_task(p, rq_src);
4548 set_task_cpu(p, dest_cpu);
4549 activate_task(p, rq_dest, 0);
4550 if (TASK_PREEMPTS_CURR(p, rq_dest))
4551 resched_task(rq_dest->curr);
4553 set_task_cpu(p, dest_cpu);
4556 double_rq_unlock(rq_src, rq_dest);
4560 * migration_thread - this is a highprio system thread that performs
4561 * thread migration by bumping thread off CPU then 'pushing' onto
4564 static int migration_thread(void * data)
4567 int cpu = (long)data;
4570 BUG_ON(rq->migration_thread != current);
4572 set_current_state(TASK_INTERRUPTIBLE);
4573 while (!kthread_should_stop()) {
4574 struct list_head *head;
4575 migration_req_t *req;
4577 if (current->flags & PF_FREEZE)
4578 refrigerator(PF_FREEZE);
4580 spin_lock_irq(&rq->lock);
4582 if (cpu_is_offline(cpu)) {
4583 spin_unlock_irq(&rq->lock);
4587 if (rq->active_balance) {
4588 active_load_balance(rq, cpu);
4589 rq->active_balance = 0;
4592 head = &rq->migration_queue;
4594 if (list_empty(head)) {
4595 spin_unlock_irq(&rq->lock);
4597 set_current_state(TASK_INTERRUPTIBLE);
4600 req = list_entry(head->next, migration_req_t, list);
4601 list_del_init(head->next);
4603 if (req->type == REQ_MOVE_TASK) {
4604 spin_unlock(&rq->lock);
4605 __migrate_task(req->task, smp_processor_id(),
4608 } else if (req->type == REQ_SET_DOMAIN) {
4610 spin_unlock_irq(&rq->lock);
4612 spin_unlock_irq(&rq->lock);
4616 complete(&req->done);
4618 __set_current_state(TASK_RUNNING);
4622 /* Wait for kthread_stop */
4623 set_current_state(TASK_INTERRUPTIBLE);
4624 while (!kthread_should_stop()) {
4626 set_current_state(TASK_INTERRUPTIBLE);
4628 __set_current_state(TASK_RUNNING);
4632 #ifdef CONFIG_HOTPLUG_CPU
4633 /* Figure out where task on dead CPU should go, use force if neccessary. */
4634 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4640 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4641 cpus_and(mask, mask, tsk->cpus_allowed);
4642 dest_cpu = any_online_cpu(mask);
4644 /* On any allowed CPU? */
4645 if (dest_cpu == NR_CPUS)
4646 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4648 /* No more Mr. Nice Guy. */
4649 if (dest_cpu == NR_CPUS) {
4650 cpus_setall(tsk->cpus_allowed);
4651 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4654 * Don't tell them about moving exiting tasks or
4655 * kernel threads (both mm NULL), since they never
4658 if (tsk->mm && printk_ratelimit())
4659 printk(KERN_INFO "process %d (%s) no "
4660 "longer affine to cpu%d\n",
4661 tsk->pid, tsk->comm, dead_cpu);
4663 __migrate_task(tsk, dead_cpu, dest_cpu);
4667 * While a dead CPU has no uninterruptible tasks queued at this point,
4668 * it might still have a nonzero ->nr_uninterruptible counter, because
4669 * for performance reasons the counter is not stricly tracking tasks to
4670 * their home CPUs. So we just add the counter to another CPU's counter,
4671 * to keep the global sum constant after CPU-down:
4673 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4675 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4676 unsigned long flags;
4678 local_irq_save(flags);
4679 double_rq_lock(rq_src, rq_dest);
4680 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4681 rq_src->nr_uninterruptible = 0;
4682 double_rq_unlock(rq_src, rq_dest);
4683 local_irq_restore(flags);
4686 /* Run through task list and migrate tasks from the dead cpu. */
4687 static void migrate_live_tasks(int src_cpu)
4689 struct task_struct *tsk, *t;
4691 write_lock_irq(&tasklist_lock);
4693 do_each_thread(t, tsk) {
4697 if (task_cpu(tsk) == src_cpu)
4698 move_task_off_dead_cpu(src_cpu, tsk);
4699 } while_each_thread(t, tsk);
4701 write_unlock_irq(&tasklist_lock);
4704 /* Schedules idle task to be the next runnable task on current CPU.
4705 * It does so by boosting its priority to highest possible and adding it to
4706 * the _front_ of runqueue. Used by CPU offline code.
4708 void sched_idle_next(void)
4710 int cpu = smp_processor_id();
4711 runqueue_t *rq = this_rq();
4712 struct task_struct *p = rq->idle;
4713 unsigned long flags;
4715 /* cpu has to be offline */
4716 BUG_ON(cpu_online(cpu));
4718 /* Strictly not necessary since rest of the CPUs are stopped by now
4719 * and interrupts disabled on current cpu.
4721 spin_lock_irqsave(&rq->lock, flags);
4723 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4724 /* Add idle task to _front_ of it's priority queue */
4725 __activate_idle_task(p, rq);
4727 spin_unlock_irqrestore(&rq->lock, flags);
4730 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4732 struct runqueue *rq = cpu_rq(dead_cpu);
4734 /* Must be exiting, otherwise would be on tasklist. */
4735 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4737 /* Cannot have done final schedule yet: would have vanished. */
4738 BUG_ON(tsk->flags & PF_DEAD);
4740 get_task_struct(tsk);
4743 * Drop lock around migration; if someone else moves it,
4744 * that's OK. No task can be added to this CPU, so iteration is
4747 spin_unlock_irq(&rq->lock);
4748 move_task_off_dead_cpu(dead_cpu, tsk);
4749 spin_lock_irq(&rq->lock);
4751 put_task_struct(tsk);
4754 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4755 static void migrate_dead_tasks(unsigned int dead_cpu)
4758 struct runqueue *rq = cpu_rq(dead_cpu);
4760 for (arr = 0; arr < 2; arr++) {
4761 for (i = 0; i < MAX_PRIO; i++) {
4762 struct list_head *list = &rq->arrays[arr].queue[i];
4763 while (!list_empty(list))
4764 migrate_dead(dead_cpu,
4765 list_entry(list->next, task_t,
4770 #endif /* CONFIG_HOTPLUG_CPU */
4773 * migration_call - callback that gets triggered when a CPU is added.
4774 * Here we can start up the necessary migration thread for the new CPU.
4776 static int migration_call(struct notifier_block *nfb, unsigned long action,
4779 int cpu = (long)hcpu;
4780 struct task_struct *p;
4781 struct runqueue *rq;
4782 unsigned long flags;
4785 case CPU_UP_PREPARE:
4786 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4789 p->flags |= PF_NOFREEZE;
4790 kthread_bind(p, cpu);
4791 /* Must be high prio: stop_machine expects to yield to it. */
4792 rq = task_rq_lock(p, &flags);
4793 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4794 task_rq_unlock(rq, &flags);
4795 cpu_rq(cpu)->migration_thread = p;
4798 /* Strictly unneccessary, as first user will wake it. */
4799 wake_up_process(cpu_rq(cpu)->migration_thread);
4801 #ifdef CONFIG_HOTPLUG_CPU
4802 case CPU_UP_CANCELED:
4803 /* Unbind it from offline cpu so it can run. Fall thru. */
4804 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4805 kthread_stop(cpu_rq(cpu)->migration_thread);
4806 cpu_rq(cpu)->migration_thread = NULL;
4809 migrate_live_tasks(cpu);
4811 kthread_stop(rq->migration_thread);
4812 rq->migration_thread = NULL;
4813 /* Idle task back to normal (off runqueue, low prio) */
4814 rq = task_rq_lock(rq->idle, &flags);
4815 deactivate_task(rq->idle, rq);
4816 rq->idle->static_prio = MAX_PRIO;
4817 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4818 migrate_dead_tasks(cpu);
4819 task_rq_unlock(rq, &flags);
4820 migrate_nr_uninterruptible(rq);
4821 BUG_ON(rq->nr_running != 0);
4823 /* No need to migrate the tasks: it was best-effort if
4824 * they didn't do lock_cpu_hotplug(). Just wake up
4825 * the requestors. */
4826 spin_lock_irq(&rq->lock);
4827 while (!list_empty(&rq->migration_queue)) {
4828 migration_req_t *req;
4829 req = list_entry(rq->migration_queue.next,
4830 migration_req_t, list);
4831 BUG_ON(req->type != REQ_MOVE_TASK);
4832 list_del_init(&req->list);
4833 complete(&req->done);
4835 spin_unlock_irq(&rq->lock);
4842 /* Register at highest priority so that task migration (migrate_all_tasks)
4843 * happens before everything else.
4845 static struct notifier_block __devinitdata migration_notifier = {
4846 .notifier_call = migration_call,
4850 int __init migration_init(void)
4852 void *cpu = (void *)(long)smp_processor_id();
4853 /* Start one for boot CPU. */
4854 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4855 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4856 register_cpu_notifier(&migration_notifier);
4863 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4864 * hold the hotplug lock.
4866 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4868 migration_req_t req;
4869 unsigned long flags;
4870 runqueue_t *rq = cpu_rq(cpu);
4873 spin_lock_irqsave(&rq->lock, flags);
4875 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4878 init_completion(&req.done);
4879 req.type = REQ_SET_DOMAIN;
4881 list_add(&req.list, &rq->migration_queue);
4885 spin_unlock_irqrestore(&rq->lock, flags);
4888 wake_up_process(rq->migration_thread);
4889 wait_for_completion(&req.done);
4893 /* cpus with isolated domains */
4894 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4896 /* Setup the mask of cpus configured for isolated domains */
4897 static int __init isolated_cpu_setup(char *str)
4899 int ints[NR_CPUS], i;
4901 str = get_options(str, ARRAY_SIZE(ints), ints);
4902 cpus_clear(cpu_isolated_map);
4903 for (i = 1; i <= ints[0]; i++)
4904 cpu_set(ints[i], cpu_isolated_map);
4908 __setup ("isolcpus=", isolated_cpu_setup);
4911 * init_sched_build_groups takes an array of groups, the cpumask we wish
4912 * to span, and a pointer to a function which identifies what group a CPU
4913 * belongs to. The return value of group_fn must be a valid index into the
4914 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4915 * keep track of groups covered with a cpumask_t).
4917 * init_sched_build_groups will build a circular linked list of the groups
4918 * covered by the given span, and will set each group's ->cpumask correctly,
4919 * and ->cpu_power to 0.
4921 void __devinit init_sched_build_groups(struct sched_group groups[],
4922 cpumask_t span, int (*group_fn)(int cpu))
4924 struct sched_group *first = NULL, *last = NULL;
4925 cpumask_t covered = CPU_MASK_NONE;
4928 for_each_cpu_mask(i, span) {
4929 int group = group_fn(i);
4930 struct sched_group *sg = &groups[group];
4933 if (cpu_isset(i, covered))
4936 sg->cpumask = CPU_MASK_NONE;
4939 for_each_cpu_mask(j, span) {
4940 if (group_fn(j) != group)
4943 cpu_set(j, covered);
4944 cpu_set(j, sg->cpumask);
4956 #ifdef ARCH_HAS_SCHED_DOMAIN
4957 extern void __devinit arch_init_sched_domains(void);
4958 extern void __devinit arch_destroy_sched_domains(void);
4960 #ifdef CONFIG_SCHED_SMT
4961 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4962 static struct sched_group sched_group_cpus[NR_CPUS];
4963 static int __devinit cpu_to_cpu_group(int cpu)
4969 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4970 static struct sched_group sched_group_phys[NR_CPUS];
4971 static int __devinit cpu_to_phys_group(int cpu)
4973 #ifdef CONFIG_SCHED_SMT
4974 return first_cpu(cpu_sibling_map[cpu]);
4982 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4983 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4984 static int __devinit cpu_to_node_group(int cpu)
4986 return cpu_to_node(cpu);
4990 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4992 * The domains setup code relies on siblings not spanning
4993 * multiple nodes. Make sure the architecture has a proper
4996 static void check_sibling_maps(void)
5000 for_each_online_cpu(i) {
5001 for_each_cpu_mask(j, cpu_sibling_map[i]) {
5002 if (cpu_to_node(i) != cpu_to_node(j)) {
5003 printk(KERN_INFO "warning: CPU %d siblings map "
5004 "to different node - isolating "
5006 cpu_sibling_map[i] = cpumask_of_cpu(i);
5015 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5017 static void __devinit arch_init_sched_domains(void)
5020 cpumask_t cpu_default_map;
5022 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
5023 check_sibling_maps();
5026 * Setup mask for cpus without special case scheduling requirements.
5027 * For now this just excludes isolated cpus, but could be used to
5028 * exclude other special cases in the future.
5030 cpus_complement(cpu_default_map, cpu_isolated_map);
5031 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
5034 * Set up domains. Isolated domains just stay on the dummy domain.
5036 for_each_cpu_mask(i, cpu_default_map) {
5038 struct sched_domain *sd = NULL, *p;
5039 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5041 cpus_and(nodemask, nodemask, cpu_default_map);
5044 sd = &per_cpu(node_domains, i);
5045 group = cpu_to_node_group(i);
5047 sd->span = cpu_default_map;
5048 sd->groups = &sched_group_nodes[group];
5052 sd = &per_cpu(phys_domains, i);
5053 group = cpu_to_phys_group(i);
5055 sd->span = nodemask;
5057 sd->groups = &sched_group_phys[group];
5059 #ifdef CONFIG_SCHED_SMT
5061 sd = &per_cpu(cpu_domains, i);
5062 group = cpu_to_cpu_group(i);
5063 *sd = SD_SIBLING_INIT;
5064 sd->span = cpu_sibling_map[i];
5065 cpus_and(sd->span, sd->span, cpu_default_map);
5067 sd->groups = &sched_group_cpus[group];
5071 #ifdef CONFIG_SCHED_SMT
5072 /* Set up CPU (sibling) groups */
5073 for_each_online_cpu(i) {
5074 cpumask_t this_sibling_map = cpu_sibling_map[i];
5075 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
5076 if (i != first_cpu(this_sibling_map))
5079 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5084 /* Set up physical groups */
5085 for (i = 0; i < MAX_NUMNODES; i++) {
5086 cpumask_t nodemask = node_to_cpumask(i);
5088 cpus_and(nodemask, nodemask, cpu_default_map);
5089 if (cpus_empty(nodemask))
5092 init_sched_build_groups(sched_group_phys, nodemask,
5093 &cpu_to_phys_group);
5098 /* Set up node groups */
5099 init_sched_build_groups(sched_group_nodes, cpu_default_map,
5100 &cpu_to_node_group);
5104 /* Calculate CPU power for physical packages and nodes */
5105 for_each_cpu_mask(i, cpu_default_map) {
5107 struct sched_domain *sd;
5108 #ifdef CONFIG_SCHED_SMT
5109 sd = &per_cpu(cpu_domains, i);
5110 power = SCHED_LOAD_SCALE;
5111 sd->groups->cpu_power = power;
5114 sd = &per_cpu(phys_domains, i);
5115 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5116 (cpus_weight(sd->groups->cpumask)-1) / 10;
5117 sd->groups->cpu_power = power;
5121 if (i == first_cpu(sd->groups->cpumask)) {
5122 /* Only add "power" once for each physical package. */
5123 sd = &per_cpu(node_domains, i);
5124 sd->groups->cpu_power += power;
5129 /* Attach the domains */
5130 for_each_online_cpu(i) {
5131 struct sched_domain *sd;
5132 #ifdef CONFIG_SCHED_SMT
5133 sd = &per_cpu(cpu_domains, i);
5135 sd = &per_cpu(phys_domains, i);
5137 cpu_attach_domain(sd, i);
5142 #ifdef CONFIG_HOTPLUG_CPU
5143 static void __devinit arch_destroy_sched_domains(void)
5145 /* Do nothing: everything is statically allocated. */
5149 #endif /* ARCH_HAS_SCHED_DOMAIN */
5151 #define SCHED_DOMAIN_DEBUG
5152 #ifdef SCHED_DOMAIN_DEBUG
5153 static void sched_domain_debug(void)
5157 for_each_online_cpu(i) {
5158 runqueue_t *rq = cpu_rq(i);
5159 struct sched_domain *sd;
5164 printk(KERN_DEBUG "CPU%d:\n", i);
5169 struct sched_group *group = sd->groups;
5170 cpumask_t groupmask;
5172 cpumask_scnprintf(str, NR_CPUS, sd->span);
5173 cpus_clear(groupmask);
5176 for (j = 0; j < level + 1; j++)
5178 printk("domain %d: ", level);
5180 if (!(sd->flags & SD_LOAD_BALANCE)) {
5181 printk("does not load-balance");
5183 printk(" ERROR !SD_LOAD_BALANCE domain has parent");
5188 printk("span %s\n", str);
5190 if (!cpu_isset(i, sd->span))
5191 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
5192 if (!cpu_isset(i, group->cpumask))
5193 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
5196 for (j = 0; j < level + 2; j++)
5201 printk(" ERROR: NULL");
5205 if (!group->cpu_power)
5206 printk(KERN_DEBUG "ERROR group->cpu_power not set\n");
5208 if (!cpus_weight(group->cpumask))
5209 printk(" ERROR empty group:");
5211 if (cpus_intersects(groupmask, group->cpumask))
5212 printk(" ERROR repeated CPUs:");
5214 cpus_or(groupmask, groupmask, group->cpumask);
5216 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5219 group = group->next;
5220 } while (group != sd->groups);
5223 if (!cpus_equal(sd->span, groupmask))
5224 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
5230 if (!cpus_subset(groupmask, sd->span))
5231 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
5238 #define sched_domain_debug() {}
5242 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5243 * it is initialized to zero, so all balancing flags are cleared which is
5246 static struct sched_domain sched_domain_dummy;
5248 #ifdef CONFIG_HOTPLUG_CPU
5250 * Force a reinitialization of the sched domains hierarchy. The domains
5251 * and groups cannot be updated in place without racing with the balancing
5252 * code, so we temporarily attach all running cpus to a "dummy" domain
5253 * which will prevent rebalancing while the sched domains are recalculated.
5255 static int update_sched_domains(struct notifier_block *nfb,
5256 unsigned long action, void *hcpu)
5261 case CPU_UP_PREPARE:
5262 case CPU_DOWN_PREPARE:
5263 for_each_online_cpu(i)
5264 cpu_attach_domain(&sched_domain_dummy, i);
5265 arch_destroy_sched_domains();
5268 case CPU_UP_CANCELED:
5269 case CPU_DOWN_FAILED:
5273 * Fall through and re-initialise the domains.
5280 /* The hotplug lock is already held by cpu_up/cpu_down */
5281 arch_init_sched_domains();
5283 sched_domain_debug();
5289 void __init sched_init_smp(void)
5292 arch_init_sched_domains();
5293 sched_domain_debug();
5294 unlock_cpu_hotplug();
5295 /* XXX: Theoretical race here - CPU may be hotplugged now */
5296 hotcpu_notifier(update_sched_domains, 0);
5299 void __init sched_init_smp(void)
5302 #endif /* CONFIG_SMP */
5304 int in_sched_functions(unsigned long addr)
5306 /* Linker adds these: start and end of __sched functions */
5307 extern char __sched_text_start[], __sched_text_end[];
5308 return in_lock_functions(addr) ||
5309 (addr >= (unsigned long)__sched_text_start
5310 && addr < (unsigned long)__sched_text_end);
5313 void __init sched_init(void)
5320 for (i = 0; i < NR_CPUS; i++) {
5321 #ifndef CONFIG_CKRM_CPU_SCHEDULE
5323 prio_array_t *array;
5326 spin_lock_init(&rq->lock);
5328 for (j = 0; j < 2; j++) {
5329 array = rq->arrays + j;
5330 for (k = 0; k < MAX_PRIO; k++) {
5331 INIT_LIST_HEAD(array->queue + k);
5332 __clear_bit(k, array->bitmap);
5334 // delimiter for bitsearch
5335 __set_bit(MAX_PRIO, array->bitmap);
5338 rq->active = rq->arrays;
5339 rq->expired = rq->arrays + 1;
5340 rq->best_expired_prio = MAX_PRIO;
5344 spin_lock_init(&rq->lock);
5348 rq->sd = &sched_domain_dummy;
5350 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5351 ckrm_load_init(rq_ckrm_load(rq));
5353 rq->active_balance = 0;
5355 rq->migration_thread = NULL;
5356 INIT_LIST_HEAD(&rq->migration_queue);
5358 #ifdef CONFIG_VSERVER_HARDCPU
5359 INIT_LIST_HEAD(&rq->hold_queue);
5361 atomic_set(&rq->nr_iowait, 0);
5366 * The boot idle thread does lazy MMU switching as well:
5368 atomic_inc(&init_mm.mm_count);
5369 enter_lazy_tlb(&init_mm, current);
5372 * Make us the idle thread. Technically, schedule() should not be
5373 * called from this thread, however somewhere below it might be,
5374 * but because we are the idle thread, we just pick up running again
5375 * when this runqueue becomes "idle".
5377 init_idle(current, smp_processor_id());
5380 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5381 void __might_sleep(char *file, int line)
5383 #if defined(in_atomic)
5384 static unsigned long prev_jiffy; /* ratelimiting */
5386 if ((in_atomic() || irqs_disabled()) &&
5387 system_state == SYSTEM_RUNNING) {
5388 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5390 prev_jiffy = jiffies;
5391 printk(KERN_ERR "Debug: sleeping function called from invalid"
5392 " context at %s:%d\n", file, line);
5393 printk("in_atomic():%d, irqs_disabled():%d\n",
5394 in_atomic(), irqs_disabled());
5399 EXPORT_SYMBOL(__might_sleep);
5402 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5404 * return the classqueue object of a certain processor
5406 struct classqueue_struct * get_cpu_classqueue(int cpu)
5408 return (& (cpu_rq(cpu)->classqueue) );
5412 * _ckrm_cpu_change_class - change the class of a task
5414 void _ckrm_cpu_change_class(task_t *tsk, struct ckrm_cpu_class *newcls)
5416 prio_array_t *array;
5417 struct runqueue *rq;
5418 unsigned long flags;
5420 rq = task_rq_lock(tsk,&flags);
5423 dequeue_task(tsk,array);
5424 tsk->cpu_class = newcls;
5425 enqueue_task(tsk,rq_active(tsk,rq));
5427 tsk->cpu_class = newcls;
5429 task_rq_unlock(rq,&flags);
5433 #ifdef CONFIG_MAGIC_SYSRQ
5434 void normalize_rt_tasks(void)
5436 struct task_struct *p;
5437 prio_array_t *array;
5438 unsigned long flags;
5441 read_lock_irq(&tasklist_lock);
5442 for_each_process (p) {
5446 rq = task_rq_lock(p, &flags);
5450 deactivate_task(p, task_rq(p));
5451 __setscheduler(p, SCHED_NORMAL, 0);
5453 __activate_task(p, task_rq(p));
5454 resched_task(rq->curr);
5457 task_rq_unlock(rq, &flags);
5459 read_unlock_irq(&tasklist_lock);
5462 #endif /* CONFIG_MAGIC_SYSRQ */