Magellan Linux

Contents of /alx-src/tags/kernel26-2.6.12-alx-r9/kernel/sched.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 630 - (show annotations) (download)
Wed Mar 4 11:03:09 2009 UTC (15 years, 6 months ago) by niro
File MIME type: text/plain
File size: 122889 byte(s)
Tag kernel26-2.6.12-alx-r9
1 /*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2005-08-20 New staircase scheduling policy by Con Kolivas with help
20 * from William Lee Irwin III, Zwane Mwaikambo & Peter Williams.
21 * Staircase v11.6
22 */
23
24 #include <linux/mm.h>
25 #include <linux/module.h>
26 #include <linux/nmi.h>
27 #include <linux/init.h>
28 #include <asm/uaccess.h>
29 #include <linux/highmem.h>
30 #include <linux/smp_lock.h>
31 #include <asm/mmu_context.h>
32 #include <linux/interrupt.h>
33 #include <linux/completion.h>
34 #include <linux/kernel_stat.h>
35 #include <linux/security.h>
36 #include <linux/notifier.h>
37 #include <linux/profile.h>
38 #include <linux/suspend.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <asm/tlb.h>
54
55 #include <asm/unistd.h>
56
57 /*
58 * Convert user-nice values [ -20 ... 0 ... 19 ]
59 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
60 * and back.
61 */
62 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
63 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
64 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
65
66 /*
67 * 'User priority' is the nice value converted to something we
68 * can work with better when scaling various scheduler parameters,
69 * it's a [ 0 ... 39 ] range.
70 */
71 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
72 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
73 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
74
75 /*
76 * Some helpers for converting nanosecond timing to jiffy resolution
77 */
78 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
80 #define NSJIFFY (1000000000 / HZ) /* One jiffy in ns */
81
82 int sched_compute = 0;
83 /*
84 *This is the time all tasks within the same priority round robin.
85 *compute setting is reserved for dedicated computational scheduling
86 *and has ten times larger intervals. Set to a minimum of 5ms.
87 */
88 #define _RR_INTERVAL ((5 * HZ / 1001) + 1)
89 #define RR_INTERVAL() (_RR_INTERVAL * (1 + 19 * sched_compute))
90 #define DEF_TIMESLICE (RR_INTERVAL() * 19)
91
92 #define task_hot(p, now, sd) ((long long) ((now) - (p)->timestamp) \
93 < (long long) (sd)->cache_hot_time)
94
95 /*
96 * These are the runqueue data structures:
97 */
98
99 typedef struct runqueue runqueue_t;
100
101 /*
102 * This is the main, per-CPU runqueue data structure.
103 *
104 * Locking rule: those places that want to lock multiple runqueues
105 * (such as the load balancing or the thread migration code), lock
106 * acquire operations must be ordered by ascending &runqueue.
107 */
108 struct runqueue {
109 spinlock_t lock;
110
111 /*
112 * nr_running and cpu_load should be in the same cacheline because
113 * remote CPUs use both these fields when doing load calculation.
114 */
115 unsigned long nr_running;
116 #ifdef CONFIG_SMP
117 unsigned long prio_bias;
118 unsigned long cpu_load;
119 #endif
120 unsigned long long nr_switches;
121
122 /*
123 * This is part of a global counter where only the total sum
124 * over all CPUs matters. A task can increase this counter on
125 * one CPU and if it got migrated afterwards it may decrease
126 * it on another CPU. Always updated under the runqueue lock:
127 */
128 unsigned long nr_uninterruptible;
129
130 unsigned long long timestamp_last_tick;
131 unsigned int cache_ticks, preempted;
132 task_t *curr, *idle;
133 struct mm_struct *prev_mm;
134 unsigned long bitmap[BITS_TO_LONGS(MAX_PRIO + 1)];
135 struct list_head queue[MAX_PRIO];
136 atomic_t nr_iowait;
137
138 #ifdef CONFIG_SMP
139 struct sched_domain *sd;
140
141 /* For active balancing */
142 int active_balance;
143 int push_cpu;
144
145 task_t *migration_thread;
146 struct list_head migration_queue;
147 #endif
148
149 #ifdef CONFIG_SCHEDSTATS
150 /* latency stats */
151 struct sched_info rq_sched_info;
152
153 /* sys_sched_yield() stats */
154 unsigned long yld_exp_empty;
155 unsigned long yld_act_empty;
156 unsigned long yld_both_empty;
157 unsigned long yld_cnt;
158
159 /* schedule() stats */
160 unsigned long sched_switch;
161 unsigned long sched_cnt;
162 unsigned long sched_goidle;
163
164 /* try_to_wake_up() stats */
165 unsigned long ttwu_cnt;
166 unsigned long ttwu_local;
167 #endif
168 };
169
170 static DEFINE_PER_CPU(struct runqueue, runqueues);
171
172 #define for_each_domain(cpu, domain) \
173 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
174
175 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
176 #define this_rq() (&__get_cpu_var(runqueues))
177 #define task_rq(p) cpu_rq(task_cpu(p))
178 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
179
180 /*
181 * Default context-switch locking:
182 */
183 #ifndef prepare_arch_switch
184 # define prepare_arch_switch(rq, next) do { } while (0)
185 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
186 # define task_running(rq, p) ((rq)->curr == (p))
187 #endif
188
189 /*
190 * task_rq_lock - lock the runqueue a given task resides on and disable
191 * interrupts. Note the ordering: we can safely lookup the task_rq without
192 * explicitly disabling preemption.
193 */
194 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
195 __acquires(rq->lock)
196 {
197 struct runqueue *rq;
198
199 repeat_lock_task:
200 local_irq_save(*flags);
201 rq = task_rq(p);
202 spin_lock(&rq->lock);
203 if (unlikely(rq != task_rq(p))) {
204 spin_unlock_irqrestore(&rq->lock, *flags);
205 goto repeat_lock_task;
206 }
207 return rq;
208 }
209
210 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
211 __releases(rq->lock)
212 {
213 spin_unlock_irqrestore(&rq->lock, *flags);
214 }
215
216 #ifdef CONFIG_SCHEDSTATS
217 /*
218 * bump this up when changing the output format or the meaning of an existing
219 * format, so that tools can adapt (or abort)
220 */
221 #define SCHEDSTAT_VERSION 11
222
223 static int show_schedstat(struct seq_file *seq, void *v)
224 {
225 int cpu;
226
227 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
228 seq_printf(seq, "timestamp %lu\n", jiffies);
229 for_each_online_cpu(cpu) {
230 runqueue_t *rq = cpu_rq(cpu);
231 #ifdef CONFIG_SMP
232 struct sched_domain *sd;
233 int dcnt = 0;
234 #endif
235
236 /* runqueue-specific stats */
237 seq_printf(seq,
238 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
239 cpu, rq->yld_both_empty,
240 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
241 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
242 rq->ttwu_cnt, rq->ttwu_local,
243 rq->rq_sched_info.cpu_time,
244 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
245
246 seq_printf(seq, "\n");
247
248 #ifdef CONFIG_SMP
249 /* domain-specific stats */
250 for_each_domain(cpu, sd) {
251 enum idle_type itype;
252 char mask_str[NR_CPUS];
253
254 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
255 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
256 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
257 itype++) {
258 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
259 sd->lb_cnt[itype],
260 sd->lb_balanced[itype],
261 sd->lb_failed[itype],
262 sd->lb_imbalance[itype],
263 sd->lb_gained[itype],
264 sd->lb_hot_gained[itype],
265 sd->lb_nobusyq[itype],
266 sd->lb_nobusyg[itype]);
267 }
268 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu\n",
269 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
270 sd->sbe_pushed, sd->sbe_attempts,
271 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
272 }
273 #endif
274 }
275 return 0;
276 }
277
278 static int schedstat_open(struct inode *inode, struct file *file)
279 {
280 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
281 char *buf = kmalloc(size, GFP_KERNEL);
282 struct seq_file *m;
283 int res;
284
285 if (!buf)
286 return -ENOMEM;
287 res = single_open(file, show_schedstat, NULL);
288 if (!res) {
289 m = file->private_data;
290 m->buf = buf;
291 m->size = size;
292 } else
293 kfree(buf);
294 return res;
295 }
296
297 struct file_operations proc_schedstat_operations = {
298 .open = schedstat_open,
299 .read = seq_read,
300 .llseek = seq_lseek,
301 .release = single_release,
302 };
303
304 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
305 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
306 #else /* !CONFIG_SCHEDSTATS */
307 # define schedstat_inc(rq, field) do { } while (0)
308 # define schedstat_add(rq, field, amt) do { } while (0)
309 #endif
310
311 /*
312 * rq_lock - lock a given runqueue and disable interrupts.
313 */
314 static inline runqueue_t *this_rq_lock(void)
315 __acquires(rq->lock)
316 {
317 runqueue_t *rq;
318
319 local_irq_disable();
320 rq = this_rq();
321 spin_lock(&rq->lock);
322
323 return rq;
324 }
325
326 #ifdef CONFIG_SCHED_SMT
327 static int cpu_and_siblings_are_idle(int cpu)
328 {
329 int sib;
330 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
331 if (idle_cpu(sib))
332 continue;
333 return 0;
334 }
335
336 return 1;
337 }
338 #else
339 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
340 #endif
341
342 #ifdef CONFIG_SCHEDSTATS
343 /*
344 * Called when a process is dequeued from the active array and given
345 * the cpu. We should note that with the exception of interactive
346 * tasks, the expired queue will become the active queue after the active
347 * queue is empty, without explicitly dequeuing and requeuing tasks in the
348 * expired queue. (Interactive tasks may be requeued directly to the
349 * active queue, thus delaying tasks in the expired queue from running;
350 * see scheduler_tick()).
351 *
352 * This function is only called from sched_info_arrive(), rather than
353 * dequeue_task(). Even though a task may be queued and dequeued multiple
354 * times as it is shuffled about, we're really interested in knowing how
355 * long it was from the *first* time it was queued to the time that it
356 * finally hit a cpu.
357 */
358 static inline void sched_info_dequeued(task_t *t)
359 {
360 t->sched_info.last_queued = 0;
361 }
362
363 /*
364 * Called when a task finally hits the cpu. We can now calculate how
365 * long it was waiting to run. We also note when it began so that we
366 * can keep stats on how long its timeslice is.
367 */
368 static inline void sched_info_arrive(task_t *t)
369 {
370 unsigned long now = jiffies, diff = 0;
371 struct runqueue *rq = task_rq(t);
372
373 if (t->sched_info.last_queued)
374 diff = now - t->sched_info.last_queued;
375 sched_info_dequeued(t);
376 t->sched_info.run_delay += diff;
377 t->sched_info.last_arrival = now;
378 t->sched_info.pcnt++;
379
380 if (!rq)
381 return;
382
383 rq->rq_sched_info.run_delay += diff;
384 rq->rq_sched_info.pcnt++;
385 }
386
387 /*
388 * Called when a process is queued into either the active or expired
389 * array. The time is noted and later used to determine how long we
390 * had to wait for us to reach the cpu. Since the expired queue will
391 * become the active queue after active queue is empty, without dequeuing
392 * and requeuing any tasks, we are interested in queuing to either. It
393 * is unusual but not impossible for tasks to be dequeued and immediately
394 * requeued in the same or another array: this can happen in sched_yield(),
395 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
396 * to runqueue.
397 *
398 * This function is only called from enqueue_task(), but also only updates
399 * the timestamp if it is already not set. It's assumed that
400 * sched_info_dequeued() will clear that stamp when appropriate.
401 */
402 static inline void sched_info_queued(task_t *t)
403 {
404 if (!t->sched_info.last_queued)
405 t->sched_info.last_queued = jiffies;
406 }
407
408 /*
409 * Called when a process ceases being the active-running process, either
410 * voluntarily or involuntarily. Now we can calculate how long we ran.
411 */
412 static inline void sched_info_depart(task_t *t)
413 {
414 struct runqueue *rq = task_rq(t);
415 unsigned long diff = jiffies - t->sched_info.last_arrival;
416
417 t->sched_info.cpu_time += diff;
418
419 if (rq)
420 rq->rq_sched_info.cpu_time += diff;
421 }
422
423 /*
424 * Called when tasks are switched involuntarily due, typically, to expiring
425 * their time slice. (This may also be called when switching to or from
426 * the idle task.) We are only called when prev != next.
427 */
428 static inline void sched_info_switch(task_t *prev, task_t *next)
429 {
430 struct runqueue *rq = task_rq(prev);
431
432 /*
433 * prev now departs the cpu. It's not interesting to record
434 * stats about how efficient we were at scheduling the idle
435 * process, however.
436 */
437 if (prev != rq->idle)
438 sched_info_depart(prev);
439
440 if (next != rq->idle)
441 sched_info_arrive(next);
442 }
443 #else
444 #define sched_info_queued(t) do { } while (0)
445 #define sched_info_switch(t, next) do { } while (0)
446 #endif /* CONFIG_SCHEDSTATS */
447
448 /*
449 * Get nanosecond clock difference without overflowing unsigned long.
450 */
451 static inline unsigned long ns_diff(unsigned long long v1, unsigned long long v2)
452 {
453 unsigned long long vdiff;
454 if (likely(v1 > v2)) {
455 vdiff = v1 - v2;
456 if (vdiff > (1 << 31))
457 vdiff = 1 << 31;
458 } else
459 /*
460 * Rarely the clock appears to go backwards. There should
461 * always be a positive difference so return 1.
462 */
463 vdiff = 1;
464 return (unsigned long)vdiff;
465 }
466
467 static inline int task_queued(task_t *task)
468 {
469 return !list_empty(&task->run_list);
470 }
471
472 /*
473 * Adding/removing a task to/from a runqueue:
474 */
475 static inline void dequeue_task(struct task_struct *p, runqueue_t *rq)
476 {
477 list_del_init(&p->run_list);
478 if (list_empty(rq->queue + p->prio))
479 __clear_bit(p->prio, rq->bitmap);
480 p->ns_debit = 0;
481 }
482
483 static void enqueue_task(struct task_struct *p, runqueue_t *rq)
484 {
485 list_add_tail(&p->run_list, rq->queue + p->prio);
486 __set_bit(p->prio, rq->bitmap);
487 }
488
489 /*
490 * Put task to the end of the run list without the overhead of dequeue
491 * followed by enqueue.
492 */
493 static inline void requeue_task(struct task_struct *p, runqueue_t *rq)
494 {
495 list_move_tail(&p->run_list, rq->queue + p->prio);
496 }
497
498 static inline void enqueue_task_head(struct task_struct *p, runqueue_t *rq)
499 {
500 list_add(&p->run_list, rq->queue + p->prio);
501 __set_bit(p->prio, rq->bitmap);
502 }
503
504 #ifdef CONFIG_SMP
505 static inline void inc_prio_bias(runqueue_t *rq, int prio)
506 {
507 rq->prio_bias += MAX_PRIO - prio;
508 }
509
510 static inline void dec_prio_bias(runqueue_t *rq, int prio)
511 {
512 rq->prio_bias -= MAX_PRIO - prio;
513 }
514 #else
515 static inline void inc_prio_bias(runqueue_t *rq, int prio)
516 {
517 }
518
519 static inline void dec_prio_bias(runqueue_t *rq, int prio)
520 {
521 }
522 #endif
523
524 static inline void inc_nr_running(task_t *p, runqueue_t *rq)
525 {
526 rq->nr_running++;
527 #ifdef CONFIG_SMP
528 if (rt_task(p)) {
529 if (p != rq->migration_thread)
530 inc_prio_bias(rq, p->prio);
531 } else
532 inc_prio_bias(rq, p->static_prio);
533 #endif
534 }
535
536 static inline void dec_nr_running(task_t *p, runqueue_t *rq)
537 {
538 rq->nr_running--;
539 #ifdef CONFIG_SMP
540 if (rt_task(p)) {
541 if (p != rq->migration_thread)
542 dec_prio_bias(rq, p->prio);
543 } else
544 dec_prio_bias(rq, p->static_prio);
545 #endif
546 }
547
548 /*
549 * __activate_task - move a task to the runqueue.
550 */
551 static void __activate_task(task_t *p, runqueue_t *rq)
552 {
553 enqueue_task(p, rq);
554 inc_nr_running(p, rq);
555 }
556
557 /*
558 * __activate_idle_task - move idle task to the _front_ of runqueue.
559 */
560 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
561 {
562 enqueue_task_head(p, rq);
563 inc_nr_running(p, rq);
564 }
565
566 /*
567 * burst - extra intervals an interactive task can run for at best priority
568 * instead of descending priorities.
569 */
570 static inline unsigned int burst(task_t *p)
571 {
572 if (likely(!rt_task(p))) {
573 unsigned int task_user_prio = TASK_USER_PRIO(p);
574 return 39 - task_user_prio;
575 } else
576 return p->burst;
577 }
578
579 static void inc_burst(task_t *p)
580 {
581 unsigned int best_burst;
582 best_burst = burst(p);
583 if (p->burst < best_burst)
584 p->burst++;
585 }
586
587 static void dec_burst(task_t *p)
588 {
589 if (p->burst)
590 p->burst--;
591 }
592
593 static inline unsigned int rr_interval(task_t * p)
594 {
595 unsigned int rr_interval = RR_INTERVAL();
596 int nice = TASK_NICE(p);
597
598 if (nice < 0 && !rt_task(p))
599 rr_interval += -(nice);
600 return rr_interval;
601 }
602
603 /*
604 * slice - the duration a task runs before getting requeued at its best
605 * priority and has its burst decremented.
606 */
607 static inline unsigned int slice(task_t *p)
608 {
609 unsigned int slice, rr;
610 slice = rr = rr_interval(p);
611 if (likely(!rt_task(p)))
612 slice += burst(p) * rr;
613 return slice;
614 }
615
616 /*
617 * sched_interactive - sysctl which allows interactive tasks to have bursts
618 */
619 int sched_interactive = 1;
620
621 /*
622 * effective_prio - dynamic priority dependent on burst.
623 * The priority normally decreases by one each RR_INTERVAL.
624 * As the burst increases the priority stays at the top "stair" or
625 * priority for longer.
626 */
627 static int effective_prio(task_t *p)
628 {
629 int prio;
630 unsigned int full_slice, used_slice, first_slice;
631 unsigned int best_burst, rr;
632 if (rt_task(p))
633 return p->prio;
634 if (batch_task(p)) {
635 if (unlikely(p->flags & (PF_NONSLEEP | PF_FREEZE))) {
636 /*
637 * If batch is waking up from in kernel activity
638 * or being frozen, reschedule at a normal priority
639 * to begin with.
640 */
641 p->flags |= PF_YIELDED;
642 return MAX_PRIO - 2;
643 }
644 return MAX_PRIO - 1;
645 }
646
647 best_burst = burst(p);
648 full_slice = slice(p);
649 rr = rr_interval(p);
650 used_slice = full_slice - p->slice;
651 if (p->burst > best_burst)
652 p->burst = best_burst;
653 first_slice = rr;
654 if (sched_interactive && !sched_compute && p->mm)
655 first_slice *= (p->burst + 1);
656 prio = MAX_PRIO - 2 - best_burst;
657
658 if (used_slice < first_slice)
659 return prio;
660 prio += 1 + (used_slice - first_slice) / rr;
661 if (prio >= MAX_PRIO - 2)
662 prio = MAX_PRIO - 2;
663 return prio;
664 }
665
666 static void continue_slice(task_t *p)
667 {
668 unsigned long total_run = NS_TO_JIFFIES(p->totalrun);
669
670 if (total_run >= p->slice) {
671 p->totalrun -= JIFFIES_TO_NS(p->slice);
672 dec_burst(p);
673 } else {
674 unsigned int remainder;
675 p->slice -= total_run;
676 remainder = p->slice % rr_interval(p);
677 if (remainder)
678 p->time_slice = remainder;
679 }
680 }
681
682 /*
683 * recalc_task_prio - this checks for tasks that run ultra short timeslices
684 * or have just forked a thread/process and make them continue their old
685 * slice instead of starting a new one at high priority.
686 */
687 static inline void recalc_task_prio(task_t *p, unsigned long long now,
688 unsigned long rq_running)
689 {
690 unsigned long sleep_time = ns_diff(now, p->timestamp);
691
692 /*
693 * Priority is elevated back to best by amount of sleep_time.
694 * sleep_time is scaled down by number of tasks currently running.
695 */
696 if (rq_running > 1)
697 sleep_time /= rq_running;
698
699 p->totalrun += p->runtime;
700 if (NS_TO_JIFFIES(p->totalrun) >= p->slice &&
701 NS_TO_JIFFIES(sleep_time) < p->slice) {
702 p->flags &= ~PF_NONSLEEP;
703 dec_burst(p);
704 p->totalrun += sleep_time - JIFFIES_TO_NS(p->slice);
705 goto out;
706 }
707
708 if (p->flags & PF_NONSLEEP) {
709 continue_slice(p);
710 p->flags &= ~PF_NONSLEEP;
711 goto out;
712 }
713
714 if (sched_compute) {
715 continue_slice(p);
716 goto out;
717 }
718
719 if (sleep_time >= p->totalrun) {
720 if (!(p->flags & PF_NONSLEEP))
721 inc_burst(p);
722 p->totalrun = 0;
723 goto out;
724 }
725
726 p->totalrun -= sleep_time;
727 continue_slice(p);
728 out:
729 return;
730 }
731
732 /*
733 * activate_task - move a task to the runqueue and do priority recalculation
734 *
735 * Update all the scheduling statistics stuff. (sleep average
736 * calculation, priority modifiers, etc.)
737 */
738 static void activate_task(task_t *p, runqueue_t *rq, int local)
739 {
740 unsigned long long now = sched_clock();
741 #ifdef CONFIG_SMP
742 if (!local) {
743 /* Compensate for drifting sched_clock */
744 runqueue_t *this_rq = this_rq();
745 now = (now - this_rq->timestamp_last_tick)
746 + rq->timestamp_last_tick;
747 }
748 #endif
749 p->slice = slice(p);
750 p->time_slice = rr_interval(p);
751 recalc_task_prio(p, now, rq->nr_running);
752 p->flags &= ~PF_NONSLEEP;
753 p->prio = effective_prio(p);
754 p->timestamp = now;
755 __activate_task(p, rq);
756 }
757
758 /*
759 * deactivate_task - remove a task from the runqueue.
760 */
761 static inline void deactivate_task(struct task_struct *p, runqueue_t *rq)
762 {
763 dec_nr_running(p, rq);
764 dequeue_task(p, rq);
765 }
766
767 /*
768 * resched_task - mark a task 'to be rescheduled now'.
769 *
770 * On UP this means the setting of the need_resched flag, on SMP it
771 * might also involve a cross-CPU call to trigger the scheduler on
772 * the target CPU.
773 */
774 #ifdef CONFIG_SMP
775 static void resched_task(task_t *p)
776 {
777 int need_resched, nrpolling;
778
779 assert_spin_locked(&task_rq(p)->lock);
780
781 /* minimise the chance of sending an interrupt to poll_idle() */
782 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
783 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
784 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
785
786 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
787 smp_send_reschedule(task_cpu(p));
788 }
789 #else
790 static inline void resched_task(task_t *p)
791 {
792 set_tsk_need_resched(p);
793 }
794 #endif
795
796 /**
797 * task_curr - is this task currently executing on a CPU?
798 * @p: the task in question.
799 */
800 inline int task_curr(const task_t *p)
801 {
802 return cpu_curr(task_cpu(p)) == p;
803 }
804
805 #ifdef CONFIG_SMP
806 enum request_type {
807 REQ_MOVE_TASK,
808 REQ_SET_DOMAIN,
809 };
810
811 typedef struct {
812 struct list_head list;
813 enum request_type type;
814
815 /* For REQ_MOVE_TASK */
816 task_t *task;
817 int dest_cpu;
818
819 /* For REQ_SET_DOMAIN */
820 struct sched_domain *sd;
821
822 struct completion done;
823 } migration_req_t;
824
825 /*
826 * The task's runqueue lock must be held.
827 * Returns true if you have to wait for migration thread.
828 */
829 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
830 {
831 runqueue_t *rq = task_rq(p);
832
833 /*
834 * If the task is not on a runqueue (and not running), then
835 * it is sufficient to simply update the task's cpu field.
836 */
837 if (!task_queued(p) && !task_running(rq, p)) {
838 set_task_cpu(p, dest_cpu);
839 return 0;
840 }
841
842 init_completion(&req->done);
843 req->type = REQ_MOVE_TASK;
844 req->task = p;
845 req->dest_cpu = dest_cpu;
846 list_add(&req->list, &rq->migration_queue);
847 return 1;
848 }
849
850 /*
851 * wait_task_inactive - wait for a thread to unschedule.
852 *
853 * The caller must ensure that the task *will* unschedule sometime soon,
854 * else this function might spin for a *long* time. This function can't
855 * be called with interrupts off, or it may introduce deadlock with
856 * smp_call_function() if an IPI is sent by the same process we are
857 * waiting to become inactive.
858 */
859 void wait_task_inactive(task_t * p)
860 {
861 unsigned long flags;
862 runqueue_t *rq;
863 int preempted;
864
865 repeat:
866 rq = task_rq_lock(p, &flags);
867 /* Must be off runqueue entirely, not preempted. */
868 if (unlikely(task_queued(p) || task_running(rq, p))) {
869 /* If it's preempted, we yield. It could be a while. */
870 preempted = !task_running(rq, p);
871 task_rq_unlock(rq, &flags);
872 cpu_relax();
873 if (preempted)
874 yield();
875 goto repeat;
876 }
877 task_rq_unlock(rq, &flags);
878 }
879
880 /***
881 * kick_process - kick a running thread to enter/exit the kernel
882 * @p: the to-be-kicked thread
883 *
884 * Cause a process which is running on another CPU to enter
885 * kernel-mode, without any delay. (to get signals handled.)
886 *
887 * NOTE: this function doesnt have to take the runqueue lock,
888 * because all it wants to ensure is that the remote task enters
889 * the kernel. If the IPI races and the task has been migrated
890 * to another CPU then no harm is done and the purpose has been
891 * achieved as well.
892 */
893 void kick_process(task_t *p)
894 {
895 int cpu;
896
897 preempt_disable();
898 cpu = task_cpu(p);
899 if ((cpu != smp_processor_id()) && task_curr(p))
900 smp_send_reschedule(cpu);
901 preempt_enable();
902 }
903
904 /*
905 * Return a low guess at the load of a migration-source cpu.
906 *
907 * We want to under-estimate the load of migration sources, to
908 * balance conservatively.
909 */
910 static inline unsigned long __source_load(int cpu, enum idle_type idle)
911 {
912 runqueue_t *rq = cpu_rq(cpu);
913 unsigned long running = rq->nr_running;
914 unsigned long source_load, cpu_load = rq->cpu_load,
915 load_now = running * SCHED_LOAD_SCALE;
916
917 source_load = min(cpu_load, load_now);
918
919 if (running > 1 || (idle == NOT_IDLE && running))
920 /*
921 * If we are busy rebalancing the load is biased by
922 * priority to create 'nice' support across cpus. When
923 * idle rebalancing we should only bias the source_load if
924 * there is more than one task running on that queue to
925 * prevent idle rebalance from trying to pull tasks from a
926 * queue with only one running task.
927 */
928 source_load = source_load * rq->prio_bias / running;
929
930 return source_load;
931 }
932
933 static inline unsigned long source_load(int cpu)
934 {
935 return __source_load(cpu, NOT_IDLE);
936 }
937
938 /*
939 * Return a high guess at the load of a migration-target cpu
940 */
941 static inline unsigned long __target_load(int cpu, enum idle_type idle)
942 {
943 runqueue_t *rq = cpu_rq(cpu);
944 unsigned long running = rq->nr_running;
945 unsigned long target_load, cpu_load = rq->cpu_load,
946 load_now = running * SCHED_LOAD_SCALE;
947
948 target_load = max(cpu_load, load_now);
949
950 if (running > 1 || (idle == NOT_IDLE && running))
951 target_load = target_load * rq->prio_bias / running;
952
953 return target_load;
954 }
955
956 static inline unsigned long target_load(int cpu)
957 {
958 return __target_load(cpu, NOT_IDLE);
959 }
960 #endif
961
962 /*
963 * wake_idle() will wake a task on an idle cpu if task->cpu is
964 * not idle and an idle cpu is available. The span of cpus to
965 * search starts with cpus closest then further out as needed,
966 * so we always favor a closer, idle cpu.
967 *
968 * Returns the CPU we should wake onto.
969 */
970 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
971 static inline int wake_idle(int cpu, task_t *p)
972 {
973 cpumask_t tmp;
974 struct sched_domain *sd;
975 int i;
976
977 if (idle_cpu(cpu))
978 return cpu;
979
980 for_each_domain(cpu, sd) {
981 if (sd->flags & SD_WAKE_IDLE) {
982 cpus_and(tmp, sd->span, cpu_online_map);
983 cpus_and(tmp, tmp, p->cpus_allowed);
984 for_each_cpu_mask(i, tmp) {
985 if (idle_cpu(i))
986 return i;
987 }
988 }
989 else break;
990 }
991 return cpu;
992 }
993 #else
994 static inline int wake_idle(int cpu, task_t *p)
995 {
996 return cpu;
997 }
998 #endif
999
1000 /*
1001 * cache_delay is the time preemption is delayed in sched_compute mode
1002 * and is set to a nominal 10ms.
1003 */
1004 static int cache_delay = 10 * HZ / 1000;
1005
1006 /*
1007 * Check to see if p preempts rq->curr and resched if it does. In compute
1008 * mode we do not preempt for at least cache_delay and set rq->preempted.
1009 */
1010 static void preempt(task_t *p, runqueue_t *rq)
1011 {
1012 if (p->prio >= rq->curr->prio)
1013 return;
1014 if (!sched_compute || rq->cache_ticks >= cache_delay ||
1015 !p->mm || rt_task(p))
1016 resched_task(rq->curr);
1017 rq->preempted = 1;
1018 }
1019
1020 /***
1021 * try_to_wake_up - wake up a thread
1022 * @p: the to-be-woken-up thread
1023 * @state: the mask of task states that can be woken
1024 * @sync: do a synchronous wakeup?
1025 *
1026 * Put it on the run-queue if it's not already there. The "current"
1027 * thread is always on the run-queue (except when the actual
1028 * re-schedule is in progress), and as such you're allowed to do
1029 * the simpler "current->state = TASK_RUNNING" to mark yourself
1030 * runnable without the overhead of this.
1031 *
1032 * returns failure only if the task is already active.
1033 */
1034 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1035 {
1036 int cpu, this_cpu, success = 0;
1037 unsigned long flags;
1038 long old_state;
1039 runqueue_t *rq;
1040 #ifdef CONFIG_SMP
1041 unsigned long load, this_load;
1042 struct sched_domain *sd;
1043 int new_cpu;
1044 #endif
1045
1046 rq = task_rq_lock(p, &flags);
1047 old_state = p->state;
1048 if (!(old_state & state))
1049 goto out;
1050
1051 if (task_queued(p))
1052 goto out_running;
1053
1054 cpu = task_cpu(p);
1055 this_cpu = smp_processor_id();
1056
1057 #ifdef CONFIG_SMP
1058 if (unlikely(task_running(rq, p)))
1059 goto out_activate;
1060
1061 #ifdef CONFIG_SCHEDSTATS
1062 schedstat_inc(rq, ttwu_cnt);
1063 if (cpu == this_cpu) {
1064 schedstat_inc(rq, ttwu_local);
1065 } else {
1066 for_each_domain(this_cpu, sd) {
1067 if (cpu_isset(cpu, sd->span)) {
1068 schedstat_inc(sd, ttwu_wake_remote);
1069 break;
1070 }
1071 }
1072 }
1073 #endif
1074
1075 new_cpu = cpu;
1076 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1077 goto out_set_cpu;
1078
1079 load = source_load(cpu);
1080 this_load = target_load(this_cpu);
1081
1082 /*
1083 * If sync wakeup then subtract the (maximum possible) effect of
1084 * the currently running task from the load of the current CPU:
1085 */
1086 if (sync)
1087 this_load -= SCHED_LOAD_SCALE;
1088
1089 /* Don't pull the task off an idle CPU to a busy one */
1090 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1091 goto out_set_cpu;
1092
1093 new_cpu = this_cpu; /* Wake to this CPU if we can */
1094
1095 /*
1096 * Scan domains for affine wakeup and passive balancing
1097 * possibilities.
1098 */
1099 for_each_domain(this_cpu, sd) {
1100 unsigned int imbalance;
1101 /*
1102 * Start passive balancing when half the imbalance_pct
1103 * limit is reached.
1104 */
1105 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1106
1107 if ((sd->flags & SD_WAKE_AFFINE) &&
1108 !task_hot(p, rq->timestamp_last_tick, sd)) {
1109 /*
1110 * This domain has SD_WAKE_AFFINE and p is cache cold
1111 * in this domain.
1112 */
1113 if (cpu_isset(cpu, sd->span)) {
1114 schedstat_inc(sd, ttwu_move_affine);
1115 goto out_set_cpu;
1116 }
1117 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1118 imbalance*this_load <= 100*load) {
1119 /*
1120 * This domain has SD_WAKE_BALANCE and there is
1121 * an imbalance.
1122 */
1123 if (cpu_isset(cpu, sd->span)) {
1124 schedstat_inc(sd, ttwu_move_balance);
1125 goto out_set_cpu;
1126 }
1127 }
1128 }
1129
1130 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1131 out_set_cpu:
1132 new_cpu = wake_idle(new_cpu, p);
1133 if (new_cpu != cpu) {
1134 set_task_cpu(p, new_cpu);
1135 task_rq_unlock(rq, &flags);
1136 /* might preempt at this point */
1137 rq = task_rq_lock(p, &flags);
1138 old_state = p->state;
1139 if (!(old_state & state))
1140 goto out;
1141 if (task_queued(p))
1142 goto out_running;
1143
1144 this_cpu = smp_processor_id();
1145 cpu = task_cpu(p);
1146 }
1147
1148 out_activate:
1149 #endif /* CONFIG_SMP */
1150 if (old_state == TASK_UNINTERRUPTIBLE)
1151 rq->nr_uninterruptible--;
1152
1153 /*
1154 * Tasks that have marked their sleep as noninteractive get
1155 * woken up without their sleep counting.
1156 */
1157 if (old_state & TASK_NONINTERACTIVE)
1158 p->flags |= PF_NONSLEEP;
1159
1160 /*
1161 * Sync wakeups (i.e. those types of wakeups where the waker
1162 * has indicated that it will leave the CPU in short order)
1163 * don't trigger a preemption, if the woken up task will run on
1164 * this cpu. (in this case the 'I will reschedule' promise of
1165 * the waker guarantees that the freshly woken up task is going
1166 * to be considered on this CPU.)
1167 */
1168 activate_task(p, rq, cpu == this_cpu);
1169 if (!sync || cpu != this_cpu) {
1170 preempt(p, rq);
1171 }
1172 success = 1;
1173
1174 out_running:
1175 p->state = TASK_RUNNING;
1176 out:
1177 task_rq_unlock(rq, &flags);
1178
1179 return success;
1180 }
1181
1182 int fastcall wake_up_process(task_t * p)
1183 {
1184 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1185 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1186 }
1187
1188 EXPORT_SYMBOL(wake_up_process);
1189
1190 int fastcall wake_up_state(task_t *p, unsigned int state)
1191 {
1192 return try_to_wake_up(p, state, 0);
1193 }
1194
1195 #ifdef CONFIG_SMP
1196 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1197 struct sched_domain *sd);
1198 #endif
1199
1200 /*
1201 * Perform scheduler related setup for a newly forked process p.
1202 * p is forked by current.
1203 */
1204 void fastcall sched_fork(task_t *p)
1205 {
1206 /*
1207 * We mark the process as running here, but have not actually
1208 * inserted it onto the runqueue yet. This guarantees that
1209 * nobody will actually run it, and a signal or other external
1210 * event cannot wake it up and insert it on the runqueue either.
1211 */
1212 p->state = TASK_RUNNING;
1213 INIT_LIST_HEAD(&p->run_list);
1214 spin_lock_init(&p->switch_lock);
1215 #ifdef CONFIG_SCHEDSTATS
1216 memset(&p->sched_info, 0, sizeof(p->sched_info));
1217 #endif
1218 #ifdef CONFIG_PREEMPT
1219 /*
1220 * During context-switch we hold precisely one spinlock, which
1221 * schedule_tail drops. (in the common case it's this_rq()->lock,
1222 * but it also can be p->switch_lock.) So we compensate with a count
1223 * of 1. Also, we want to start with kernel preemption disabled.
1224 */
1225 p->thread_info->preempt_count = 1;
1226 #endif
1227 }
1228
1229 /*
1230 * wake_up_new_task - wake up a newly created task for the first time.
1231 *
1232 * This function will do some initial scheduler statistics housekeeping
1233 * that must be done for every newly created context, then puts the task
1234 * on the runqueue and wakes it.
1235 */
1236 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1237 {
1238 unsigned long flags;
1239 int this_cpu, cpu;
1240 runqueue_t *rq, *this_rq;
1241
1242 rq = task_rq_lock(p, &flags);
1243 cpu = task_cpu(p);
1244 this_cpu = smp_processor_id();
1245
1246 BUG_ON(p->state != TASK_RUNNING);
1247
1248 /*
1249 * Forked process gets no burst to prevent fork bombs.
1250 */
1251 p->burst = 0;
1252
1253 if (likely(cpu == this_cpu)) {
1254 current->flags |= PF_NONSLEEP;
1255 activate_task(p, rq, 1);
1256 if (!(clone_flags & CLONE_VM))
1257 /*
1258 * The VM isn't cloned, so we're in a good position to
1259 * do child-runs-first in anticipation of an exec. This
1260 * usually avoids a lot of COW overhead.
1261 */
1262 set_need_resched();
1263 /*
1264 * We skip the following code due to cpu == this_cpu
1265 *
1266 * task_rq_unlock(rq, &flags);
1267 * this_rq = task_rq_lock(current, &flags);
1268 */
1269 this_rq = rq;
1270 } else {
1271 this_rq = cpu_rq(this_cpu);
1272
1273 /*
1274 * Not the local CPU - must adjust timestamp. This should
1275 * get optimised away in the !CONFIG_SMP case.
1276 */
1277 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1278 + rq->timestamp_last_tick;
1279 activate_task(p, rq, 0);
1280 preempt(p, rq);
1281
1282 /*
1283 * Parent and child are on different CPUs, now get the
1284 * parent runqueue to update the parent's ->flags:
1285 */
1286 task_rq_unlock(rq, &flags);
1287 this_rq = task_rq_lock(current, &flags);
1288 current->flags |= PF_NONSLEEP;
1289 }
1290 task_rq_unlock(this_rq, &flags);
1291 }
1292
1293 /**
1294 * finish_task_switch - clean up after a task-switch
1295 * @prev: the thread we just switched away from.
1296 *
1297 * We enter this with the runqueue still locked, and finish_arch_switch()
1298 * will unlock it along with doing any other architecture-specific cleanup
1299 * actions.
1300 *
1301 * Note that we may have delayed dropping an mm in context_switch(). If
1302 * so, we finish that here outside of the runqueue lock. (Doing it
1303 * with the lock held can cause deadlocks; see schedule() for
1304 * details.)
1305 */
1306 static inline void finish_task_switch(task_t *prev)
1307 __releases(rq->lock)
1308 {
1309 runqueue_t *rq = this_rq();
1310 struct mm_struct *mm = rq->prev_mm;
1311 unsigned long prev_task_flags;
1312
1313 rq->prev_mm = NULL;
1314
1315 /*
1316 * A task struct has one reference for the use as "current".
1317 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1318 * calls schedule one last time. The schedule call will never return,
1319 * and the scheduled task must drop that reference.
1320 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1321 * still held, otherwise prev could be scheduled on another cpu, die
1322 * there before we look at prev->state, and then the reference would
1323 * be dropped twice.
1324 * Manfred Spraul <manfred@colorfullife.com>
1325 */
1326 prev_task_flags = prev->flags;
1327 finish_arch_switch(rq, prev);
1328 if (mm)
1329 mmdrop(mm);
1330 if (unlikely(prev_task_flags & PF_DEAD))
1331 put_task_struct(prev);
1332 }
1333
1334 /**
1335 * schedule_tail - first thing a freshly forked thread must call.
1336 * @prev: the thread we just switched away from.
1337 */
1338 asmlinkage void schedule_tail(task_t *prev)
1339 __releases(rq->lock)
1340 {
1341 finish_task_switch(prev);
1342
1343 if (current->set_child_tid)
1344 put_user(current->pid, current->set_child_tid);
1345 }
1346
1347 /*
1348 * context_switch - switch to the new MM and the new
1349 * thread's register state.
1350 */
1351 static inline
1352 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1353 {
1354 struct mm_struct *mm = next->mm;
1355 struct mm_struct *oldmm = prev->active_mm;
1356
1357 if (unlikely(!mm)) {
1358 next->active_mm = oldmm;
1359 atomic_inc(&oldmm->mm_count);
1360 enter_lazy_tlb(oldmm, next);
1361 } else
1362 switch_mm(oldmm, mm, next);
1363
1364 if (unlikely(!prev->mm)) {
1365 prev->active_mm = NULL;
1366 WARN_ON(rq->prev_mm);
1367 rq->prev_mm = oldmm;
1368 }
1369
1370 /* Here we just switch the register state and the stack. */
1371 switch_to(prev, next, prev);
1372
1373 return prev;
1374 }
1375
1376 /*
1377 * nr_running, nr_uninterruptible and nr_context_switches:
1378 *
1379 * externally visible scheduler statistics: current number of runnable
1380 * threads, current number of uninterruptible-sleeping threads, total
1381 * number of context switches performed since bootup.
1382 */
1383 unsigned long nr_running(void)
1384 {
1385 unsigned long i, sum = 0;
1386
1387 for_each_online_cpu(i)
1388 sum += cpu_rq(i)->nr_running;
1389
1390 return sum;
1391 }
1392
1393 unsigned long nr_uninterruptible(void)
1394 {
1395 unsigned long i, sum = 0;
1396
1397 for_each_cpu(i)
1398 sum += cpu_rq(i)->nr_uninterruptible;
1399
1400 /*
1401 * Since we read the counters lockless, it might be slightly
1402 * inaccurate. Do not allow it to go below zero though:
1403 */
1404 if (unlikely((long)sum < 0))
1405 sum = 0;
1406
1407 return sum;
1408 }
1409
1410 unsigned long long nr_context_switches(void)
1411 {
1412 unsigned long long i, sum = 0;
1413
1414 for_each_cpu(i)
1415 sum += cpu_rq(i)->nr_switches;
1416
1417 return sum;
1418 }
1419
1420 unsigned long nr_iowait(void)
1421 {
1422 unsigned long i, sum = 0;
1423
1424 for_each_cpu(i)
1425 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1426
1427 return sum;
1428 }
1429
1430 #ifdef CONFIG_SMP
1431
1432 /*
1433 * double_rq_lock - safely lock two runqueues
1434 *
1435 * Note this does not disable interrupts like task_rq_lock,
1436 * you need to do so manually before calling.
1437 */
1438 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1439 __acquires(rq1->lock)
1440 __acquires(rq2->lock)
1441 {
1442 if (rq1 == rq2) {
1443 spin_lock(&rq1->lock);
1444 __acquire(rq2->lock); /* Fake it out ;) */
1445 } else {
1446 if (rq1 < rq2) {
1447 spin_lock(&rq1->lock);
1448 spin_lock(&rq2->lock);
1449 } else {
1450 spin_lock(&rq2->lock);
1451 spin_lock(&rq1->lock);
1452 }
1453 }
1454 }
1455
1456 /*
1457 * double_rq_unlock - safely unlock two runqueues
1458 *
1459 * Note this does not restore interrupts like task_rq_unlock,
1460 * you need to do so manually after calling.
1461 */
1462 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1463 __releases(rq1->lock)
1464 __releases(rq2->lock)
1465 {
1466 spin_unlock(&rq1->lock);
1467 if (rq1 != rq2)
1468 spin_unlock(&rq2->lock);
1469 else
1470 __release(rq2->lock);
1471 }
1472
1473 /*
1474 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1475 */
1476 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1477 __releases(this_rq->lock)
1478 __acquires(busiest->lock)
1479 __acquires(this_rq->lock)
1480 {
1481 if (unlikely(!spin_trylock(&busiest->lock))) {
1482 if (busiest < this_rq) {
1483 spin_unlock(&this_rq->lock);
1484 spin_lock(&busiest->lock);
1485 spin_lock(&this_rq->lock);
1486 } else
1487 spin_lock(&busiest->lock);
1488 }
1489 }
1490
1491 /*
1492 * find_idlest_cpu - find the least busy runqueue.
1493 */
1494 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1495 struct sched_domain *sd)
1496 {
1497 unsigned long load, min_load, this_load;
1498 int i, min_cpu;
1499 cpumask_t mask;
1500
1501 min_cpu = UINT_MAX;
1502 min_load = ULONG_MAX;
1503
1504 cpus_and(mask, sd->span, p->cpus_allowed);
1505
1506 for_each_cpu_mask(i, mask) {
1507 load = target_load(i);
1508
1509 if (load < min_load) {
1510 min_cpu = i;
1511 min_load = load;
1512
1513 /* break out early on an idle CPU: */
1514 if (!min_load)
1515 break;
1516 }
1517 }
1518
1519 /* add +1 to account for the new task */
1520 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1521
1522 /*
1523 * Would with the addition of the new task to the
1524 * current CPU there be an imbalance between this
1525 * CPU and the idlest CPU?
1526 *
1527 * Use half of the balancing threshold - new-context is
1528 * a good opportunity to balance.
1529 */
1530 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1531 return min_cpu;
1532
1533 return this_cpu;
1534 }
1535
1536 /*
1537 * If dest_cpu is allowed for this process, migrate the task to it.
1538 * This is accomplished by forcing the cpu_allowed mask to only
1539 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1540 * the cpu_allowed mask is restored.
1541 */
1542 static inline void sched_migrate_task(task_t *p, int dest_cpu)
1543 {
1544 migration_req_t req;
1545 runqueue_t *rq;
1546 unsigned long flags;
1547
1548 rq = task_rq_lock(p, &flags);
1549 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1550 || unlikely(cpu_is_offline(dest_cpu)))
1551 goto out;
1552
1553 /* force the process onto the specified CPU */
1554 if (migrate_task(p, dest_cpu, &req)) {
1555 /* Need to wait for migration thread (might exit: take ref). */
1556 struct task_struct *mt = rq->migration_thread;
1557 get_task_struct(mt);
1558 task_rq_unlock(rq, &flags);
1559 wake_up_process(mt);
1560 put_task_struct(mt);
1561 wait_for_completion(&req.done);
1562 return;
1563 }
1564 out:
1565 task_rq_unlock(rq, &flags);
1566 }
1567
1568 /*
1569 * sched_exec(): find the highest-level, exec-balance-capable
1570 * domain and try to migrate the task to the least loaded CPU.
1571 *
1572 * execve() is a valuable balancing opportunity, because at this point
1573 * the task has the smallest effective memory and cache footprint.
1574 */
1575 void sched_exec(void)
1576 {
1577 struct sched_domain *tmp, *sd = NULL;
1578 int new_cpu, this_cpu = get_cpu();
1579
1580 /* Prefer the current CPU if there's only this task running */
1581 if (this_rq()->nr_running <= 1)
1582 goto out;
1583
1584 for_each_domain(this_cpu, tmp)
1585 if (tmp->flags & SD_BALANCE_EXEC)
1586 sd = tmp;
1587
1588 if (sd) {
1589 schedstat_inc(sd, sbe_attempts);
1590 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1591 if (new_cpu != this_cpu) {
1592 schedstat_inc(sd, sbe_pushed);
1593 put_cpu();
1594 sched_migrate_task(current, new_cpu);
1595 return;
1596 }
1597 }
1598 out:
1599 put_cpu();
1600 }
1601
1602 /*
1603 * pull_task - move a task from a remote runqueue to the local runqueue.
1604 * Both runqueues must be locked.
1605 */
1606 static inline void pull_task(runqueue_t *src_rq, task_t *p,
1607 runqueue_t *this_rq, int this_cpu)
1608 {
1609 dequeue_task(p, src_rq);
1610 dec_nr_running(p, src_rq);
1611 set_task_cpu(p, this_cpu);
1612 inc_nr_running(p, this_rq);
1613 enqueue_task(p, this_rq);
1614 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1615 + this_rq->timestamp_last_tick;
1616 /*
1617 * Note that idle threads have a prio of MAX_PRIO, for this test
1618 * to be always true for them.
1619 */
1620 preempt(p, this_rq);
1621 }
1622
1623 /*
1624 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1625 */
1626 static inline int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1627 struct sched_domain *sd, enum idle_type idle)
1628 {
1629 /*
1630 * We do not migrate tasks that are:
1631 * 1) running (obviously), or
1632 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1633 * 3) are cache-hot on their current CPU.
1634 */
1635 if (task_running(rq, p))
1636 return 0;
1637 if (!cpu_isset(this_cpu, p->cpus_allowed))
1638 return 0;
1639
1640 /*
1641 * Aggressive migration if:
1642 * 1) the [whole] cpu is idle, or
1643 * 2) too many balance attempts have failed.
1644 */
1645
1646 if (cpu_and_siblings_are_idle(this_cpu) || \
1647 sd->nr_balance_failed > sd->cache_nice_tries)
1648 return 1;
1649
1650 if (task_hot(p, rq->timestamp_last_tick, sd))
1651 return 0;
1652 return 1;
1653 }
1654
1655 /*
1656 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1657 * as part of a balancing operation within "domain". Returns the number of
1658 * tasks moved.
1659 *
1660 * Called with both runqueues locked.
1661 */
1662 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1663 unsigned long max_nr_move, struct sched_domain *sd,
1664 enum idle_type idle)
1665 {
1666 struct list_head *head, *curr;
1667 int idx, pulled = 0;
1668 task_t *tmp;
1669
1670 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1671 goto out;
1672
1673 /* Start searching at priority 0: */
1674 idx = 0;
1675 skip_bitmap:
1676 if (!idx)
1677 idx = sched_find_first_bit(busiest->bitmap);
1678 else
1679 idx = find_next_bit(busiest->bitmap, MAX_PRIO, idx);
1680 if (idx >= MAX_PRIO)
1681 goto out;
1682
1683 head = busiest->queue + idx;
1684 curr = head->prev;
1685 skip_queue:
1686 tmp = list_entry(curr, task_t, run_list);
1687
1688 curr = curr->prev;
1689
1690 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1691 if (curr != head)
1692 goto skip_queue;
1693 idx++;
1694 goto skip_bitmap;
1695 }
1696
1697 #ifdef CONFIG_SCHEDSTATS
1698 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1699 schedstat_inc(sd, lb_hot_gained[idle]);
1700 #endif
1701
1702 pull_task(busiest, tmp, this_rq, this_cpu);
1703 pulled++;
1704
1705 /* We only want to steal up to the prescribed number of tasks. */
1706 if (pulled < max_nr_move) {
1707 if (curr != head)
1708 goto skip_queue;
1709 idx++;
1710 goto skip_bitmap;
1711 }
1712 out:
1713 /*
1714 * Right now, this is the only place pull_task() is called,
1715 * so we can safely collect pull_task() stats here rather than
1716 * inside pull_task().
1717 */
1718 schedstat_add(sd, lb_gained[idle], pulled);
1719 return pulled;
1720 }
1721
1722 /*
1723 * find_busiest_group finds and returns the busiest CPU group within the
1724 * domain. It calculates and returns the number of tasks which should be
1725 * moved to restore balance via the imbalance parameter.
1726 */
1727 static inline struct sched_group *
1728 find_busiest_group(struct sched_domain *sd, int this_cpu,
1729 unsigned long *imbalance, enum idle_type idle)
1730 {
1731 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1732 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1733
1734 max_load = this_load = total_load = total_pwr = 0;
1735
1736 do {
1737 unsigned long load;
1738 int local_group;
1739 int i;
1740
1741 local_group = cpu_isset(this_cpu, group->cpumask);
1742
1743 /* Tally up the load of all CPUs in the group */
1744 avg_load = 0;
1745
1746 for_each_cpu_mask(i, group->cpumask) {
1747 /* Bias balancing toward cpus of our domain */
1748 if (local_group)
1749 load = __target_load(i, idle);
1750 else
1751 load = __source_load(i, idle);
1752
1753 avg_load += load;
1754 }
1755
1756 total_load += avg_load;
1757 total_pwr += group->cpu_power;
1758
1759 /* Adjust by relative CPU power of the group */
1760 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1761
1762 if (local_group) {
1763 this_load = avg_load;
1764 this = group;
1765 goto nextgroup;
1766 } else if (avg_load > max_load) {
1767 max_load = avg_load;
1768 busiest = group;
1769 }
1770 nextgroup:
1771 group = group->next;
1772 } while (group != sd->groups);
1773
1774 if (!busiest || this_load >= max_load)
1775 goto out_balanced;
1776
1777 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1778
1779 if (this_load >= avg_load ||
1780 100*max_load <= sd->imbalance_pct*this_load)
1781 goto out_balanced;
1782
1783 /*
1784 * We're trying to get all the cpus to the average_load, so we don't
1785 * want to push ourselves above the average load, nor do we wish to
1786 * reduce the max loaded cpu below the average load, as either of these
1787 * actions would just result in more rebalancing later, and ping-pong
1788 * tasks around. Thus we look for the minimum possible imbalance.
1789 * Negative imbalances (*we* are more loaded than anyone else) will
1790 * be counted as no imbalance for these purposes -- we can't fix that
1791 * by pulling tasks to us. Be careful of negative numbers as they'll
1792 * appear as very large values with unsigned longs.
1793 */
1794 /* How much load to actually move to equalise the imbalance */
1795 *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1796 (avg_load - this_load) * this->cpu_power)
1797 / SCHED_LOAD_SCALE;
1798
1799 if (*imbalance < SCHED_LOAD_SCALE) {
1800 unsigned long pwr_now = 0, pwr_move = 0;
1801 unsigned long tmp;
1802
1803 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1804 *imbalance = 1;
1805 return busiest;
1806 }
1807
1808 /*
1809 * OK, we don't have enough imbalance to justify moving tasks,
1810 * however we may be able to increase total CPU power used by
1811 * moving them.
1812 */
1813
1814 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1815 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1816 pwr_now /= SCHED_LOAD_SCALE;
1817
1818 /* Amount of load we'd subtract */
1819 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1820 if (max_load > tmp)
1821 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1822 max_load - tmp);
1823
1824 /* Amount of load we'd add */
1825 if (max_load*busiest->cpu_power <
1826 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1827 tmp = max_load*busiest->cpu_power/this->cpu_power;
1828 else
1829 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1830 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1831 pwr_move /= SCHED_LOAD_SCALE;
1832
1833 /* Move if we gain throughput */
1834 if (pwr_move <= pwr_now)
1835 goto out_balanced;
1836
1837 *imbalance = 1;
1838 return busiest;
1839 }
1840
1841 /* Get rid of the scaling factor, rounding down as we divide */
1842 *imbalance = *imbalance / SCHED_LOAD_SCALE;
1843
1844 return busiest;
1845
1846 out_balanced:
1847 if (busiest && (idle == NEWLY_IDLE ||
1848 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1849 *imbalance = 1;
1850 return busiest;
1851 }
1852
1853 *imbalance = 0;
1854 return NULL;
1855 }
1856
1857 /*
1858 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1859 */
1860 static runqueue_t *find_busiest_queue(struct sched_group *group,
1861 enum idle_type idle)
1862 {
1863 unsigned long load, max_load = 0;
1864 runqueue_t *busiest = NULL;
1865 int i;
1866
1867 for_each_cpu_mask(i, group->cpumask) {
1868 load = __source_load(i, idle);
1869
1870 if (load > max_load) {
1871 max_load = load;
1872 busiest = cpu_rq(i);
1873 }
1874 }
1875
1876 return busiest;
1877 }
1878
1879 /*
1880 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1881 * tasks if there is an imbalance.
1882 *
1883 * Called with this_rq unlocked.
1884 */
1885 static inline int load_balance(int this_cpu, runqueue_t *this_rq,
1886 struct sched_domain *sd, enum idle_type idle)
1887 {
1888 struct sched_group *group;
1889 runqueue_t *busiest;
1890 unsigned long imbalance;
1891 int nr_moved;
1892
1893 spin_lock(&this_rq->lock);
1894 schedstat_inc(sd, lb_cnt[idle]);
1895
1896 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1897 if (!group) {
1898 schedstat_inc(sd, lb_nobusyg[idle]);
1899 goto out_balanced;
1900 }
1901
1902 busiest = find_busiest_queue(group, idle);
1903 if (!busiest) {
1904 schedstat_inc(sd, lb_nobusyq[idle]);
1905 goto out_balanced;
1906 }
1907
1908 /*
1909 * This should be "impossible", but since load
1910 * balancing is inherently racy and statistical,
1911 * it could happen in theory.
1912 */
1913 if (unlikely(busiest == this_rq)) {
1914 WARN_ON(1);
1915 goto out_balanced;
1916 }
1917
1918 schedstat_add(sd, lb_imbalance[idle], imbalance);
1919
1920 nr_moved = 0;
1921 if (busiest->nr_running > 1) {
1922 /*
1923 * Attempt to move tasks. If find_busiest_group has found
1924 * an imbalance but busiest->nr_running <= 1, the group is
1925 * still unbalanced. nr_moved simply stays zero, so it is
1926 * correctly treated as an imbalance.
1927 */
1928 double_lock_balance(this_rq, busiest);
1929 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1930 imbalance, sd, idle);
1931 spin_unlock(&busiest->lock);
1932 }
1933 spin_unlock(&this_rq->lock);
1934
1935 if (!nr_moved) {
1936 schedstat_inc(sd, lb_failed[idle]);
1937 sd->nr_balance_failed++;
1938
1939 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1940 int wake = 0;
1941
1942 spin_lock(&busiest->lock);
1943 if (!busiest->active_balance) {
1944 busiest->active_balance = 1;
1945 busiest->push_cpu = this_cpu;
1946 wake = 1;
1947 }
1948 spin_unlock(&busiest->lock);
1949 if (wake)
1950 wake_up_process(busiest->migration_thread);
1951
1952 /*
1953 * We've kicked active balancing, reset the failure
1954 * counter.
1955 */
1956 sd->nr_balance_failed = sd->cache_nice_tries;
1957 }
1958
1959 /*
1960 * We were unbalanced, but unsuccessful in move_tasks(),
1961 * so bump the balance_interval to lessen the lock contention.
1962 */
1963 if (sd->balance_interval < sd->max_interval)
1964 sd->balance_interval++;
1965 } else {
1966 sd->nr_balance_failed = 0;
1967
1968 /* We were unbalanced, so reset the balancing interval */
1969 sd->balance_interval = sd->min_interval;
1970 }
1971
1972 return nr_moved;
1973
1974 out_balanced:
1975 spin_unlock(&this_rq->lock);
1976
1977 schedstat_inc(sd, lb_balanced[idle]);
1978
1979 /* tune up the balancing interval */
1980 if (sd->balance_interval < sd->max_interval)
1981 sd->balance_interval *= 2;
1982
1983 return 0;
1984 }
1985
1986 /*
1987 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1988 * tasks if there is an imbalance.
1989 *
1990 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1991 * this_rq is locked.
1992 */
1993 static inline int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1994 struct sched_domain *sd)
1995 {
1996 struct sched_group *group;
1997 runqueue_t *busiest = NULL;
1998 unsigned long imbalance;
1999 int nr_moved = 0;
2000
2001 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2002 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2003 if (!group) {
2004 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2005 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2006 goto out;
2007 }
2008
2009 busiest = find_busiest_queue(group, NEWLY_IDLE);
2010 if (!busiest || busiest == this_rq) {
2011 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2012 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2013 goto out;
2014 }
2015
2016 /* Attempt to move tasks */
2017 double_lock_balance(this_rq, busiest);
2018
2019 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2020 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2021 imbalance, sd, NEWLY_IDLE);
2022 if (!nr_moved)
2023 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2024
2025 spin_unlock(&busiest->lock);
2026
2027 out:
2028 return nr_moved;
2029 }
2030
2031 /*
2032 * idle_balance is called by schedule() if this_cpu is about to become
2033 * idle. Attempts to pull tasks from other CPUs.
2034 */
2035 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2036 {
2037 struct sched_domain *sd;
2038
2039 for_each_domain(this_cpu, sd) {
2040 if (sd->flags & SD_BALANCE_NEWIDLE) {
2041 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2042 /* We've pulled tasks over so stop searching */
2043 break;
2044 }
2045 }
2046 }
2047 }
2048
2049 /*
2050 * active_load_balance is run by migration threads. It pushes running tasks
2051 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2052 * running on each physical CPU where possible, and avoids physical /
2053 * logical imbalances.
2054 *
2055 * Called with busiest_rq locked.
2056 */
2057 static inline void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2058 {
2059 struct sched_domain *sd;
2060 struct sched_group *cpu_group;
2061 runqueue_t *target_rq;
2062 cpumask_t visited_cpus;
2063 int cpu;
2064
2065 /*
2066 * Search for suitable CPUs to push tasks to in successively higher
2067 * domains with SD_LOAD_BALANCE set.
2068 */
2069 visited_cpus = CPU_MASK_NONE;
2070 for_each_domain(busiest_cpu, sd) {
2071 if (!(sd->flags & SD_LOAD_BALANCE))
2072 /* no more domains to search */
2073 break;
2074
2075 schedstat_inc(sd, alb_cnt);
2076
2077 cpu_group = sd->groups;
2078 do {
2079 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2080 if (busiest_rq->nr_running <= 1)
2081 /* no more tasks left to move */
2082 return;
2083 if (cpu_isset(cpu, visited_cpus))
2084 continue;
2085 cpu_set(cpu, visited_cpus);
2086 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2087 continue;
2088
2089 target_rq = cpu_rq(cpu);
2090 /*
2091 * This condition is "impossible", if it occurs
2092 * we need to fix it. Originally reported by
2093 * Bjorn Helgaas on a 128-cpu setup.
2094 */
2095 BUG_ON(busiest_rq == target_rq);
2096
2097 /* move a task from busiest_rq to target_rq */
2098 double_lock_balance(busiest_rq, target_rq);
2099 if (move_tasks(target_rq, cpu, busiest_rq,
2100 1, sd, SCHED_IDLE)) {
2101 schedstat_inc(sd, alb_pushed);
2102 } else {
2103 schedstat_inc(sd, alb_failed);
2104 }
2105 spin_unlock(&target_rq->lock);
2106 }
2107 cpu_group = cpu_group->next;
2108 } while (cpu_group != sd->groups);
2109 }
2110 }
2111
2112 /*
2113 * rebalance_tick will get called every timer tick, on every CPU.
2114 *
2115 * It checks each scheduling domain to see if it is due to be balanced,
2116 * and initiates a balancing operation if so.
2117 *
2118 * Balancing parameters are set up in arch_init_sched_domains.
2119 */
2120
2121 /* Don't have all balancing operations going off at once */
2122 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2123
2124 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2125 enum idle_type idle)
2126 {
2127 unsigned long old_load, this_load;
2128 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2129 struct sched_domain *sd;
2130
2131 /* Update our load */
2132 old_load = this_rq->cpu_load;
2133 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2134 /*
2135 * Round up the averaging division if load is increasing. This
2136 * prevents us from getting stuck on 9 if the load is 10, for
2137 * example.
2138 */
2139 if (this_load > old_load)
2140 old_load++;
2141 this_rq->cpu_load = (old_load + this_load) / 2;
2142
2143 for_each_domain(this_cpu, sd) {
2144 unsigned long interval;
2145
2146 if (!(sd->flags & SD_LOAD_BALANCE))
2147 continue;
2148
2149 interval = sd->balance_interval;
2150
2151 /* scale ms to jiffies */
2152 interval = msecs_to_jiffies(interval);
2153 if (unlikely(!interval))
2154 interval = 1;
2155
2156 if (idle != SCHED_IDLE || j - sd->last_balance >= interval) {
2157 if (load_balance(this_cpu, this_rq, sd, idle)) {
2158 /* We've pulled tasks over so no longer idle */
2159 idle = NOT_IDLE;
2160 }
2161 sd->last_balance += interval;
2162 }
2163 }
2164 }
2165 #else
2166 /*
2167 * on UP we do not need to balance between CPUs:
2168 */
2169 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2170 {
2171 }
2172 static inline void idle_balance(int cpu, runqueue_t *rq)
2173 {
2174 }
2175 #endif
2176
2177 static inline int wake_priority_sleeper(runqueue_t *rq)
2178 {
2179 int ret = 0;
2180 #ifdef CONFIG_SCHED_SMT
2181 spin_lock(&rq->lock);
2182 /*
2183 * If an SMT sibling task has been put to sleep for priority
2184 * reasons reschedule the idle task to see if it can now run.
2185 */
2186 if (rq->nr_running) {
2187 resched_task(rq->idle);
2188 ret = 1;
2189 }
2190 spin_unlock(&rq->lock);
2191 #endif
2192 return ret;
2193 }
2194
2195 DEFINE_PER_CPU(struct kernel_stat, kstat);
2196
2197 EXPORT_PER_CPU_SYMBOL(kstat);
2198
2199 /*
2200 * This is called on clock ticks and on context switches.
2201 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2202 */
2203 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2204 unsigned long long now)
2205 {
2206 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2207 p->sched_time += now - last;
2208 }
2209
2210 /*
2211 * Return current->sched_time plus any more ns on the sched_clock
2212 * that have not yet been banked.
2213 */
2214 unsigned long long current_sched_time(const task_t *tsk)
2215 {
2216 unsigned long long ns;
2217 unsigned long flags;
2218 local_irq_save(flags);
2219 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2220 ns = tsk->sched_time + (sched_clock() - ns);
2221 local_irq_restore(flags);
2222 return ns;
2223 }
2224
2225 /*
2226 * Account user cpu time to a process.
2227 * @p: the process that the cpu time gets accounted to
2228 * @hardirq_offset: the offset to subtract from hardirq_count()
2229 * @cputime: the cpu time spent in user space since the last update
2230 */
2231 void account_user_time(struct task_struct *p, cputime_t cputime)
2232 {
2233 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2234 cputime64_t tmp;
2235
2236 p->utime = cputime_add(p->utime, cputime);
2237
2238 /* Add user time to cpustat. */
2239 tmp = cputime_to_cputime64(cputime);
2240 if (TASK_NICE(p) > 0 || batch_task(p))
2241 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2242 else
2243 cpustat->user = cputime64_add(cpustat->user, tmp);
2244 }
2245
2246 /*
2247 * Account system cpu time to a process.
2248 * @p: the process that the cpu time gets accounted to
2249 * @hardirq_offset: the offset to subtract from hardirq_count()
2250 * @cputime: the cpu time spent in kernel space since the last update
2251 */
2252 void account_system_time(struct task_struct *p, int hardirq_offset,
2253 cputime_t cputime)
2254 {
2255 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2256 runqueue_t *rq = this_rq();
2257 cputime64_t tmp;
2258
2259 p->stime = cputime_add(p->stime, cputime);
2260
2261 /* Add system time to cpustat. */
2262 tmp = cputime_to_cputime64(cputime);
2263 if (hardirq_count() - hardirq_offset)
2264 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2265 else if (softirq_count())
2266 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2267 else if (p != rq->idle)
2268 cpustat->system = cputime64_add(cpustat->system, tmp);
2269 else if (atomic_read(&rq->nr_iowait) > 0)
2270 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2271 else
2272 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2273
2274 /* Account for system time used */
2275 acct_update_integrals(p);
2276 /* Update rss highwater mark */
2277 update_mem_hiwater(p);
2278 }
2279
2280 /*
2281 * Account for involuntary wait time.
2282 * @p: the process from which the cpu time has been stolen
2283 * @steal: the cpu time spent in involuntary wait
2284 */
2285 void account_steal_time(struct task_struct *p, cputime_t steal)
2286 {
2287 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2288 cputime64_t tmp = cputime_to_cputime64(steal);
2289 runqueue_t *rq = this_rq();
2290
2291 if (p == rq->idle) {
2292 p->stime = cputime_add(p->stime, steal);
2293 if (atomic_read(&rq->nr_iowait) > 0)
2294 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2295 else
2296 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2297 } else
2298 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2299 }
2300
2301 static void time_slice_expired(task_t *p, runqueue_t *rq)
2302 {
2303 set_tsk_need_resched(p);
2304 dequeue_task(p, rq);
2305 p->prio = effective_prio(p);
2306 p->time_slice = rr_interval(p);
2307 enqueue_task(p, rq);
2308 }
2309
2310 /*
2311 * This function gets called by the timer code, with HZ frequency.
2312 * We call it with interrupts disabled.
2313 */
2314 void scheduler_tick(void)
2315 {
2316 int cpu = smp_processor_id();
2317 runqueue_t *rq = this_rq();
2318 task_t *p = current;
2319 unsigned long debit, expired_balance = rq->nr_running;
2320 unsigned long long now = sched_clock();
2321
2322 update_cpu_clock(p, rq, now);
2323
2324 rq->timestamp_last_tick = now;
2325
2326 if (p == rq->idle) {
2327 if (wake_priority_sleeper(rq))
2328 goto out;
2329 rebalance_tick(cpu, rq, SCHED_IDLE);
2330 return;
2331 }
2332
2333 /* Task might have expired already, but not scheduled off yet */
2334 if (unlikely(!task_queued(p))) {
2335 set_tsk_need_resched(p);
2336 goto out;
2337 }
2338 /*
2339 * SCHED_FIFO tasks never run out of timeslice.
2340 */
2341 if (unlikely(p->policy == SCHED_FIFO)) {
2342 expired_balance = 0;
2343 goto out;
2344 }
2345
2346 spin_lock(&rq->lock);
2347 debit = ns_diff(rq->timestamp_last_tick, p->timestamp);
2348 p->ns_debit += debit;
2349 if (p->ns_debit < NSJIFFY)
2350 goto out_unlock;
2351 p->ns_debit %= NSJIFFY;
2352 /*
2353 * Tasks lose burst each time they use up a full slice().
2354 */
2355 if (!--p->slice) {
2356 dec_burst(p);
2357 p->slice = slice(p);
2358 time_slice_expired(p, rq);
2359 p->totalrun = 0;
2360 goto out_unlock;
2361 }
2362 /*
2363 * Tasks that run out of time_slice but still have slice left get
2364 * requeued with a lower priority && RR_INTERVAL time_slice.
2365 */
2366 if (!--p->time_slice) {
2367 time_slice_expired(p, rq);
2368 goto out_unlock;
2369 }
2370 rq->cache_ticks++;
2371 if (rq->preempted && rq->cache_ticks >= cache_delay) {
2372 set_tsk_need_resched(p);
2373 goto out_unlock;
2374 }
2375 expired_balance = 0;
2376 out_unlock:
2377 spin_unlock(&rq->lock);
2378 out:
2379 if (expired_balance > 1)
2380 rebalance_tick(cpu, rq, NOT_IDLE);
2381 }
2382
2383 #ifdef CONFIG_SCHED_SMT
2384 static inline void wakeup_busy_runqueue(runqueue_t *rq)
2385 {
2386 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2387 if (rq->curr == rq->idle && rq->nr_running)
2388 resched_task(rq->idle);
2389 }
2390
2391 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2392 {
2393 struct sched_domain *sd = this_rq->sd;
2394 cpumask_t sibling_map;
2395 int i;
2396
2397 if (!(sd->flags & SD_SHARE_CPUPOWER))
2398 return;
2399
2400 /*
2401 * Unlock the current runqueue because we have to lock in
2402 * CPU order to avoid deadlocks. Caller knows that we might
2403 * unlock. We keep IRQs disabled.
2404 */
2405 spin_unlock(&this_rq->lock);
2406
2407 sibling_map = sd->span;
2408
2409 for_each_cpu_mask(i, sibling_map)
2410 spin_lock(&cpu_rq(i)->lock);
2411 /*
2412 * We clear this CPU from the mask. This both simplifies the
2413 * inner loop and keps this_rq locked when we exit:
2414 */
2415 cpu_clear(this_cpu, sibling_map);
2416
2417 for_each_cpu_mask(i, sibling_map) {
2418 runqueue_t *smt_rq = cpu_rq(i);
2419
2420 wakeup_busy_runqueue(smt_rq);
2421 }
2422
2423 for_each_cpu_mask(i, sibling_map)
2424 spin_unlock(&cpu_rq(i)->lock);
2425 /*
2426 * We exit with this_cpu's rq still held and IRQs
2427 * still disabled:
2428 */
2429 }
2430
2431 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2432 {
2433 struct sched_domain *sd = this_rq->sd;
2434 cpumask_t sibling_map;
2435 int ret = 0, i;
2436 task_t *p;
2437
2438 if (!(sd->flags & SD_SHARE_CPUPOWER))
2439 return 0;
2440
2441 /*
2442 * The same locking rules and details apply as for
2443 * wake_sleeping_dependent():
2444 */
2445 spin_unlock(&this_rq->lock);
2446 sibling_map = sd->span;
2447 for_each_cpu_mask(i, sibling_map)
2448 spin_lock(&cpu_rq(i)->lock);
2449 cpu_clear(this_cpu, sibling_map);
2450
2451 /*
2452 * Establish next task to be run - it might have gone away because
2453 * we released the runqueue lock above:
2454 */
2455 if (!this_rq->nr_running)
2456 goto out_unlock;
2457
2458 p = list_entry(this_rq->queue[sched_find_first_bit(this_rq->bitmap)].next,
2459 task_t, run_list);
2460
2461 for_each_cpu_mask(i, sibling_map) {
2462 runqueue_t *smt_rq = cpu_rq(i);
2463 task_t *smt_curr = smt_rq->curr;
2464
2465 /* Kernel threads do not participate in dependent sleeping */
2466 if (!p->mm || !smt_curr->mm || rt_task(p))
2467 goto check_smt_task;
2468
2469 /*
2470 * If a user task with lower static priority than the
2471 * running task on the SMT sibling is trying to schedule,
2472 * delay it till there is proportionately less timeslice
2473 * left of the sibling task to prevent a lower priority
2474 * task from using an unfair proportion of the
2475 * physical cpu's resources. -ck
2476 */
2477 if (rt_task(smt_curr)) {
2478 /*
2479 * With real time tasks we run non-rt tasks only
2480 * per_cpu_gain% of the time.
2481 */
2482 if ((jiffies % DEF_TIMESLICE) >
2483 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2484 ret = 1;
2485 else if (batch_task(p))
2486 ret = 1;
2487 } else {
2488 if (((smt_curr->slice * (100 - sd->per_cpu_gain) /
2489 100) > slice(p)))
2490 ret = 1;
2491 else if (batch_task(p) && !batch_task(smt_curr) &&
2492 smt_curr->slice * sd->per_cpu_gain >
2493 slice(smt_curr))
2494 /*
2495 * With batch tasks they run just the last
2496 * per_cpu_gain percent of the smt task's slice.
2497 */
2498 ret = 1;
2499 }
2500
2501 check_smt_task:
2502 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2503 rt_task(smt_curr))
2504 continue;
2505 if (!p->mm) {
2506 wakeup_busy_runqueue(smt_rq);
2507 continue;
2508 }
2509
2510 /*
2511 * Reschedule a lower priority task on the SMT sibling,
2512 * or wake it up if it has been put to sleep for priority
2513 * reasons to see if it should run now.
2514 */
2515 if (rt_task(p)) {
2516 if ((jiffies % DEF_TIMESLICE) >
2517 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2518 resched_task(smt_curr);
2519 else if (batch_task(smt_curr))
2520 resched_task(smt_curr);
2521 } else {
2522 if ((p->slice * (100 - sd->per_cpu_gain) / 100) >
2523 slice(smt_curr))
2524 resched_task(smt_curr);
2525 else if (batch_task(smt_curr) && !batch_task(p) &&
2526 p->slice * sd->per_cpu_gain > slice(p))
2527 resched_task(smt_curr);
2528 else
2529 wakeup_busy_runqueue(smt_rq);
2530 }
2531 }
2532 out_unlock:
2533 for_each_cpu_mask(i, sibling_map)
2534 spin_unlock(&cpu_rq(i)->lock);
2535 return ret;
2536 }
2537 #else
2538 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2539 {
2540 }
2541
2542 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2543 {
2544 return 0;
2545 }
2546 #endif
2547
2548 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2549
2550 void fastcall add_preempt_count(int val)
2551 {
2552 /*
2553 * Underflow?
2554 */
2555 BUG_ON(((int)preempt_count() < 0));
2556 preempt_count() += val;
2557 /*
2558 * Spinlock count overflowing soon?
2559 */
2560 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2561 }
2562 EXPORT_SYMBOL(add_preempt_count);
2563
2564 void fastcall sub_preempt_count(int val)
2565 {
2566 /*
2567 * Underflow?
2568 */
2569 BUG_ON(val > preempt_count());
2570 /*
2571 * Is the spinlock portion underflowing?
2572 */
2573 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2574 preempt_count() -= val;
2575 }
2576 EXPORT_SYMBOL(sub_preempt_count);
2577
2578 #endif
2579
2580 /*
2581 * schedule() is the main scheduler function.
2582 */
2583 asmlinkage void __sched schedule(void)
2584 {
2585 long *switch_count;
2586 task_t *prev, *next;
2587 runqueue_t *rq;
2588 struct list_head *queue;
2589 unsigned long long now;
2590 unsigned long debit;
2591 int cpu, idx;
2592
2593 /*
2594 * Test if we are atomic. Since do_exit() needs to call into
2595 * schedule() atomically, we ignore that path for now.
2596 * Otherwise, whine if we are scheduling when we should not be.
2597 */
2598 if (likely(!current->exit_state)) {
2599 if (unlikely(in_atomic())) {
2600 printk(KERN_ERR "scheduling while atomic: "
2601 "%s/0x%08x/%d\n",
2602 current->comm, preempt_count(), current->pid);
2603 dump_stack();
2604 }
2605 }
2606 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2607
2608 need_resched:
2609 preempt_disable();
2610 prev = current;
2611 release_kernel_lock(prev);
2612 need_resched_nonpreemptible:
2613 rq = this_rq();
2614
2615 /*
2616 * The idle thread is not allowed to schedule!
2617 * Remove this check after it has been exercised a bit.
2618 */
2619 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2620 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2621 dump_stack();
2622 }
2623
2624 schedstat_inc(rq, sched_cnt);
2625 now = sched_clock();
2626
2627 spin_lock_irq(&rq->lock);
2628 prev->runtime = ns_diff(now, prev->timestamp);
2629 debit = ns_diff(now, rq->timestamp_last_tick) % NSJIFFY;
2630 prev->ns_debit += debit;
2631
2632 if (unlikely(prev->flags & PF_DEAD))
2633 prev->state = EXIT_DEAD;
2634
2635 switch_count = &prev->nivcsw;
2636 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2637 switch_count = &prev->nvcsw;
2638 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2639 unlikely(signal_pending(prev))))
2640 prev->state = TASK_RUNNING;
2641 else {
2642 if (prev->state == TASK_UNINTERRUPTIBLE) {
2643 prev->flags |= PF_NONSLEEP;
2644 rq->nr_uninterruptible++;
2645 }
2646 deactivate_task(prev, rq);
2647 }
2648 }
2649
2650 cpu = smp_processor_id();
2651 if (unlikely(!rq->nr_running)) {
2652 go_idle:
2653 idle_balance(cpu, rq);
2654 if (!rq->nr_running) {
2655 next = rq->idle;
2656 wake_sleeping_dependent(cpu, rq);
2657 /*
2658 * wake_sleeping_dependent() might have released
2659 * the runqueue, so break out if we got new
2660 * tasks meanwhile:
2661 */
2662 if (!rq->nr_running)
2663 goto switch_tasks;
2664 }
2665 } else {
2666 if (dependent_sleeper(cpu, rq)) {
2667 next = rq->idle;
2668 goto switch_tasks;
2669 }
2670 /*
2671 * dependent_sleeper() releases and reacquires the runqueue
2672 * lock, hence go into the idle loop if the rq went
2673 * empty meanwhile:
2674 */
2675 if (unlikely(!rq->nr_running))
2676 goto go_idle;
2677 }
2678
2679 idx = sched_find_first_bit(rq->bitmap);
2680 queue = rq->queue + idx;
2681 next = list_entry(queue->next, task_t, run_list);
2682
2683 switch_tasks:
2684 if (next == rq->idle)
2685 schedstat_inc(rq, sched_goidle);
2686 prev->timestamp = now;
2687 if (unlikely(next->flags & PF_YIELDED)) {
2688 /*
2689 * Tasks that have yield()ed get requeued at normal priority
2690 */
2691 int newprio = effective_prio(next);
2692 next->flags &= ~PF_YIELDED;
2693 if (newprio != next->prio) {
2694 dequeue_task(next, rq);
2695 next->prio = newprio;
2696 enqueue_task(next, rq);
2697 }
2698 }
2699
2700 prefetch(next);
2701 clear_tsk_need_resched(prev);
2702 rcu_qsctr_inc(task_cpu(prev));
2703
2704 update_cpu_clock(prev, rq, now);
2705
2706 sched_info_switch(prev, next);
2707 if (likely(prev != next)) {
2708 rq->preempted = 0;
2709 rq->cache_ticks = 0;
2710 next->timestamp = now;
2711 rq->nr_switches++;
2712 rq->curr = next;
2713 ++*switch_count;
2714
2715 prepare_arch_switch(rq, next);
2716 prev = context_switch(rq, prev, next);
2717 barrier();
2718
2719 finish_task_switch(prev);
2720 } else
2721 spin_unlock_irq(&rq->lock);
2722
2723 prev = current;
2724 if (unlikely(reacquire_kernel_lock(prev) < 0))
2725 goto need_resched_nonpreemptible;
2726 preempt_enable_no_resched();
2727 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2728 goto need_resched;
2729 }
2730
2731 EXPORT_SYMBOL(schedule);
2732
2733 #ifdef CONFIG_PREEMPT
2734 /*
2735 * this is is the entry point to schedule() from in-kernel preemption
2736 * off of preempt_enable. Kernel preemptions off return from interrupt
2737 * occur there and call schedule directly.
2738 */
2739 asmlinkage void __sched preempt_schedule(void)
2740 {
2741 struct thread_info *ti = current_thread_info();
2742 #ifdef CONFIG_PREEMPT_BKL
2743 struct task_struct *task = current;
2744 int saved_lock_depth;
2745 #endif
2746 /*
2747 * If there is a non-zero preempt_count or interrupts are disabled,
2748 * we do not want to preempt the current task. Just return..
2749 */
2750 if (unlikely(ti->preempt_count || irqs_disabled()))
2751 return;
2752
2753 need_resched:
2754 add_preempt_count(PREEMPT_ACTIVE);
2755 /*
2756 * We keep the big kernel semaphore locked, but we
2757 * clear ->lock_depth so that schedule() doesnt
2758 * auto-release the semaphore:
2759 */
2760 #ifdef CONFIG_PREEMPT_BKL
2761 saved_lock_depth = task->lock_depth;
2762 task->lock_depth = -1;
2763 #endif
2764 schedule();
2765 #ifdef CONFIG_PREEMPT_BKL
2766 task->lock_depth = saved_lock_depth;
2767 #endif
2768 sub_preempt_count(PREEMPT_ACTIVE);
2769
2770 /* we could miss a preemption opportunity between schedule and now */
2771 barrier();
2772 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2773 goto need_resched;
2774 }
2775
2776 EXPORT_SYMBOL(preempt_schedule);
2777
2778 /*
2779 * this is is the entry point to schedule() from kernel preemption
2780 * off of irq context.
2781 * Note, that this is called and return with irqs disabled. This will
2782 * protect us against recursive calling from irq.
2783 */
2784 asmlinkage void __sched preempt_schedule_irq(void)
2785 {
2786 struct thread_info *ti = current_thread_info();
2787 #ifdef CONFIG_PREEMPT_BKL
2788 struct task_struct *task = current;
2789 int saved_lock_depth;
2790 #endif
2791 /* Catch callers which need to be fixed*/
2792 BUG_ON(ti->preempt_count || !irqs_disabled());
2793
2794 need_resched:
2795 add_preempt_count(PREEMPT_ACTIVE);
2796 /*
2797 * We keep the big kernel semaphore locked, but we
2798 * clear ->lock_depth so that schedule() doesnt
2799 * auto-release the semaphore:
2800 */
2801 #ifdef CONFIG_PREEMPT_BKL
2802 saved_lock_depth = task->lock_depth;
2803 task->lock_depth = -1;
2804 #endif
2805 local_irq_enable();
2806 schedule();
2807 local_irq_disable();
2808 #ifdef CONFIG_PREEMPT_BKL
2809 task->lock_depth = saved_lock_depth;
2810 #endif
2811 sub_preempt_count(PREEMPT_ACTIVE);
2812
2813 /* we could miss a preemption opportunity between schedule and now */
2814 barrier();
2815 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2816 goto need_resched;
2817 }
2818
2819 #endif /* CONFIG_PREEMPT */
2820
2821 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2822 {
2823 task_t *p = curr->task;
2824 return try_to_wake_up(p, mode, sync);
2825 }
2826
2827 EXPORT_SYMBOL(default_wake_function);
2828
2829 /*
2830 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2831 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2832 * number) then we wake all the non-exclusive tasks and one exclusive task.
2833 *
2834 * There are circumstances in which we can try to wake a task which has already
2835 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2836 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2837 */
2838 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2839 int nr_exclusive, int sync, void *key)
2840 {
2841 struct list_head *tmp, *next;
2842
2843 list_for_each_safe(tmp, next, &q->task_list) {
2844 wait_queue_t *curr;
2845 unsigned flags;
2846 curr = list_entry(tmp, wait_queue_t, task_list);
2847 flags = curr->flags;
2848 if (curr->func(curr, mode, sync, key) &&
2849 (flags & WQ_FLAG_EXCLUSIVE) &&
2850 !--nr_exclusive)
2851 break;
2852 }
2853 }
2854
2855 /**
2856 * __wake_up - wake up threads blocked on a waitqueue.
2857 * @q: the waitqueue
2858 * @mode: which threads
2859 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2860 * @key: is directly passed to the wakeup function
2861 */
2862 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2863 int nr_exclusive, void *key)
2864 {
2865 unsigned long flags;
2866
2867 spin_lock_irqsave(&q->lock, flags);
2868 __wake_up_common(q, mode, nr_exclusive, 0, key);
2869 spin_unlock_irqrestore(&q->lock, flags);
2870 }
2871
2872 EXPORT_SYMBOL(__wake_up);
2873
2874 /*
2875 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2876 */
2877 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2878 {
2879 __wake_up_common(q, mode, 1, 0, NULL);
2880 }
2881
2882 /**
2883 * __wake_up_sync - wake up threads blocked on a waitqueue.
2884 * @q: the waitqueue
2885 * @mode: which threads
2886 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2887 *
2888 * The sync wakeup differs that the waker knows that it will schedule
2889 * away soon, so while the target thread will be woken up, it will not
2890 * be migrated to another CPU - ie. the two threads are 'synchronized'
2891 * with each other. This can prevent needless bouncing between CPUs.
2892 *
2893 * On UP it can prevent extra preemption.
2894 */
2895 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2896 {
2897 unsigned long flags;
2898 int sync = 1;
2899
2900 if (unlikely(!q))
2901 return;
2902
2903 if (unlikely(!nr_exclusive))
2904 sync = 0;
2905
2906 spin_lock_irqsave(&q->lock, flags);
2907 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2908 spin_unlock_irqrestore(&q->lock, flags);
2909 }
2910 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2911
2912 void fastcall complete(struct completion *x)
2913 {
2914 unsigned long flags;
2915
2916 spin_lock_irqsave(&x->wait.lock, flags);
2917 x->done++;
2918 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2919 1, 0, NULL);
2920 spin_unlock_irqrestore(&x->wait.lock, flags);
2921 }
2922 EXPORT_SYMBOL(complete);
2923
2924 void fastcall complete_all(struct completion *x)
2925 {
2926 unsigned long flags;
2927
2928 spin_lock_irqsave(&x->wait.lock, flags);
2929 x->done += UINT_MAX/2;
2930 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2931 0, 0, NULL);
2932 spin_unlock_irqrestore(&x->wait.lock, flags);
2933 }
2934 EXPORT_SYMBOL(complete_all);
2935
2936 void fastcall __sched wait_for_completion(struct completion *x)
2937 {
2938 might_sleep();
2939 spin_lock_irq(&x->wait.lock);
2940 if (!x->done) {
2941 DECLARE_WAITQUEUE(wait, current);
2942
2943 wait.flags |= WQ_FLAG_EXCLUSIVE;
2944 __add_wait_queue_tail(&x->wait, &wait);
2945 do {
2946 __set_current_state(TASK_UNINTERRUPTIBLE);
2947 spin_unlock_irq(&x->wait.lock);
2948 schedule();
2949 spin_lock_irq(&x->wait.lock);
2950 } while (!x->done);
2951 __remove_wait_queue(&x->wait, &wait);
2952 }
2953 x->done--;
2954 spin_unlock_irq(&x->wait.lock);
2955 }
2956 EXPORT_SYMBOL(wait_for_completion);
2957
2958 unsigned long fastcall __sched
2959 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
2960 {
2961 might_sleep();
2962
2963 spin_lock_irq(&x->wait.lock);
2964 if (!x->done) {
2965 DECLARE_WAITQUEUE(wait, current);
2966
2967 wait.flags |= WQ_FLAG_EXCLUSIVE;
2968 __add_wait_queue_tail(&x->wait, &wait);
2969 do {
2970 __set_current_state(TASK_UNINTERRUPTIBLE);
2971 spin_unlock_irq(&x->wait.lock);
2972 timeout = schedule_timeout(timeout);
2973 spin_lock_irq(&x->wait.lock);
2974 if (!timeout) {
2975 __remove_wait_queue(&x->wait, &wait);
2976 goto out;
2977 }
2978 } while (!x->done);
2979 __remove_wait_queue(&x->wait, &wait);
2980 }
2981 x->done--;
2982 out:
2983 spin_unlock_irq(&x->wait.lock);
2984 return timeout;
2985 }
2986 EXPORT_SYMBOL(wait_for_completion_timeout);
2987
2988 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
2989 {
2990 int ret = 0;
2991
2992 might_sleep();
2993
2994 spin_lock_irq(&x->wait.lock);
2995 if (!x->done) {
2996 DECLARE_WAITQUEUE(wait, current);
2997
2998 wait.flags |= WQ_FLAG_EXCLUSIVE;
2999 __add_wait_queue_tail(&x->wait, &wait);
3000 do {
3001 if (signal_pending(current)) {
3002 ret = -ERESTARTSYS;
3003 __remove_wait_queue(&x->wait, &wait);
3004 goto out;
3005 }
3006 __set_current_state(TASK_INTERRUPTIBLE);
3007 spin_unlock_irq(&x->wait.lock);
3008 schedule();
3009 spin_lock_irq(&x->wait.lock);
3010 } while (!x->done);
3011 __remove_wait_queue(&x->wait, &wait);
3012 }
3013 x->done--;
3014 out:
3015 spin_unlock_irq(&x->wait.lock);
3016
3017 return ret;
3018 }
3019 EXPORT_SYMBOL(wait_for_completion_interruptible);
3020
3021 unsigned long fastcall __sched
3022 wait_for_completion_interruptible_timeout(struct completion *x,
3023 unsigned long timeout)
3024 {
3025 might_sleep();
3026
3027 spin_lock_irq(&x->wait.lock);
3028 if (!x->done) {
3029 DECLARE_WAITQUEUE(wait, current);
3030
3031 wait.flags |= WQ_FLAG_EXCLUSIVE;
3032 __add_wait_queue_tail(&x->wait, &wait);
3033 do {
3034 if (signal_pending(current)) {
3035 timeout = -ERESTARTSYS;
3036 __remove_wait_queue(&x->wait, &wait);
3037 goto out;
3038 }
3039 __set_current_state(TASK_INTERRUPTIBLE);
3040 spin_unlock_irq(&x->wait.lock);
3041 timeout = schedule_timeout(timeout);
3042 spin_lock_irq(&x->wait.lock);
3043 if (!timeout) {
3044 __remove_wait_queue(&x->wait, &wait);
3045 goto out;
3046 }
3047 } while (!x->done);
3048 __remove_wait_queue(&x->wait, &wait);
3049 }
3050 x->done--;
3051 out:
3052 spin_unlock_irq(&x->wait.lock);
3053 return timeout;
3054 }
3055 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3056
3057
3058 #define SLEEP_ON_VAR \
3059 unsigned long flags; \
3060 wait_queue_t wait; \
3061 init_waitqueue_entry(&wait, current);
3062
3063 #define SLEEP_ON_HEAD \
3064 spin_lock_irqsave(&q->lock,flags); \
3065 __add_wait_queue(q, &wait); \
3066 spin_unlock(&q->lock);
3067
3068 #define SLEEP_ON_TAIL \
3069 spin_lock_irq(&q->lock); \
3070 __remove_wait_queue(q, &wait); \
3071 spin_unlock_irqrestore(&q->lock, flags);
3072
3073 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3074 {
3075 SLEEP_ON_VAR
3076
3077 current->state = TASK_INTERRUPTIBLE;
3078
3079 SLEEP_ON_HEAD
3080 schedule();
3081 SLEEP_ON_TAIL
3082 }
3083
3084 EXPORT_SYMBOL(interruptible_sleep_on);
3085
3086 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3087 {
3088 SLEEP_ON_VAR
3089
3090 current->state = TASK_INTERRUPTIBLE;
3091
3092 SLEEP_ON_HEAD
3093 timeout = schedule_timeout(timeout);
3094 SLEEP_ON_TAIL
3095
3096 return timeout;
3097 }
3098
3099 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3100
3101 void fastcall __sched sleep_on(wait_queue_head_t *q)
3102 {
3103 SLEEP_ON_VAR
3104
3105 current->state = TASK_UNINTERRUPTIBLE;
3106
3107 SLEEP_ON_HEAD
3108 schedule();
3109 SLEEP_ON_TAIL
3110 }
3111
3112 EXPORT_SYMBOL(sleep_on);
3113
3114 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3115 {
3116 SLEEP_ON_VAR
3117
3118 current->state = TASK_UNINTERRUPTIBLE;
3119
3120 SLEEP_ON_HEAD
3121 timeout = schedule_timeout(timeout);
3122 SLEEP_ON_TAIL
3123
3124 return timeout;
3125 }
3126
3127 EXPORT_SYMBOL(sleep_on_timeout);
3128
3129 void set_user_nice(task_t *p, long nice)
3130 {
3131 unsigned long flags;
3132 runqueue_t *rq;
3133 int queued, old_prio, new_prio, delta;
3134
3135 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3136 return;
3137 /*
3138 * We have to be careful, if called from sys_setpriority(),
3139 * the task might be in the middle of scheduling on another CPU.
3140 */
3141 rq = task_rq_lock(p, &flags);
3142 /*
3143 * The RT priorities are set via sched_setscheduler(), but we still
3144 * allow the 'normal' nice value to be set - but as expected
3145 * it wont have any effect on scheduling until the task is
3146 * not SCHED_NORMAL:
3147 */
3148 if (rt_task(p)) {
3149 p->static_prio = NICE_TO_PRIO(nice);
3150 goto out_unlock;
3151 }
3152 if ((queued = task_queued(p))) {
3153 dequeue_task(p, rq);
3154 dec_prio_bias(rq, p->static_prio);
3155 }
3156
3157 old_prio = p->prio;
3158 new_prio = NICE_TO_PRIO(nice);
3159 delta = new_prio - old_prio;
3160 p->static_prio = NICE_TO_PRIO(nice);
3161 p->prio += delta;
3162
3163 if (queued) {
3164 enqueue_task(p, rq);
3165 inc_prio_bias(rq, p->static_prio);
3166 /*
3167 * If the task increased its priority or is running and
3168 * lowered its priority, then reschedule its CPU:
3169 */
3170 if (delta < 0 || ((delta > 0 || batch_task(p)) &&
3171 task_running(rq, p)))
3172 resched_task(rq->curr);
3173 }
3174 out_unlock:
3175 task_rq_unlock(rq, &flags);
3176 }
3177
3178 EXPORT_SYMBOL(set_user_nice);
3179
3180 /*
3181 * can_nice - check if a task can reduce its nice value
3182 * @p: task
3183 * @nice: nice value
3184 */
3185 int can_nice(const task_t *p, const int nice)
3186 {
3187 /* convert nice value [19,-20] to rlimit style value [0,39] */
3188 int nice_rlim = 19 - nice;
3189 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3190 capable(CAP_SYS_NICE));
3191 }
3192
3193 #ifdef __ARCH_WANT_SYS_NICE
3194
3195 /*
3196 * sys_nice - change the priority of the current process.
3197 * @increment: priority increment
3198 *
3199 * sys_setpriority is a more generic, but much slower function that
3200 * does similar things.
3201 */
3202 asmlinkage long sys_nice(int increment)
3203 {
3204 int retval;
3205 long nice;
3206
3207 /*
3208 * Setpriority might change our priority at the same moment.
3209 * We don't have to worry. Conceptually one call occurs first
3210 * and we have a single winner.
3211 */
3212 if (increment < -40)
3213 increment = -40;
3214 if (increment > 40)
3215 increment = 40;
3216
3217 nice = PRIO_TO_NICE(current->static_prio) + increment;
3218 if (nice < -20)
3219 nice = -20;
3220 if (nice > 19)
3221 nice = 19;
3222
3223 if (increment < 0 && !can_nice(current, nice))
3224 return -EPERM;
3225
3226 retval = security_task_setnice(current, nice);
3227 if (retval)
3228 return retval;
3229
3230 set_user_nice(current, nice);
3231 return 0;
3232 }
3233
3234 #endif
3235
3236 /**
3237 * task_prio - return the priority value of a given task.
3238 * @p: the task in question.
3239 *
3240 * This is the priority value as seen by users in /proc.
3241 * RT tasks are offset by -200. Normal tasks are centered
3242 * around 0, value goes from -16 to +15.
3243 */
3244 int task_prio(const task_t *p)
3245 {
3246 return p->prio - MAX_RT_PRIO;
3247 }
3248
3249 /**
3250 * task_nice - return the nice value of a given task.
3251 * @p: the task in question.
3252 */
3253 int task_nice(const task_t *p)
3254 {
3255 return TASK_NICE(p);
3256 }
3257 EXPORT_SYMBOL_GPL(task_nice);
3258
3259 /**
3260 * idle_cpu - is a given cpu idle currently?
3261 * @cpu: the processor in question.
3262 */
3263 int idle_cpu(int cpu)
3264 {
3265 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3266 }
3267
3268 EXPORT_SYMBOL_GPL(idle_cpu);
3269
3270 /**
3271 * idle_task - return the idle task for a given cpu.
3272 * @cpu: the processor in question.
3273 */
3274 task_t *idle_task(int cpu)
3275 {
3276 return cpu_rq(cpu)->idle;
3277 }
3278
3279 /**
3280 * find_process_by_pid - find a process with a matching PID value.
3281 * @pid: the pid in question.
3282 */
3283 static inline task_t *find_process_by_pid(pid_t pid)
3284 {
3285 return pid ? find_task_by_pid(pid) : current;
3286 }
3287
3288 /* Actually do priority change: must hold rq lock. */
3289 static void __setscheduler(struct task_struct *p, int policy, int prio)
3290 {
3291 BUG_ON(task_queued(p));
3292 p->policy = policy;
3293 p->rt_priority = prio;
3294 if (SCHED_RT(policy))
3295 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3296 else
3297 p->prio = p->static_prio;
3298 }
3299
3300 /**
3301 * sched_setscheduler - change the scheduling policy and/or RT priority of
3302 * a thread.
3303 * @p: the task in question.
3304 * @policy: new policy.
3305 * @param: structure containing the new RT priority.
3306 */
3307 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3308 {
3309 int retval;
3310 int queued, oldprio, oldpolicy = -1;
3311 unsigned long flags;
3312 runqueue_t *rq;
3313
3314 recheck:
3315 /* double check policy once rq lock held */
3316 if (policy < 0)
3317 policy = oldpolicy = p->policy;
3318 else if (!SCHED_RANGE(policy))
3319 return -EINVAL;
3320 /*
3321 * Valid priorities for SCHED_FIFO and SCHED_RR are
3322 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3323 */
3324 if (param->sched_priority < 0 ||
3325 param->sched_priority > MAX_USER_RT_PRIO-1)
3326 return -EINVAL;
3327 if ((!SCHED_RT(policy)) != (param->sched_priority == 0))
3328 return -EINVAL;
3329
3330 if (SCHED_RT(policy) &&
3331 param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
3332 !capable(CAP_SYS_NICE))
3333 return -EPERM;
3334 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3335 !capable(CAP_SYS_NICE))
3336 return -EPERM;
3337
3338 if (!(p->mm) && policy == SCHED_BATCH)
3339 /*
3340 * Don't allow kernel threads to be SCHED_BATCH.
3341 */
3342 return -EINVAL;
3343
3344 retval = security_task_setscheduler(p, policy, param);
3345 if (retval)
3346 return retval;
3347 /*
3348 * To be able to change p->policy safely, the apropriate
3349 * runqueue lock must be held.
3350 */
3351 rq = task_rq_lock(p, &flags);
3352 /* recheck policy now with rq lock held */
3353 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3354 policy = oldpolicy = -1;
3355 task_rq_unlock(rq, &flags);
3356 goto recheck;
3357 }
3358 if ((queued = task_queued(p)))
3359 deactivate_task(p, rq);
3360 oldprio = p->prio;
3361 __setscheduler(p, policy, param->sched_priority);
3362 if (queued) {
3363 __activate_task(p, rq);
3364 /*
3365 * Reschedule if we are currently running on this runqueue and
3366 * our priority decreased, or if we are not currently running on
3367 * this runqueue and our priority is higher than the current's
3368 */
3369 if (task_running(rq, p)) {
3370 if (p->prio > oldprio)
3371 resched_task(rq->curr);
3372 } else
3373 preempt(p, rq);
3374 }
3375 task_rq_unlock(rq, &flags);
3376 return 0;
3377 }
3378 EXPORT_SYMBOL_GPL(sched_setscheduler);
3379
3380 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3381 {
3382 int retval;
3383 struct sched_param lparam;
3384 struct task_struct *p;
3385
3386 if (!param || pid < 0)
3387 return -EINVAL;
3388 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3389 return -EFAULT;
3390 read_lock_irq(&tasklist_lock);
3391 p = find_process_by_pid(pid);
3392 if (!p) {
3393 read_unlock_irq(&tasklist_lock);
3394 return -ESRCH;
3395 }
3396 retval = sched_setscheduler(p, policy, &lparam);
3397 read_unlock_irq(&tasklist_lock);
3398 return retval;
3399 }
3400
3401 /**
3402 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3403 * @pid: the pid in question.
3404 * @policy: new policy.
3405 * @param: structure containing the new RT priority.
3406 */
3407 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3408 struct sched_param __user *param)
3409 {
3410 return do_sched_setscheduler(pid, policy, param);
3411 }
3412
3413 /**
3414 * sys_sched_setparam - set/change the RT priority of a thread
3415 * @pid: the pid in question.
3416 * @param: structure containing the new RT priority.
3417 */
3418 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3419 {
3420 return do_sched_setscheduler(pid, -1, param);
3421 }
3422
3423 /**
3424 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3425 * @pid: the pid in question.
3426 */
3427 asmlinkage long sys_sched_getscheduler(pid_t pid)
3428 {
3429 int retval = -EINVAL;
3430 task_t *p;
3431
3432 if (pid < 0)
3433 goto out_nounlock;
3434
3435 retval = -ESRCH;
3436 read_lock(&tasklist_lock);
3437 p = find_process_by_pid(pid);
3438 if (p) {
3439 retval = security_task_getscheduler(p);
3440 if (!retval)
3441 retval = p->policy;
3442 }
3443 read_unlock(&tasklist_lock);
3444
3445 out_nounlock:
3446 return retval;
3447 }
3448
3449 /**
3450 * sys_sched_getscheduler - get the RT priority of a thread
3451 * @pid: the pid in question.
3452 * @param: structure containing the RT priority.
3453 */
3454 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3455 {
3456 struct sched_param lp;
3457 int retval = -EINVAL;
3458 task_t *p;
3459
3460 if (!param || pid < 0)
3461 goto out_nounlock;
3462
3463 read_lock(&tasklist_lock);
3464 p = find_process_by_pid(pid);
3465 retval = -ESRCH;
3466 if (!p)
3467 goto out_unlock;
3468
3469 retval = security_task_getscheduler(p);
3470 if (retval)
3471 goto out_unlock;
3472
3473 lp.sched_priority = p->rt_priority;
3474 read_unlock(&tasklist_lock);
3475
3476 /*
3477 * This one might sleep, we cannot do it with a spinlock held ...
3478 */
3479 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3480
3481 out_nounlock:
3482 return retval;
3483
3484 out_unlock:
3485 read_unlock(&tasklist_lock);
3486 return retval;
3487 }
3488
3489 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3490 {
3491 task_t *p;
3492 int retval;
3493 cpumask_t cpus_allowed;
3494
3495 lock_cpu_hotplug();
3496 read_lock(&tasklist_lock);
3497
3498 p = find_process_by_pid(pid);
3499 if (!p) {
3500 read_unlock(&tasklist_lock);
3501 unlock_cpu_hotplug();
3502 return -ESRCH;
3503 }
3504
3505 /*
3506 * It is not safe to call set_cpus_allowed with the
3507 * tasklist_lock held. We will bump the task_struct's
3508 * usage count and then drop tasklist_lock.
3509 */
3510 get_task_struct(p);
3511 read_unlock(&tasklist_lock);
3512
3513 retval = -EPERM;
3514 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3515 !capable(CAP_SYS_NICE))
3516 goto out_unlock;
3517
3518 cpus_allowed = cpuset_cpus_allowed(p);
3519 cpus_and(new_mask, new_mask, cpus_allowed);
3520 retval = set_cpus_allowed(p, new_mask);
3521
3522 out_unlock:
3523 put_task_struct(p);
3524 unlock_cpu_hotplug();
3525 return retval;
3526 }
3527
3528 static inline int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3529 cpumask_t *new_mask)
3530 {
3531 if (len < sizeof(cpumask_t)) {
3532 memset(new_mask, 0, sizeof(cpumask_t));
3533 } else if (len > sizeof(cpumask_t)) {
3534 len = sizeof(cpumask_t);
3535 }
3536 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3537 }
3538
3539 /**
3540 * sys_sched_setaffinity - set the cpu affinity of a process
3541 * @pid: pid of the process
3542 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3543 * @user_mask_ptr: user-space pointer to the new cpu mask
3544 */
3545 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3546 unsigned long __user *user_mask_ptr)
3547 {
3548 cpumask_t new_mask;
3549 int retval;
3550
3551 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3552 if (retval)
3553 return retval;
3554
3555 return sched_setaffinity(pid, new_mask);
3556 }
3557
3558 /*
3559 * Represents all cpu's present in the system
3560 * In systems capable of hotplug, this map could dynamically grow
3561 * as new cpu's are detected in the system via any platform specific
3562 * method, such as ACPI for e.g.
3563 */
3564
3565 cpumask_t cpu_present_map;
3566 EXPORT_SYMBOL(cpu_present_map);
3567
3568 #ifndef CONFIG_SMP
3569 cpumask_t cpu_online_map = CPU_MASK_ALL;
3570 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3571 #endif
3572
3573 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3574 {
3575 int retval;
3576 task_t *p;
3577
3578 lock_cpu_hotplug();
3579 read_lock(&tasklist_lock);
3580
3581 retval = -ESRCH;
3582 p = find_process_by_pid(pid);
3583 if (!p)
3584 goto out_unlock;
3585
3586 retval = 0;
3587 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3588
3589 out_unlock:
3590 read_unlock(&tasklist_lock);
3591 unlock_cpu_hotplug();
3592 if (retval)
3593 return retval;
3594
3595 return 0;
3596 }
3597
3598 /**
3599 * sys_sched_getaffinity - get the cpu affinity of a process
3600 * @pid: pid of the process
3601 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3602 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3603 */
3604 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3605 unsigned long __user *user_mask_ptr)
3606 {
3607 int ret;
3608 cpumask_t mask;
3609
3610 if (len < sizeof(cpumask_t))
3611 return -EINVAL;
3612
3613 ret = sched_getaffinity(pid, &mask);
3614 if (ret < 0)
3615 return ret;
3616
3617 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3618 return -EFAULT;
3619
3620 return sizeof(cpumask_t);
3621 }
3622
3623 /**
3624 * sys_sched_yield - yield the current processor to other threads.
3625 * This function yields the current CPU by dropping the priority of current
3626 * to the lowest priority and setting the PF_YIELDED flag.
3627 */
3628 asmlinkage long sys_sched_yield(void)
3629 {
3630 int newprio;
3631 runqueue_t *rq = this_rq_lock();
3632
3633 newprio = current->prio;
3634 schedstat_inc(rq, yld_cnt);
3635 current->slice = slice(current);
3636 current->time_slice = rr_interval(current);
3637 if (likely(!rt_task(current) && !batch_task(current))) {
3638 current->flags |= PF_YIELDED;
3639 newprio = MAX_PRIO - 2;
3640 }
3641
3642 if (newprio != current->prio) {
3643 dequeue_task(current, rq);
3644 current->prio = newprio;
3645 enqueue_task(current, rq);
3646 } else
3647 requeue_task(current, rq);
3648
3649 /*
3650 * Since we are going to call schedule() anyway, there's
3651 * no need to preempt or enable interrupts:
3652 */
3653 __release(rq->lock);
3654 _raw_spin_unlock(&rq->lock);
3655 preempt_enable_no_resched();
3656
3657 schedule();
3658
3659 return 0;
3660 }
3661
3662 static inline void __cond_resched(void)
3663 {
3664 do {
3665 add_preempt_count(PREEMPT_ACTIVE);
3666 schedule();
3667 sub_preempt_count(PREEMPT_ACTIVE);
3668 } while (need_resched());
3669 }
3670
3671 int __sched cond_resched(void)
3672 {
3673 if (need_resched()) {
3674 __cond_resched();
3675 return 1;
3676 }
3677 return 0;
3678 }
3679
3680 EXPORT_SYMBOL(cond_resched);
3681
3682 /*
3683 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3684 * call schedule, and on return reacquire the lock.
3685 *
3686 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3687 * operations here to prevent schedule() from being called twice (once via
3688 * spin_unlock(), once by hand).
3689 */
3690 int cond_resched_lock(spinlock_t * lock)
3691 {
3692 int ret = 0;
3693
3694 if (need_lockbreak(lock)) {
3695 spin_unlock(lock);
3696 cpu_relax();
3697 ret = 1;
3698 spin_lock(lock);
3699 }
3700 if (need_resched()) {
3701 _raw_spin_unlock(lock);
3702 preempt_enable_no_resched();
3703 __cond_resched();
3704 ret = 1;
3705 spin_lock(lock);
3706 }
3707 return ret;
3708 }
3709
3710 EXPORT_SYMBOL(cond_resched_lock);
3711
3712 int __sched cond_resched_softirq(void)
3713 {
3714 BUG_ON(!in_softirq());
3715
3716 if (need_resched()) {
3717 __local_bh_enable();
3718 __cond_resched();
3719 local_bh_disable();
3720 return 1;
3721 }
3722 return 0;
3723 }
3724
3725 EXPORT_SYMBOL(cond_resched_softirq);
3726
3727
3728 /**
3729 * yield - yield the current processor to other threads.
3730 *
3731 * this is a shortcut for kernel-space yielding - it marks the
3732 * thread runnable and calls sys_sched_yield().
3733 */
3734 void __sched yield(void)
3735 {
3736 set_current_state(TASK_RUNNING);
3737 sys_sched_yield();
3738 }
3739
3740 EXPORT_SYMBOL(yield);
3741
3742 /*
3743 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3744 * that process accounting knows that this is a task in IO wait state.
3745 *
3746 * But don't do that if it is a deliberate, throttling IO wait (this task
3747 * has set its backing_dev_info: the queue against which it should throttle)
3748 */
3749 void __sched io_schedule(void)
3750 {
3751 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3752
3753 atomic_inc(&rq->nr_iowait);
3754 schedule();
3755 atomic_dec(&rq->nr_iowait);
3756 }
3757
3758 EXPORT_SYMBOL(io_schedule);
3759
3760 long __sched io_schedule_timeout(long timeout)
3761 {
3762 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3763 long ret;
3764
3765 atomic_inc(&rq->nr_iowait);
3766 ret = schedule_timeout(timeout);
3767 atomic_dec(&rq->nr_iowait);
3768 return ret;
3769 }
3770
3771 /**
3772 * sys_sched_get_priority_max - return maximum RT priority.
3773 * @policy: scheduling class.
3774 *
3775 * this syscall returns the maximum rt_priority that can be used
3776 * by a given scheduling class.
3777 */
3778 asmlinkage long sys_sched_get_priority_max(int policy)
3779 {
3780 int ret = -EINVAL;
3781
3782 switch (policy) {
3783 case SCHED_FIFO:
3784 case SCHED_RR:
3785 ret = MAX_USER_RT_PRIO-1;
3786 break;
3787 case SCHED_NORMAL:
3788 case SCHED_BATCH:
3789 ret = 0;
3790 break;
3791 }
3792 return ret;
3793 }
3794
3795 /**
3796 * sys_sched_get_priority_min - return minimum RT priority.
3797 * @policy: scheduling class.
3798 *
3799 * this syscall returns the minimum rt_priority that can be used
3800 * by a given scheduling class.
3801 */
3802 asmlinkage long sys_sched_get_priority_min(int policy)
3803 {
3804 int ret = -EINVAL;
3805
3806 switch (policy) {
3807 case SCHED_FIFO:
3808 case SCHED_RR:
3809 ret = 1;
3810 break;
3811 case SCHED_NORMAL:
3812 case SCHED_BATCH:
3813 ret = 0;
3814 }
3815 return ret;
3816 }
3817
3818 /**
3819 * sys_sched_rr_get_interval - return the default timeslice of a process.
3820 * @pid: pid of the process.
3821 * @interval: userspace pointer to the timeslice value.
3822 *
3823 * this syscall writes the default timeslice value of a given process
3824 * into the user-space timespec buffer. A value of '0' means infinity.
3825 */
3826 asmlinkage
3827 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3828 {
3829 int retval = -EINVAL;
3830 struct timespec t;
3831 task_t *p;
3832
3833 if (pid < 0)
3834 goto out_nounlock;
3835
3836 retval = -ESRCH;
3837 read_lock(&tasklist_lock);
3838 p = find_process_by_pid(pid);
3839 if (!p)
3840 goto out_unlock;
3841
3842 retval = security_task_getscheduler(p);
3843 if (retval)
3844 goto out_unlock;
3845
3846 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3847 0 : slice(p), &t);
3848 read_unlock(&tasklist_lock);
3849 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3850 out_nounlock:
3851 return retval;
3852 out_unlock:
3853 read_unlock(&tasklist_lock);
3854 return retval;
3855 }
3856
3857 static inline struct task_struct *eldest_child(struct task_struct *p)
3858 {
3859 if (list_empty(&p->children)) return NULL;
3860 return list_entry(p->children.next,struct task_struct,sibling);
3861 }
3862
3863 static inline struct task_struct *older_sibling(struct task_struct *p)
3864 {
3865 if (p->sibling.prev==&p->parent->children) return NULL;
3866 return list_entry(p->sibling.prev,struct task_struct,sibling);
3867 }
3868
3869 static inline struct task_struct *younger_sibling(struct task_struct *p)
3870 {
3871 if (p->sibling.next==&p->parent->children) return NULL;
3872 return list_entry(p->sibling.next,struct task_struct,sibling);
3873 }
3874
3875 static inline void show_task(task_t * p)
3876 {
3877 task_t *relative;
3878 unsigned state;
3879 unsigned long free = 0;
3880 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3881
3882 printk("%-13.13s ", p->comm);
3883 state = p->state ? __ffs(p->state) + 1 : 0;
3884 if (state < ARRAY_SIZE(stat_nam))
3885 printk(stat_nam[state]);
3886 else
3887 printk("?");
3888 #if (BITS_PER_LONG == 32)
3889 if (state == TASK_RUNNING)
3890 printk(" running ");
3891 else
3892 printk(" %08lX ", thread_saved_pc(p));
3893 #else
3894 if (state == TASK_RUNNING)
3895 printk(" running task ");
3896 else
3897 printk(" %016lx ", thread_saved_pc(p));
3898 #endif
3899 #ifdef CONFIG_DEBUG_STACK_USAGE
3900 {
3901 unsigned long * n = (unsigned long *) (p->thread_info+1);
3902 while (!*n)
3903 n++;
3904 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3905 }
3906 #endif
3907 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3908 if ((relative = eldest_child(p)))
3909 printk("%5d ", relative->pid);
3910 else
3911 printk(" ");
3912 if ((relative = younger_sibling(p)))
3913 printk("%7d", relative->pid);
3914 else
3915 printk(" ");
3916 if ((relative = older_sibling(p)))
3917 printk(" %5d", relative->pid);
3918 else
3919 printk(" ");
3920 if (!p->mm)
3921 printk(" (L-TLB)\n");
3922 else
3923 printk(" (NOTLB)\n");
3924
3925 if (state != TASK_RUNNING)
3926 show_stack(p, NULL);
3927 }
3928
3929 void show_state(void)
3930 {
3931 task_t *g, *p;
3932
3933 #if (BITS_PER_LONG == 32)
3934 printk("\n"
3935 " sibling\n");
3936 printk(" task PC pid father child younger older\n");
3937 #else
3938 printk("\n"
3939 " sibling\n");
3940 printk(" task PC pid father child younger older\n");
3941 #endif
3942 read_lock(&tasklist_lock);
3943 do_each_thread(g, p) {
3944 /*
3945 * reset the NMI-timeout, listing all files on a slow
3946 * console might take alot of time:
3947 */
3948 touch_nmi_watchdog();
3949 show_task(p);
3950 } while_each_thread(g, p);
3951
3952 read_unlock(&tasklist_lock);
3953 }
3954
3955 void __devinit init_idle(task_t *idle, int cpu)
3956 {
3957 runqueue_t *rq = cpu_rq(cpu);
3958 unsigned long flags;
3959
3960 idle->prio = MAX_PRIO;
3961 idle->state = TASK_RUNNING;
3962 idle->cpus_allowed = cpumask_of_cpu(cpu);
3963 set_task_cpu(idle, cpu);
3964
3965 spin_lock_irqsave(&rq->lock, flags);
3966 rq->curr = rq->idle = idle;
3967 set_tsk_need_resched(idle);
3968 spin_unlock_irqrestore(&rq->lock, flags);
3969
3970 /* Set the preempt count _outside_ the spinlocks! */
3971 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
3972 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3973 #else
3974 idle->thread_info->preempt_count = 0;
3975 #endif
3976 }
3977
3978 /*
3979 * In a system that switches off the HZ timer nohz_cpu_mask
3980 * indicates which cpus entered this state. This is used
3981 * in the rcu update to wait only for active cpus. For system
3982 * which do not switch off the HZ timer nohz_cpu_mask should
3983 * always be CPU_MASK_NONE.
3984 */
3985 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3986
3987 #ifdef CONFIG_SMP
3988 /*
3989 * This is how migration works:
3990 *
3991 * 1) we queue a migration_req_t structure in the source CPU's
3992 * runqueue and wake up that CPU's migration thread.
3993 * 2) we down() the locked semaphore => thread blocks.
3994 * 3) migration thread wakes up (implicitly it forces the migrated
3995 * thread off the CPU)
3996 * 4) it gets the migration request and checks whether the migrated
3997 * task is still in the wrong runqueue.
3998 * 5) if it's in the wrong runqueue then the migration thread removes
3999 * it and puts it into the right queue.
4000 * 6) migration thread up()s the semaphore.
4001 * 7) we wake up and the migration is done.
4002 */
4003
4004 /*
4005 * Change a given task's CPU affinity. Migrate the thread to a
4006 * proper CPU and schedule it away if the CPU it's executing on
4007 * is removed from the allowed bitmask.
4008 *
4009 * NOTE: the caller must have a valid reference to the task, the
4010 * task must not exit() & deallocate itself prematurely. The
4011 * call is not atomic; no spinlocks may be held.
4012 */
4013 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4014 {
4015 unsigned long flags;
4016 int ret = 0;
4017 migration_req_t req;
4018 runqueue_t *rq;
4019
4020 rq = task_rq_lock(p, &flags);
4021 if (!cpus_intersects(new_mask, cpu_online_map)) {
4022 ret = -EINVAL;
4023 goto out;
4024 }
4025
4026 p->cpus_allowed = new_mask;
4027 /* Can the task run on the task's current CPU? If so, we're done */
4028 if (cpu_isset(task_cpu(p), new_mask))
4029 goto out;
4030
4031 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4032 /* Need help from migration thread: drop lock and wait. */
4033 task_rq_unlock(rq, &flags);
4034 wake_up_process(rq->migration_thread);
4035 wait_for_completion(&req.done);
4036 tlb_migrate_finish(p->mm);
4037 return 0;
4038 }
4039 out:
4040 task_rq_unlock(rq, &flags);
4041 return ret;
4042 }
4043
4044 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4045
4046 /*
4047 * Move (not current) task off this cpu, onto dest cpu. We're doing
4048 * this because either it can't run here any more (set_cpus_allowed()
4049 * away from this CPU, or CPU going down), or because we're
4050 * attempting to rebalance this task on exec (sched_exec).
4051 *
4052 * So we race with normal scheduler movements, but that's OK, as long
4053 * as the task is no longer on this CPU.
4054 */
4055 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4056 {
4057 runqueue_t *rq_dest, *rq_src;
4058
4059 if (unlikely(cpu_is_offline(dest_cpu)))
4060 return;
4061
4062 rq_src = cpu_rq(src_cpu);
4063 rq_dest = cpu_rq(dest_cpu);
4064
4065 double_rq_lock(rq_src, rq_dest);
4066 /* Already moved. */
4067 if (task_cpu(p) != src_cpu)
4068 goto out;
4069 /* Affinity changed (again). */
4070 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4071 goto out;
4072
4073 set_task_cpu(p, dest_cpu);
4074 if (task_queued(p)) {
4075 /*
4076 * Sync timestamp with rq_dest's before activating.
4077 * The same thing could be achieved by doing this step
4078 * afterwards, and pretending it was a local activate.
4079 * This way is cleaner and logically correct.
4080 */
4081 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4082 + rq_dest->timestamp_last_tick;
4083 deactivate_task(p, rq_src);
4084 activate_task(p, rq_dest, 0);
4085 preempt(p, rq_dest);
4086 }
4087
4088 out:
4089 double_rq_unlock(rq_src, rq_dest);
4090 }
4091
4092 /*
4093 * migration_thread - this is a highprio system thread that performs
4094 * thread migration by bumping thread off CPU then 'pushing' onto
4095 * another runqueue.
4096 */
4097 static int migration_thread(void * data)
4098 {
4099 runqueue_t *rq;
4100 int cpu = (long)data;
4101
4102 rq = cpu_rq(cpu);
4103 BUG_ON(rq->migration_thread != current);
4104
4105 set_current_state(TASK_INTERRUPTIBLE);
4106 while (!kthread_should_stop()) {
4107 struct list_head *head;
4108 migration_req_t *req;
4109
4110 if (current->flags & PF_FREEZE)
4111 refrigerator(PF_FREEZE);
4112
4113 spin_lock_irq(&rq->lock);
4114
4115 if (cpu_is_offline(cpu)) {
4116 spin_unlock_irq(&rq->lock);
4117 goto wait_to_die;
4118 }
4119
4120 if (rq->active_balance) {
4121 active_load_balance(rq, cpu);
4122 rq->active_balance = 0;
4123 }
4124
4125 head = &rq->migration_queue;
4126
4127 if (list_empty(head)) {
4128 spin_unlock_irq(&rq->lock);
4129 schedule();
4130 set_current_state(TASK_INTERRUPTIBLE);
4131 continue;
4132 }
4133 req = list_entry(head->next, migration_req_t, list);
4134 list_del_init(head->next);
4135
4136 if (req->type == REQ_MOVE_TASK) {
4137 spin_unlock(&rq->lock);
4138 __migrate_task(req->task, cpu, req->dest_cpu);
4139 local_irq_enable();
4140 } else if (req->type == REQ_SET_DOMAIN) {
4141 rq->sd = req->sd;
4142 spin_unlock_irq(&rq->lock);
4143 } else {
4144 spin_unlock_irq(&rq->lock);
4145 WARN_ON(1);
4146 }
4147
4148 complete(&req->done);
4149 }
4150 __set_current_state(TASK_RUNNING);
4151 return 0;
4152
4153 wait_to_die:
4154 /* Wait for kthread_stop */
4155 set_current_state(TASK_INTERRUPTIBLE);
4156 while (!kthread_should_stop()) {
4157 schedule();
4158 set_current_state(TASK_INTERRUPTIBLE);
4159 }
4160 __set_current_state(TASK_RUNNING);
4161 return 0;
4162 }
4163
4164 #ifdef CONFIG_HOTPLUG_CPU
4165 /* Figure out where task on dead CPU should go, use force if neccessary. */
4166 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4167 {
4168 int dest_cpu;
4169 cpumask_t mask;
4170
4171 /* On same node? */
4172 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4173 cpus_and(mask, mask, tsk->cpus_allowed);
4174 dest_cpu = any_online_cpu(mask);
4175
4176 /* On any allowed CPU? */
4177 if (dest_cpu == NR_CPUS)
4178 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4179
4180 /* No more Mr. Nice Guy. */
4181 if (dest_cpu == NR_CPUS) {
4182 cpus_setall(tsk->cpus_allowed);
4183 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4184
4185 /*
4186 * Don't tell them about moving exiting tasks or
4187 * kernel threads (both mm NULL), since they never
4188 * leave kernel.
4189 */
4190 if (tsk->mm && printk_ratelimit())
4191 printk(KERN_INFO "process %d (%s) no "
4192 "longer affine to cpu%d\n",
4193 tsk->pid, tsk->comm, dead_cpu);
4194 }
4195 __migrate_task(tsk, dead_cpu, dest_cpu);
4196 }
4197
4198 /*
4199 * While a dead CPU has no uninterruptible tasks queued at this point,
4200 * it might still have a nonzero ->nr_uninterruptible counter, because
4201 * for performance reasons the counter is not stricly tracking tasks to
4202 * their home CPUs. So we just add the counter to another CPU's counter,
4203 * to keep the global sum constant after CPU-down:
4204 */
4205 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4206 {
4207 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4208 unsigned long flags;
4209
4210 local_irq_save(flags);
4211 double_rq_lock(rq_src, rq_dest);
4212 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4213 rq_src->nr_uninterruptible = 0;
4214 double_rq_unlock(rq_src, rq_dest);
4215 local_irq_restore(flags);
4216 }
4217
4218 /* Run through task list and migrate tasks from the dead cpu. */
4219 static void migrate_live_tasks(int src_cpu)
4220 {
4221 struct task_struct *tsk, *t;
4222
4223 write_lock_irq(&tasklist_lock);
4224
4225 do_each_thread(t, tsk) {
4226 if (tsk == current)
4227 continue;
4228
4229 if (task_cpu(tsk) == src_cpu)
4230 move_task_off_dead_cpu(src_cpu, tsk);
4231 } while_each_thread(t, tsk);
4232
4233 write_unlock_irq(&tasklist_lock);
4234 }
4235
4236 /* Schedules idle task to be the next runnable task on current CPU.
4237 * It does so by boosting its priority to highest possible and adding it to
4238 * the _front_ of runqueue. Used by CPU offline code.
4239 */
4240 void sched_idle_next(void)
4241 {
4242 int cpu = smp_processor_id();
4243 runqueue_t *rq = this_rq();
4244 struct task_struct *p = rq->idle;
4245 unsigned long flags;
4246
4247 /* cpu has to be offline */
4248 BUG_ON(cpu_online(cpu));
4249
4250 /* Strictly not necessary since rest of the CPUs are stopped by now
4251 * and interrupts disabled on current cpu.
4252 */
4253 spin_lock_irqsave(&rq->lock, flags);
4254
4255 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4256 /* Add idle task to _front_ of it's priority queue */
4257 __activate_idle_task(p, rq);
4258
4259 spin_unlock_irqrestore(&rq->lock, flags);
4260 }
4261
4262 /* Ensures that the idle task is using init_mm right before its cpu goes
4263 * offline.
4264 */
4265 void idle_task_exit(void)
4266 {
4267 struct mm_struct *mm = current->active_mm;
4268
4269 BUG_ON(cpu_online(smp_processor_id()));
4270
4271 if (mm != &init_mm)
4272 switch_mm(mm, &init_mm, current);
4273 mmdrop(mm);
4274 }
4275
4276 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4277 {
4278 struct runqueue *rq = cpu_rq(dead_cpu);
4279
4280 /* Must be exiting, otherwise would be on tasklist. */
4281 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4282
4283 /* Cannot have done final schedule yet: would have vanished. */
4284 BUG_ON(tsk->flags & PF_DEAD);
4285
4286 get_task_struct(tsk);
4287
4288 /*
4289 * Drop lock around migration; if someone else moves it,
4290 * that's OK. No task can be added to this CPU, so iteration is
4291 * fine.
4292 */
4293 spin_unlock_irq(&rq->lock);
4294 move_task_off_dead_cpu(dead_cpu, tsk);
4295 spin_lock_irq(&rq->lock);
4296
4297 put_task_struct(tsk);
4298 }
4299
4300 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4301 static void migrate_dead_tasks(unsigned int dead_cpu)
4302 {
4303 unsigned arr, i;
4304 struct runqueue *rq = cpu_rq(dead_cpu);
4305
4306 for (arr = 0; arr < 2; arr++) {
4307 for (i = 0; i < MAX_PRIO; i++) {
4308 struct list_head *list = &rq->queue[i];
4309 while (!list_empty(list))
4310 migrate_dead(dead_cpu,
4311 list_entry(list->next, task_t,
4312 run_list));
4313 }
4314 }
4315 }
4316 #endif /* CONFIG_HOTPLUG_CPU */
4317
4318 /*
4319 * migration_call - callback that gets triggered when a CPU is added.
4320 * Here we can start up the necessary migration thread for the new CPU.
4321 */
4322 static int migration_call(struct notifier_block *nfb, unsigned long action,
4323 void *hcpu)
4324 {
4325 int cpu = (long)hcpu;
4326 struct task_struct *p;
4327 struct runqueue *rq;
4328 unsigned long flags;
4329
4330 switch (action) {
4331 case CPU_UP_PREPARE:
4332 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4333 if (IS_ERR(p))
4334 return NOTIFY_BAD;
4335 p->flags |= PF_NOFREEZE;
4336 kthread_bind(p, cpu);
4337 /* Must be high prio: stop_machine expects to yield to it. */
4338 rq = task_rq_lock(p, &flags);
4339 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4340 task_rq_unlock(rq, &flags);
4341 cpu_rq(cpu)->migration_thread = p;
4342 break;
4343 case CPU_ONLINE:
4344 /* Strictly unneccessary, as first user will wake it. */
4345 wake_up_process(cpu_rq(cpu)->migration_thread);
4346 break;
4347 #ifdef CONFIG_HOTPLUG_CPU
4348 case CPU_UP_CANCELED:
4349 /* Unbind it from offline cpu so it can run. Fall thru. */
4350 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4351 kthread_stop(cpu_rq(cpu)->migration_thread);
4352 cpu_rq(cpu)->migration_thread = NULL;
4353 break;
4354 case CPU_DEAD:
4355 migrate_live_tasks(cpu);
4356 rq = cpu_rq(cpu);
4357 kthread_stop(rq->migration_thread);
4358 rq->migration_thread = NULL;
4359 /* Idle task back to normal (off runqueue, low prio) */
4360 rq = task_rq_lock(rq->idle, &flags);
4361 deactivate_task(rq->idle, rq);
4362 rq->idle->static_prio = MAX_PRIO;
4363 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4364 migrate_dead_tasks(cpu);
4365 task_rq_unlock(rq, &flags);
4366 migrate_nr_uninterruptible(rq);
4367 BUG_ON(rq->nr_running != 0);
4368
4369 /* No need to migrate the tasks: it was best-effort if
4370 * they didn't do lock_cpu_hotplug(). Just wake up
4371 * the requestors. */
4372 spin_lock_irq(&rq->lock);
4373 while (!list_empty(&rq->migration_queue)) {
4374 migration_req_t *req;
4375 req = list_entry(rq->migration_queue.next,
4376 migration_req_t, list);
4377 BUG_ON(req->type != REQ_MOVE_TASK);
4378 list_del_init(&req->list);
4379 complete(&req->done);
4380 }
4381 spin_unlock_irq(&rq->lock);
4382 break;
4383 #endif
4384 }
4385 return NOTIFY_OK;
4386 }
4387
4388 /* Register at highest priority so that task migration (migrate_all_tasks)
4389 * happens before everything else.
4390 */
4391 static struct notifier_block __devinitdata migration_notifier = {
4392 .notifier_call = migration_call,
4393 .priority = 10
4394 };
4395
4396 int __init migration_init(void)
4397 {
4398 void *cpu = (void *)(long)smp_processor_id();
4399 /* Start one for boot CPU. */
4400 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4401 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4402 register_cpu_notifier(&migration_notifier);
4403 return 0;
4404 }
4405 #endif
4406
4407 #ifdef CONFIG_SMP
4408 #define SCHED_DOMAIN_DEBUG
4409 #ifdef SCHED_DOMAIN_DEBUG
4410 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4411 {
4412 int level = 0;
4413
4414 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4415
4416 do {
4417 int i;
4418 char str[NR_CPUS];
4419 struct sched_group *group = sd->groups;
4420 cpumask_t groupmask;
4421
4422 cpumask_scnprintf(str, NR_CPUS, sd->span);
4423 cpus_clear(groupmask);
4424
4425 printk(KERN_DEBUG);
4426 for (i = 0; i < level + 1; i++)
4427 printk(" ");
4428 printk("domain %d: ", level);
4429
4430 if (!(sd->flags & SD_LOAD_BALANCE)) {
4431 printk("does not load-balance\n");
4432 if (sd->parent)
4433 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4434 break;
4435 }
4436
4437 printk("span %s\n", str);
4438
4439 if (!cpu_isset(cpu, sd->span))
4440 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4441 if (!cpu_isset(cpu, group->cpumask))
4442 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4443
4444 printk(KERN_DEBUG);
4445 for (i = 0; i < level + 2; i++)
4446 printk(" ");
4447 printk("groups:");
4448 do {
4449 if (!group) {
4450 printk("\n");
4451 printk(KERN_ERR "ERROR: group is NULL\n");
4452 break;
4453 }
4454
4455 if (!group->cpu_power) {
4456 printk("\n");
4457 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4458 }
4459
4460 if (!cpus_weight(group->cpumask)) {
4461 printk("\n");
4462 printk(KERN_ERR "ERROR: empty group\n");
4463 }
4464
4465 if (cpus_intersects(groupmask, group->cpumask)) {
4466 printk("\n");
4467 printk(KERN_ERR "ERROR: repeated CPUs\n");
4468 }
4469
4470 cpus_or(groupmask, groupmask, group->cpumask);
4471
4472 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4473 printk(" %s", str);
4474
4475 group = group->next;
4476 } while (group != sd->groups);
4477 printk("\n");
4478
4479 if (!cpus_equal(sd->span, groupmask))
4480 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4481
4482 level++;
4483 sd = sd->parent;
4484
4485 if (sd) {
4486 if (!cpus_subset(groupmask, sd->span))
4487 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4488 }
4489
4490 } while (sd);
4491 }
4492 #else
4493 #define sched_domain_debug(sd, cpu) {}
4494 #endif
4495
4496 /*
4497 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4498 * hold the hotplug lock.
4499 */
4500 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4501 {
4502 migration_req_t req;
4503 unsigned long flags;
4504 runqueue_t *rq = cpu_rq(cpu);
4505 int local = 1;
4506
4507 sched_domain_debug(sd, cpu);
4508
4509 spin_lock_irqsave(&rq->lock, flags);
4510
4511 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4512 rq->sd = sd;
4513 } else {
4514 init_completion(&req.done);
4515 req.type = REQ_SET_DOMAIN;
4516 req.sd = sd;
4517 list_add(&req.list, &rq->migration_queue);
4518 local = 0;
4519 }
4520
4521 spin_unlock_irqrestore(&rq->lock, flags);
4522
4523 if (!local) {
4524 wake_up_process(rq->migration_thread);
4525 wait_for_completion(&req.done);
4526 }
4527 }
4528
4529 /* cpus with isolated domains */
4530 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4531
4532 /* Setup the mask of cpus configured for isolated domains */
4533 static int __init isolated_cpu_setup(char *str)
4534 {
4535 int ints[NR_CPUS], i;
4536
4537 str = get_options(str, ARRAY_SIZE(ints), ints);
4538 cpus_clear(cpu_isolated_map);
4539 for (i = 1; i <= ints[0]; i++)
4540 if (ints[i] < NR_CPUS)
4541 cpu_set(ints[i], cpu_isolated_map);
4542 return 1;
4543 }
4544
4545 __setup ("isolcpus=", isolated_cpu_setup);
4546
4547 /*
4548 * init_sched_build_groups takes an array of groups, the cpumask we wish
4549 * to span, and a pointer to a function which identifies what group a CPU
4550 * belongs to. The return value of group_fn must be a valid index into the
4551 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4552 * keep track of groups covered with a cpumask_t).
4553 *
4554 * init_sched_build_groups will build a circular linked list of the groups
4555 * covered by the given span, and will set each group's ->cpumask correctly,
4556 * and ->cpu_power to 0.
4557 */
4558 void __devinit init_sched_build_groups(struct sched_group groups[],
4559 cpumask_t span, int (*group_fn)(int cpu))
4560 {
4561 struct sched_group *first = NULL, *last = NULL;
4562 cpumask_t covered = CPU_MASK_NONE;
4563 int i;
4564
4565 for_each_cpu_mask(i, span) {
4566 int group = group_fn(i);
4567 struct sched_group *sg = &groups[group];
4568 int j;
4569
4570 if (cpu_isset(i, covered))
4571 continue;
4572
4573 sg->cpumask = CPU_MASK_NONE;
4574 sg->cpu_power = 0;
4575
4576 for_each_cpu_mask(j, span) {
4577 if (group_fn(j) != group)
4578 continue;
4579
4580 cpu_set(j, covered);
4581 cpu_set(j, sg->cpumask);
4582 }
4583 if (!first)
4584 first = sg;
4585 if (last)
4586 last->next = sg;
4587 last = sg;
4588 }
4589 last->next = first;
4590 }
4591
4592
4593 #ifdef ARCH_HAS_SCHED_DOMAIN
4594 extern void __devinit arch_init_sched_domains(void);
4595 extern void __devinit arch_destroy_sched_domains(void);
4596 #else
4597 #ifdef CONFIG_SCHED_SMT
4598 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4599 static struct sched_group sched_group_cpus[NR_CPUS];
4600 static int __devinit cpu_to_cpu_group(int cpu)
4601 {
4602 return cpu;
4603 }
4604 #endif
4605
4606 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4607 static struct sched_group sched_group_phys[NR_CPUS];
4608 static int __devinit cpu_to_phys_group(int cpu)
4609 {
4610 #ifdef CONFIG_SCHED_SMT
4611 return first_cpu(cpu_sibling_map[cpu]);
4612 #else
4613 return cpu;
4614 #endif
4615 }
4616
4617 #ifdef CONFIG_NUMA
4618
4619 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4620 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4621 static int __devinit cpu_to_node_group(int cpu)
4622 {
4623 return cpu_to_node(cpu);
4624 }
4625 #endif
4626
4627 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4628 /*
4629 * The domains setup code relies on siblings not spanning
4630 * multiple nodes. Make sure the architecture has a proper
4631 * siblings map:
4632 */
4633 static void check_sibling_maps(void)
4634 {
4635 int i, j;
4636
4637 for_each_online_cpu(i) {
4638 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4639 if (cpu_to_node(i) != cpu_to_node(j)) {
4640 printk(KERN_INFO "warning: CPU %d siblings map "
4641 "to different node - isolating "
4642 "them.\n", i);
4643 cpu_sibling_map[i] = cpumask_of_cpu(i);
4644 break;
4645 }
4646 }
4647 }
4648 }
4649 #endif
4650
4651 /*
4652 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4653 */
4654 static void __devinit arch_init_sched_domains(void)
4655 {
4656 int i;
4657 cpumask_t cpu_default_map;
4658
4659 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4660 check_sibling_maps();
4661 #endif
4662 /*
4663 * Setup mask for cpus without special case scheduling requirements.
4664 * For now this just excludes isolated cpus, but could be used to
4665 * exclude other special cases in the future.
4666 */
4667 cpus_complement(cpu_default_map, cpu_isolated_map);
4668 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4669
4670 /*
4671 * Set up domains. Isolated domains just stay on the dummy domain.
4672 */
4673 for_each_cpu_mask(i, cpu_default_map) {
4674 int group;
4675 struct sched_domain *sd = NULL, *p;
4676 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4677
4678 cpus_and(nodemask, nodemask, cpu_default_map);
4679
4680 #ifdef CONFIG_NUMA
4681 sd = &per_cpu(node_domains, i);
4682 group = cpu_to_node_group(i);
4683 *sd = SD_NODE_INIT;
4684 sd->span = cpu_default_map;
4685 sd->groups = &sched_group_nodes[group];
4686 #endif
4687
4688 p = sd;
4689 sd = &per_cpu(phys_domains, i);
4690 group = cpu_to_phys_group(i);
4691 *sd = SD_CPU_INIT;
4692 sd->span = nodemask;
4693 sd->parent = p;
4694 sd->groups = &sched_group_phys[group];
4695
4696 #ifdef CONFIG_SCHED_SMT
4697 p = sd;
4698 sd = &per_cpu(cpu_domains, i);
4699 group = cpu_to_cpu_group(i);
4700 *sd = SD_SIBLING_INIT;
4701 sd->span = cpu_sibling_map[i];
4702 cpus_and(sd->span, sd->span, cpu_default_map);
4703 sd->parent = p;
4704 sd->groups = &sched_group_cpus[group];
4705 #endif
4706 }
4707
4708 #ifdef CONFIG_SCHED_SMT
4709 /* Set up CPU (sibling) groups */
4710 for_each_online_cpu(i) {
4711 cpumask_t this_sibling_map = cpu_sibling_map[i];
4712 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4713 if (i != first_cpu(this_sibling_map))
4714 continue;
4715
4716 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4717 &cpu_to_cpu_group);
4718 }
4719 #endif
4720
4721 /* Set up physical groups */
4722 for (i = 0; i < MAX_NUMNODES; i++) {
4723 cpumask_t nodemask = node_to_cpumask(i);
4724
4725 cpus_and(nodemask, nodemask, cpu_default_map);
4726 if (cpus_empty(nodemask))
4727 continue;
4728
4729 init_sched_build_groups(sched_group_phys, nodemask,
4730 &cpu_to_phys_group);
4731 }
4732
4733 #ifdef CONFIG_NUMA
4734 /* Set up node groups */
4735 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4736 &cpu_to_node_group);
4737 #endif
4738
4739 /* Calculate CPU power for physical packages and nodes */
4740 for_each_cpu_mask(i, cpu_default_map) {
4741 int power;
4742 struct sched_domain *sd;
4743 #ifdef CONFIG_SCHED_SMT
4744 sd = &per_cpu(cpu_domains, i);
4745 power = SCHED_LOAD_SCALE;
4746 sd->groups->cpu_power = power;
4747 #endif
4748
4749 sd = &per_cpu(phys_domains, i);
4750 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4751 (cpus_weight(sd->groups->cpumask)-1) / 10;
4752 sd->groups->cpu_power = power;
4753
4754 #ifdef CONFIG_NUMA
4755 if (i == first_cpu(sd->groups->cpumask)) {
4756 /* Only add "power" once for each physical package. */
4757 sd = &per_cpu(node_domains, i);
4758 sd->groups->cpu_power += power;
4759 }
4760 #endif
4761 }
4762
4763 /* Attach the domains */
4764 for_each_online_cpu(i) {
4765 struct sched_domain *sd;
4766 #ifdef CONFIG_SCHED_SMT
4767 sd = &per_cpu(cpu_domains, i);
4768 #else
4769 sd = &per_cpu(phys_domains, i);
4770 #endif
4771 cpu_attach_domain(sd, i);
4772 }
4773 }
4774
4775 #ifdef CONFIG_HOTPLUG_CPU
4776 static void __devinit arch_destroy_sched_domains(void)
4777 {
4778 /* Do nothing: everything is statically allocated. */
4779 }
4780 #endif
4781
4782 #endif /* ARCH_HAS_SCHED_DOMAIN */
4783
4784 /*
4785 * Initial dummy domain for early boot and for hotplug cpu. Being static,
4786 * it is initialized to zero, so all balancing flags are cleared which is
4787 * what we want.
4788 */
4789 static struct sched_domain sched_domain_dummy;
4790
4791 #ifdef CONFIG_HOTPLUG_CPU
4792 /*
4793 * Force a reinitialization of the sched domains hierarchy. The domains
4794 * and groups cannot be updated in place without racing with the balancing
4795 * code, so we temporarily attach all running cpus to a "dummy" domain
4796 * which will prevent rebalancing while the sched domains are recalculated.
4797 */
4798 static int update_sched_domains(struct notifier_block *nfb,
4799 unsigned long action, void *hcpu)
4800 {
4801 int i;
4802
4803 switch (action) {
4804 case CPU_UP_PREPARE:
4805 case CPU_DOWN_PREPARE:
4806 for_each_online_cpu(i)
4807 cpu_attach_domain(&sched_domain_dummy, i);
4808 arch_destroy_sched_domains();
4809 return NOTIFY_OK;
4810
4811 case CPU_UP_CANCELED:
4812 case CPU_DOWN_FAILED:
4813 case CPU_ONLINE:
4814 case CPU_DEAD:
4815 /*
4816 * Fall through and re-initialise the domains.
4817 */
4818 break;
4819 default:
4820 return NOTIFY_DONE;
4821 }
4822
4823 /* The hotplug lock is already held by cpu_up/cpu_down */
4824 arch_init_sched_domains();
4825
4826 return NOTIFY_OK;
4827 }
4828 #endif
4829
4830 void __init sched_init_smp(void)
4831 {
4832 lock_cpu_hotplug();
4833 arch_init_sched_domains();
4834 unlock_cpu_hotplug();
4835 /* XXX: Theoretical race here - CPU may be hotplugged now */
4836 hotcpu_notifier(update_sched_domains, 0);
4837 }
4838 #else
4839 void __init sched_init_smp(void)
4840 {
4841 }
4842 #endif /* CONFIG_SMP */
4843
4844 int in_sched_functions(unsigned long addr)
4845 {
4846 /* Linker adds these: start and end of __sched functions */
4847 extern char __sched_text_start[], __sched_text_end[];
4848 return in_lock_functions(addr) ||
4849 (addr >= (unsigned long)__sched_text_start
4850 && addr < (unsigned long)__sched_text_end);
4851 }
4852
4853 void __init sched_init(void)
4854 {
4855 runqueue_t *rq;
4856 int i, j;
4857
4858 for (i = 0; i < NR_CPUS; i++) {
4859
4860 rq = cpu_rq(i);
4861 spin_lock_init(&rq->lock);
4862 rq->cache_ticks = 0;
4863 rq->preempted = 0;
4864
4865 #ifdef CONFIG_SMP
4866 rq->sd = &sched_domain_dummy;
4867 rq->cpu_load = 0;
4868 rq->active_balance = 0;
4869 rq->push_cpu = 0;
4870 rq->migration_thread = NULL;
4871 INIT_LIST_HEAD(&rq->migration_queue);
4872 #endif
4873 atomic_set(&rq->nr_iowait, 0);
4874 for (j = 0; j < MAX_PRIO; j++)
4875 INIT_LIST_HEAD(&rq->queue[j]);
4876 memset(rq->bitmap, 0, BITS_TO_LONGS(MAX_PRIO)*sizeof(long));
4877 /*
4878 * delimiter for bitsearch
4879 */
4880 __set_bit(MAX_PRIO, rq->bitmap);
4881 }
4882
4883 /*
4884 * The boot idle thread does lazy MMU switching as well:
4885 */
4886 atomic_inc(&init_mm.mm_count);
4887 enter_lazy_tlb(&init_mm, current);
4888
4889 /*
4890 * Make us the idle thread. Technically, schedule() should not be
4891 * called from this thread, however somewhere below it might be,
4892 * but because we are the idle thread, we just pick up running again
4893 * when this runqueue becomes "idle".
4894 */
4895 init_idle(current, smp_processor_id());
4896 }
4897
4898 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4899 void __might_sleep(char *file, int line)
4900 {
4901 #if defined(in_atomic)
4902 static unsigned long prev_jiffy; /* ratelimiting */
4903
4904 if ((in_atomic() || irqs_disabled()) &&
4905 system_state == SYSTEM_RUNNING && !oops_in_progress) {
4906 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4907 return;
4908 prev_jiffy = jiffies;
4909 printk(KERN_ERR "Debug: sleeping function called from invalid"
4910 " context at %s:%d\n", file, line);
4911 printk("in_atomic():%d, irqs_disabled():%d\n",
4912 in_atomic(), irqs_disabled());
4913 dump_stack();
4914 }
4915 #endif
4916 }
4917 EXPORT_SYMBOL(__might_sleep);
4918 #endif
4919
4920 #ifdef CONFIG_MAGIC_SYSRQ
4921 void normalize_rt_tasks(void)
4922 {
4923 struct task_struct *p;
4924 unsigned long flags;
4925 runqueue_t *rq;
4926 int queued;
4927
4928 read_lock_irq(&tasklist_lock);
4929 for_each_process (p) {
4930 if (!rt_task(p))
4931 continue;
4932
4933 rq = task_rq_lock(p, &flags);
4934
4935 if ((queued = task_queued(p)))
4936 deactivate_task(p, task_rq(p));
4937 __setscheduler(p, SCHED_NORMAL, 0);
4938 if (queued) {
4939 __activate_task(p, task_rq(p));
4940 resched_task(rq->curr);
4941 }
4942
4943 task_rq_unlock(rq, &flags);
4944 }
4945 read_unlock_irq(&tasklist_lock);
4946 }
4947
4948 #endif /* CONFIG_MAGIC_SYSRQ */