code style scripts/checkpatch.pl formatting round #4 (2.6.34.14)
[linux-2.6.34.14-moxart.git] / kernel / sched.c
blobe24d139ff6945cf669fdbc3972032e01f8fcb055
1 /*
2 * kernel/sched.c
4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
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 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/kthread.h>
59 #include <linux/proc_fs.h>
60 #include <linux/seq_file.h>
61 #include <linux/sysctl.h>
62 #include <linux/syscalls.h>
63 #include <linux/times.h>
64 #include <linux/tsacct_kern.h>
65 #include <linux/kprobes.h>
66 #include <linux/delayacct.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
73 #include <linux/ftrace.h>
74 #include <linux/slab.h>
76 #include <asm/tlb.h>
77 #include <asm/irq_regs.h>
79 #include "sched_cpupri.h"
81 #define CREATE_TRACE_POINTS
82 #include <trace/events/sched.h>
85 * Convert user-nice values [ -20 ... 0 ... 19 ]
86 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
87 * and back.
89 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
90 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
91 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
94 * 'User priority' is the nice value converted to something we
95 * can work with better when scaling various scheduler parameters,
96 * it's a [ 0 ... 39 ] range.
98 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
99 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
100 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
103 * Helpers for converting nanosecond timing to jiffy resolution
105 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
107 #define NICE_0_LOAD SCHED_LOAD_SCALE
108 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
111 * These are the 'tuning knobs' of the scheduler:
113 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
114 * Timeslices get refilled after they expire.
116 #define DEF_TIMESLICE (100 * HZ / 1000)
119 * single value that denotes runtime == period, ie unlimited time.
121 #define RUNTIME_INF ((u64)~0ULL)
123 static inline int rt_policy(int policy)
125 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
126 return 1;
127 return 0;
130 static inline int task_has_rt_policy(struct task_struct *p)
132 return rt_policy(p->policy);
136 * This is the priority-queue data structure of the RT scheduling class:
138 struct rt_prio_array {
139 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
140 struct list_head queue[MAX_RT_PRIO];
143 struct rt_bandwidth {
144 /* nests inside the rq lock: */
145 raw_spinlock_t rt_runtime_lock;
146 ktime_t rt_period;
147 u64 rt_runtime;
148 struct hrtimer rt_period_timer;
151 static struct rt_bandwidth def_rt_bandwidth;
153 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
155 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
157 struct rt_bandwidth *rt_b =
158 container_of(timer, struct rt_bandwidth, rt_period_timer);
159 ktime_t now;
160 int overrun;
161 int idle = 0;
163 for (;;) {
164 now = hrtimer_cb_get_time(timer);
165 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
167 if (!overrun)
168 break;
170 idle = do_sched_rt_period_timer(rt_b, overrun);
173 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
176 static
177 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
179 rt_b->rt_period = ns_to_ktime(period);
180 rt_b->rt_runtime = runtime;
182 raw_spin_lock_init(&rt_b->rt_runtime_lock);
184 hrtimer_init(&rt_b->rt_period_timer,
185 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
186 rt_b->rt_period_timer.function = sched_rt_period_timer;
189 static inline int rt_bandwidth_enabled(void)
191 return sysctl_sched_rt_runtime >= 0;
194 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
196 ktime_t now;
198 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
199 return;
201 if (hrtimer_active(&rt_b->rt_period_timer))
202 return;
204 raw_spin_lock(&rt_b->rt_runtime_lock);
205 for (;;) {
206 unsigned long delta;
207 ktime_t soft, hard;
209 if (hrtimer_active(&rt_b->rt_period_timer))
210 break;
212 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
213 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
215 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
216 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
217 delta = ktime_to_ns(ktime_sub(hard, soft));
218 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
219 HRTIMER_MODE_ABS_PINNED, 0);
221 raw_spin_unlock(&rt_b->rt_runtime_lock);
224 #ifdef CONFIG_RT_GROUP_SCHED
225 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
227 hrtimer_cancel(&rt_b->rt_period_timer);
229 #endif
232 * sched_domains_mutex serializes calls to arch_init_sched_domains,
233 * detach_destroy_domains and partition_sched_domains.
235 static DEFINE_MUTEX(sched_domains_mutex);
237 #ifdef CONFIG_CGROUP_SCHED
239 #include <linux/cgroup.h>
241 struct cfs_rq;
243 static LIST_HEAD(task_groups);
245 /* task group related information */
246 struct task_group {
247 struct cgroup_subsys_state css;
249 #ifdef CONFIG_FAIR_GROUP_SCHED
250 /* schedulable entities of this group on each cpu */
251 struct sched_entity **se;
252 /* runqueue "owned" by this group on each cpu */
253 struct cfs_rq **cfs_rq;
254 unsigned long shares;
255 #endif
257 #ifdef CONFIG_RT_GROUP_SCHED
258 struct sched_rt_entity **rt_se;
259 struct rt_rq **rt_rq;
261 struct rt_bandwidth rt_bandwidth;
262 #endif
264 struct rcu_head rcu;
265 struct list_head list;
267 struct task_group *parent;
268 struct list_head siblings;
269 struct list_head children;
272 #define root_task_group init_task_group
274 /* task_group_lock serializes add/remove of task groups and also changes to
275 * a task group's cpu shares.
277 static DEFINE_SPINLOCK(task_group_lock);
279 #ifdef CONFIG_FAIR_GROUP_SCHED
281 #ifdef CONFIG_SMP
282 static int root_task_group_empty(void)
284 return list_empty(&root_task_group.children);
286 #endif
288 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
291 * A weight of 0 or 1 can cause arithmetics problems.
292 * A weight of a cfs_rq is the sum of weights of which entities
293 * are queued on this cfs_rq, so a weight of a entity should not be
294 * too large, so as the shares value of a task group.
295 * (The default weight is 1024 - so there's no practical
296 * limitation from this.)
298 #define MIN_SHARES 2
299 #define MAX_SHARES (1UL << 18)
301 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
302 #endif
304 /* Default task group.
305 * Every task in system belong to this group at bootup.
307 struct task_group init_task_group;
309 /* return group to which a task belongs */
310 static inline struct task_group *task_group(struct task_struct *p)
312 struct task_group *tg;
314 #ifdef CONFIG_CGROUP_SCHED
315 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
316 struct task_group, css);
317 #else
318 tg = &init_task_group;
319 #endif
320 return tg;
323 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
324 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
327 * Strictly speaking this rcu_read_lock() is not needed since the
328 * task_group is tied to the cgroup, which in turn can never go away
329 * as long as there are tasks attached to it.
331 * However since task_group() uses task_subsys_state() which is an
332 * rcu_dereference() user, this quiets CONFIG_PROVE_RCU.
334 rcu_read_lock();
335 #ifdef CONFIG_FAIR_GROUP_SCHED
336 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
337 p->se.parent = task_group(p)->se[cpu];
338 #endif
340 #ifdef CONFIG_RT_GROUP_SCHED
341 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
342 p->rt.parent = task_group(p)->rt_se[cpu];
343 #endif
344 rcu_read_unlock();
347 #else
349 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
350 static inline struct task_group *task_group(struct task_struct *p)
352 return NULL;
355 #endif /* CONFIG_CGROUP_SCHED */
357 /* CFS-related fields in a runqueue */
358 struct cfs_rq {
359 struct load_weight load;
360 unsigned long nr_running;
362 u64 exec_clock;
363 u64 min_vruntime;
365 struct rb_root tasks_timeline;
366 struct rb_node *rb_leftmost;
368 struct list_head tasks;
369 struct list_head *balance_iterator;
372 * 'curr' points to currently running entity on this cfs_rq.
373 * It is set to NULL otherwise (i.e when none are currently running).
375 struct sched_entity *curr, *next, *last;
377 unsigned int nr_spread_over;
379 #ifdef CONFIG_FAIR_GROUP_SCHED
380 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
383 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
384 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
385 * (like users, containers etc.)
387 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
388 * list is used during load balance.
390 struct list_head leaf_cfs_rq_list;
391 struct task_group *tg; /* group that "owns" this runqueue */
393 #ifdef CONFIG_SMP
395 * the part of load.weight contributed by tasks
397 unsigned long task_weight;
400 * h_load = weight * f(tg)
402 * Where f(tg) is the recursive weight fraction assigned to
403 * this group.
405 unsigned long h_load;
408 * this cpu's part of tg->shares
410 unsigned long shares;
413 * load.weight at the time we set shares
415 unsigned long rq_weight;
416 #endif
417 #endif
420 /* Real-Time classes' related field in a runqueue: */
421 struct rt_rq {
422 struct rt_prio_array active;
423 unsigned long rt_nr_running;
424 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
425 struct {
426 int curr; /* highest queued rt task prio */
427 #ifdef CONFIG_SMP
428 int next; /* next highest */
429 #endif
430 } highest_prio;
431 #endif
432 #ifdef CONFIG_SMP
433 unsigned long rt_nr_migratory;
434 unsigned long rt_nr_total;
435 int overloaded;
436 struct plist_head pushable_tasks;
437 #endif
438 int rt_throttled;
439 u64 rt_time;
440 u64 rt_runtime;
441 /* Nests inside the rq lock: */
442 raw_spinlock_t rt_runtime_lock;
444 #ifdef CONFIG_RT_GROUP_SCHED
445 unsigned long rt_nr_boosted;
447 struct rq *rq;
448 struct list_head leaf_rt_rq_list;
449 struct task_group *tg;
450 #endif
453 #ifdef CONFIG_SMP
456 * We add the notion of a root-domain which will be used to define per-domain
457 * variables. Each exclusive cpuset essentially defines an island domain by
458 * fully partitioning the member cpus from any other cpuset. Whenever a new
459 * exclusive cpuset is created, we also create and attach a new root-domain
460 * object.
463 struct root_domain {
464 atomic_t refcount;
465 cpumask_var_t span;
466 cpumask_var_t online;
469 * The "RT overload" flag: it gets set if a CPU has more than
470 * one runnable RT task.
472 cpumask_var_t rto_mask;
473 atomic_t rto_count;
474 #ifdef CONFIG_SMP
475 struct cpupri cpupri;
476 #endif
480 * By default the system creates a single root-domain with all cpus as
481 * members (mimicking the global state we have today).
483 static struct root_domain def_root_domain;
485 #endif
488 * This is the main, per-CPU runqueue data structure.
490 * Locking rule: those places that want to lock multiple runqueues
491 * (such as the load balancing or the thread migration code), lock
492 * acquire operations must be ordered by ascending &runqueue.
494 struct rq {
495 /* runqueue lock: */
496 raw_spinlock_t lock;
499 * nr_running and cpu_load should be in the same cacheline because
500 * remote CPUs use both these fields when doing load calculation.
502 unsigned long nr_running;
503 #define CPU_LOAD_IDX_MAX 5
504 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
505 #ifdef CONFIG_NO_HZ
506 unsigned char in_nohz_recently;
507 #endif
508 /* capture load from *all* tasks on this cpu: */
509 struct load_weight load;
510 unsigned long nr_load_updates;
511 u64 nr_switches;
513 struct cfs_rq cfs;
514 struct rt_rq rt;
516 #ifdef CONFIG_FAIR_GROUP_SCHED
517 /* list of leaf cfs_rq on this cpu: */
518 struct list_head leaf_cfs_rq_list;
519 #endif
520 #ifdef CONFIG_RT_GROUP_SCHED
521 struct list_head leaf_rt_rq_list;
522 #endif
525 * This is part of a global counter where only the total sum
526 * over all CPUs matters. A task can increase this counter on
527 * one CPU and if it got migrated afterwards it may decrease
528 * it on another CPU. Always updated under the runqueue lock:
530 unsigned long nr_uninterruptible;
532 struct task_struct *curr, *idle;
533 unsigned long next_balance;
534 struct mm_struct *prev_mm;
536 u64 clock;
538 atomic_t nr_iowait;
540 #ifdef CONFIG_SMP
541 struct root_domain *rd;
542 struct sched_domain *sd;
544 unsigned long cpu_power;
546 unsigned char idle_at_tick;
547 /* For active balancing */
548 int post_schedule;
549 int active_balance;
550 int push_cpu;
551 /* cpu of this runqueue: */
552 int cpu;
553 int online;
555 unsigned long avg_load_per_task;
557 struct task_struct *migration_thread;
558 struct list_head migration_queue;
560 u64 rt_avg;
561 u64 age_stamp;
562 u64 idle_stamp;
563 u64 avg_idle;
564 #endif
566 /* calc_load related fields */
567 unsigned long calc_load_update;
568 long calc_load_active;
570 #ifdef CONFIG_SCHED_HRTICK
571 #ifdef CONFIG_SMP
572 int hrtick_csd_pending;
573 struct call_single_data hrtick_csd;
574 #endif
575 struct hrtimer hrtick_timer;
576 #endif
578 #ifdef CONFIG_SCHEDSTATS
579 /* latency stats */
580 struct sched_info rq_sched_info;
581 unsigned long long rq_cpu_time;
582 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
584 /* sys_sched_yield() stats */
585 unsigned int yld_count;
587 /* schedule() stats */
588 unsigned int sched_switch;
589 unsigned int sched_count;
590 unsigned int sched_goidle;
592 /* try_to_wake_up() stats */
593 unsigned int ttwu_count;
594 unsigned int ttwu_local;
596 /* BKL stats */
597 unsigned int bkl_count;
598 #endif
601 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
603 static inline
604 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
606 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
609 static inline int cpu_of(struct rq *rq)
611 #ifdef CONFIG_SMP
612 return rq->cpu;
613 #else
614 return 0;
615 #endif
618 #define rcu_dereference_check_sched_domain(p) \
619 rcu_dereference_check((p), \
620 rcu_read_lock_sched_held() || \
621 lockdep_is_held(&sched_domains_mutex))
624 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
625 * See detach_destroy_domains: synchronize_sched for details.
627 * The domain tree of any CPU may only be accessed from within
628 * preempt-disabled sections.
630 #define for_each_domain(cpu, __sd) \
631 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
633 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
634 #define this_rq() (&__get_cpu_var(runqueues))
635 #define task_rq(p) cpu_rq(task_cpu(p))
636 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
637 #define raw_rq() (&__raw_get_cpu_var(runqueues))
639 inline void update_rq_clock(struct rq *rq)
641 rq->clock = sched_clock_cpu(cpu_of(rq));
645 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
647 #ifdef CONFIG_SCHED_DEBUG
648 # define const_debug __read_mostly
649 #else
650 # define const_debug static const
651 #endif
654 * runqueue_is_locked
655 * @cpu: the processor in question.
657 * Returns true if the current cpu runqueue is locked.
658 * This interface allows printk to be called with the runqueue lock
659 * held and know whether or not it is OK to wake up the klogd.
661 int runqueue_is_locked(int cpu)
663 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
667 * Debugging: various feature bits
670 #define SCHED_FEAT(name, enabled) \
671 __SCHED_FEAT_##name ,
673 enum {
674 #include "sched_features.h"
677 #undef SCHED_FEAT
679 #define SCHED_FEAT(name, enabled) \
680 (1UL << __SCHED_FEAT_##name) * enabled |
682 const_debug unsigned int sysctl_sched_features =
683 #include "sched_features.h"
686 #undef SCHED_FEAT
688 #ifdef CONFIG_SCHED_DEBUG
689 #define SCHED_FEAT(name, enabled) \
690 #name ,
692 static __read_mostly char *sched_feat_names[] = {
693 #include "sched_features.h"
694 NULL
697 #undef SCHED_FEAT
699 static int sched_feat_show(struct seq_file *m, void *v)
701 int i;
703 for (i = 0; sched_feat_names[i]; i++) {
704 if (!(sysctl_sched_features & (1UL << i)))
705 seq_puts(m, "NO_");
706 seq_printf(m, "%s ", sched_feat_names[i]);
708 seq_puts(m, "\n");
710 return 0;
713 static ssize_t
714 sched_feat_write(struct file *filp, const char __user *ubuf,
715 size_t cnt, loff_t *ppos)
717 char buf[64];
718 char *cmp;
719 int neg = 0;
720 int i;
722 if (cnt > 63)
723 cnt = 63;
725 if (copy_from_user(&buf, ubuf, cnt))
726 return -EFAULT;
728 buf[cnt] = 0;
729 cmp = strstrip(buf);
731 if (strncmp(buf, "NO_", 3) == 0) {
732 neg = 1;
733 cmp += 3;
736 for (i = 0; sched_feat_names[i]; i++) {
737 if (strcmp(cmp, sched_feat_names[i]) == 0) {
738 if (neg)
739 sysctl_sched_features &= ~(1UL << i);
740 else
741 sysctl_sched_features |= (1UL << i);
742 break;
746 if (!sched_feat_names[i])
747 return -EINVAL;
749 *ppos += cnt;
751 return cnt;
754 static int sched_feat_open(struct inode *inode, struct file *filp)
756 return single_open(filp, sched_feat_show, NULL);
759 static const struct file_operations sched_feat_fops = {
760 .open = sched_feat_open,
761 .write = sched_feat_write,
762 .read = seq_read,
763 .llseek = seq_lseek,
764 .release = single_release,
767 static __init int sched_init_debug(void)
769 debugfs_create_file("sched_features", 0644, NULL, NULL,
770 &sched_feat_fops);
772 return 0;
774 late_initcall(sched_init_debug);
776 #endif
778 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
781 * Number of tasks to iterate in a single balance run.
782 * Limited because this is done with IRQs disabled.
784 const_debug unsigned int sysctl_sched_nr_migrate = 32;
787 * ratelimit for updating the group shares.
788 * default: 0.25ms
790 unsigned int sysctl_sched_shares_ratelimit = 250000;
791 unsigned int normalized_sysctl_sched_shares_ratelimit = 250000;
794 * Inject some fuzzyness into changing the per-cpu group shares
795 * this avoids remote rq-locks at the expense of fairness.
796 * default: 4
798 unsigned int sysctl_sched_shares_thresh = 4;
801 * period over which we average the RT time consumption, measured
802 * in ms.
804 * default: 1s
806 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
809 * period over which we measure -rt task cpu usage in us.
810 * default: 1s
812 unsigned int sysctl_sched_rt_period = 1000000;
814 static __read_mostly int scheduler_running;
817 * part of the period that we allow rt tasks to run in us.
818 * default: 0.95s
820 int sysctl_sched_rt_runtime = 950000;
822 static inline u64 global_rt_period(void)
824 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
827 static inline u64 global_rt_runtime(void)
829 if (sysctl_sched_rt_runtime < 0)
830 return RUNTIME_INF;
832 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
835 #ifndef prepare_arch_switch
836 # define prepare_arch_switch(next) do { } while (0)
837 #endif
838 #ifndef finish_arch_switch
839 # define finish_arch_switch(prev) do { } while (0)
840 #endif
842 static inline int task_current(struct rq *rq, struct task_struct *p)
844 return rq->curr == p;
847 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
848 static inline int task_running(struct rq *rq, struct task_struct *p)
850 return task_current(rq, p);
853 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
857 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
859 #ifdef CONFIG_DEBUG_SPINLOCK
860 /* this is a valid case when another task releases the spinlock */
861 rq->lock.owner = current;
862 #endif
864 * If we are tracking spinlock dependencies then we have to
865 * fix up the runqueue lock - which gets 'carried over' from
866 * prev into current:
868 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
870 raw_spin_unlock_irq(&rq->lock);
873 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
874 static inline int task_running(struct rq *rq, struct task_struct *p)
876 #ifdef CONFIG_SMP
877 return p->oncpu;
878 #else
879 return task_current(rq, p);
880 #endif
883 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
885 #ifdef CONFIG_SMP
887 * We can optimise this out completely for !SMP, because the
888 * SMP rebalancing from interrupt is the only thing that cares
889 * here.
891 next->oncpu = 1;
892 #endif
893 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
894 raw_spin_unlock_irq(&rq->lock);
895 #else
896 raw_spin_unlock(&rq->lock);
897 #endif
900 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
902 #ifdef CONFIG_SMP
904 * After ->oncpu is cleared, the task can be moved to a different CPU.
905 * We must ensure this doesn't happen until the switch is completely
906 * finished.
908 smp_wmb();
909 prev->oncpu = 0;
910 #endif
911 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
912 local_irq_enable();
913 #endif
915 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
918 * Check whether the task is waking, we use this to synchronize ->cpus_allowed
919 * against ttwu().
921 static inline int task_is_waking(struct task_struct *p)
923 return unlikely(p->state == TASK_WAKING);
927 * __task_rq_lock - lock the runqueue a given task resides on.
928 * Must be called interrupts disabled.
930 static inline struct rq *__task_rq_lock(struct task_struct *p)
931 __acquires(rq->lock)
933 struct rq *rq;
935 for (;;) {
936 rq = task_rq(p);
937 raw_spin_lock(&rq->lock);
938 if (likely(rq == task_rq(p)))
939 return rq;
940 raw_spin_unlock(&rq->lock);
945 * task_rq_lock - lock the runqueue a given task resides on and disable
946 * interrupts. Note the ordering: we can safely lookup the task_rq without
947 * explicitly disabling preemption.
949 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
950 __acquires(rq->lock)
952 struct rq *rq;
954 for (;;) {
955 local_irq_save(*flags);
956 rq = task_rq(p);
957 raw_spin_lock(&rq->lock);
958 if (likely(rq == task_rq(p)))
959 return rq;
960 raw_spin_unlock_irqrestore(&rq->lock, *flags);
964 void task_rq_unlock_wait(struct task_struct *p)
966 struct rq *rq = task_rq(p);
968 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
969 raw_spin_unlock_wait(&rq->lock);
972 static void __task_rq_unlock(struct rq *rq)
973 __releases(rq->lock)
975 raw_spin_unlock(&rq->lock);
978 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
979 __releases(rq->lock)
981 raw_spin_unlock_irqrestore(&rq->lock, *flags);
985 * this_rq_lock - lock this runqueue and disable interrupts.
987 static struct rq *this_rq_lock(void)
988 __acquires(rq->lock)
990 struct rq *rq;
992 local_irq_disable();
993 rq = this_rq();
994 raw_spin_lock(&rq->lock);
996 return rq;
999 #ifdef CONFIG_SCHED_HRTICK
1001 * Use HR-timers to deliver accurate preemption points.
1003 * Its all a bit involved since we cannot program an hrt while holding the
1004 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1005 * reschedule event.
1007 * When we get rescheduled we reprogram the hrtick_timer outside of the
1008 * rq->lock.
1012 * Use hrtick when:
1013 * - enabled by features
1014 * - hrtimer is actually high res
1016 static inline int hrtick_enabled(struct rq *rq)
1018 if (!sched_feat(HRTICK))
1019 return 0;
1020 if (!cpu_active(cpu_of(rq)))
1021 return 0;
1022 return hrtimer_is_hres_active(&rq->hrtick_timer);
1025 static void hrtick_clear(struct rq *rq)
1027 if (hrtimer_active(&rq->hrtick_timer))
1028 hrtimer_cancel(&rq->hrtick_timer);
1032 * High-resolution timer tick.
1033 * Runs from hardirq context with interrupts disabled.
1035 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1037 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1039 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1041 raw_spin_lock(&rq->lock);
1042 update_rq_clock(rq);
1043 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1044 raw_spin_unlock(&rq->lock);
1046 return HRTIMER_NORESTART;
1049 #ifdef CONFIG_SMP
1051 * called from hardirq (IPI) context
1053 static void __hrtick_start(void *arg)
1055 struct rq *rq = arg;
1057 raw_spin_lock(&rq->lock);
1058 hrtimer_restart(&rq->hrtick_timer);
1059 rq->hrtick_csd_pending = 0;
1060 raw_spin_unlock(&rq->lock);
1064 * Called to set the hrtick timer state.
1066 * called with rq->lock held and irqs disabled
1068 static void hrtick_start(struct rq *rq, u64 delay)
1070 struct hrtimer *timer = &rq->hrtick_timer;
1071 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1073 hrtimer_set_expires(timer, time);
1075 if (rq == this_rq()) {
1076 hrtimer_restart(timer);
1077 } else if (!rq->hrtick_csd_pending) {
1078 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1079 rq->hrtick_csd_pending = 1;
1083 static int
1084 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1086 int cpu = (int)(long)hcpu;
1088 switch (action) {
1089 case CPU_UP_CANCELED:
1090 case CPU_UP_CANCELED_FROZEN:
1091 case CPU_DOWN_PREPARE:
1092 case CPU_DOWN_PREPARE_FROZEN:
1093 case CPU_DEAD:
1094 case CPU_DEAD_FROZEN:
1095 hrtick_clear(cpu_rq(cpu));
1096 return NOTIFY_OK;
1099 return NOTIFY_DONE;
1102 static __init void init_hrtick(void)
1104 hotcpu_notifier(hotplug_hrtick, 0);
1106 #else
1108 * Called to set the hrtick timer state.
1110 * called with rq->lock held and irqs disabled
1112 static void hrtick_start(struct rq *rq, u64 delay)
1114 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1115 HRTIMER_MODE_REL_PINNED, 0);
1118 static inline void init_hrtick(void)
1121 #endif /* CONFIG_SMP */
1123 static void init_rq_hrtick(struct rq *rq)
1125 #ifdef CONFIG_SMP
1126 rq->hrtick_csd_pending = 0;
1128 rq->hrtick_csd.flags = 0;
1129 rq->hrtick_csd.func = __hrtick_start;
1130 rq->hrtick_csd.info = rq;
1131 #endif
1133 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1134 rq->hrtick_timer.function = hrtick;
1136 #else /* CONFIG_SCHED_HRTICK */
1137 static inline void hrtick_clear(struct rq *rq)
1141 static inline void init_rq_hrtick(struct rq *rq)
1145 static inline void init_hrtick(void)
1148 #endif /* CONFIG_SCHED_HRTICK */
1151 * resched_task - mark a task 'to be rescheduled now'.
1153 * On UP this means the setting of the need_resched flag, on SMP it
1154 * might also involve a cross-CPU call to trigger the scheduler on
1155 * the target CPU.
1157 #ifdef CONFIG_SMP
1159 #ifndef tsk_is_polling
1160 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1161 #endif
1163 static void resched_task(struct task_struct *p)
1165 int cpu;
1167 assert_raw_spin_locked(&task_rq(p)->lock);
1169 if (test_tsk_need_resched(p))
1170 return;
1172 set_tsk_need_resched(p);
1174 cpu = task_cpu(p);
1175 if (cpu == smp_processor_id())
1176 return;
1178 /* NEED_RESCHED must be visible before we test polling */
1179 smp_mb();
1180 if (!tsk_is_polling(p))
1181 smp_send_reschedule(cpu);
1184 static void resched_cpu(int cpu)
1186 struct rq *rq = cpu_rq(cpu);
1187 unsigned long flags;
1189 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1190 return;
1191 resched_task(cpu_curr(cpu));
1192 raw_spin_unlock_irqrestore(&rq->lock, flags);
1195 #ifdef CONFIG_NO_HZ
1197 * When add_timer_on() enqueues a timer into the timer wheel of an
1198 * idle CPU then this timer might expire before the next timer event
1199 * which is scheduled to wake up that CPU. In case of a completely
1200 * idle system the next event might even be infinite time into the
1201 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1202 * leaves the inner idle loop so the newly added timer is taken into
1203 * account when the CPU goes back to idle and evaluates the timer
1204 * wheel for the next timer event.
1206 void wake_up_idle_cpu(int cpu)
1208 struct rq *rq = cpu_rq(cpu);
1210 if (cpu == smp_processor_id())
1211 return;
1214 * This is safe, as this function is called with the timer
1215 * wheel base lock of (cpu) held. When the CPU is on the way
1216 * to idle and has not yet set rq->curr to idle then it will
1217 * be serialized on the timer wheel base lock and take the new
1218 * timer into account automatically.
1220 if (rq->curr != rq->idle)
1221 return;
1224 * We can set TIF_RESCHED on the idle task of the other CPU
1225 * lockless. The worst case is that the other CPU runs the
1226 * idle task through an additional NOOP schedule()
1228 set_tsk_need_resched(rq->idle);
1230 /* NEED_RESCHED must be visible before we test polling */
1231 smp_mb();
1232 if (!tsk_is_polling(rq->idle))
1233 smp_send_reschedule(cpu);
1235 #endif /* CONFIG_NO_HZ */
1237 static u64 sched_avg_period(void)
1239 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1242 static void sched_avg_update(struct rq *rq)
1244 s64 period = sched_avg_period();
1246 while ((s64)(rq->clock - rq->age_stamp) > period) {
1248 * Inline assembly required to prevent the compiler
1249 * optimising this loop into a divmod call.
1250 * See __iter_div_u64_rem() for another example of this.
1252 asm("" : "+rm" (rq->age_stamp));
1253 rq->age_stamp += period;
1254 rq->rt_avg /= 2;
1258 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1260 rq->rt_avg += rt_delta;
1261 sched_avg_update(rq);
1264 #else /* !CONFIG_SMP */
1265 static void resched_task(struct task_struct *p)
1267 assert_raw_spin_locked(&task_rq(p)->lock);
1268 set_tsk_need_resched(p);
1271 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1275 static void sched_avg_update(struct rq *rq)
1278 #endif /* CONFIG_SMP */
1280 #if BITS_PER_LONG == 32
1281 # define WMULT_CONST (~0UL)
1282 #else
1283 # define WMULT_CONST (1UL << 32)
1284 #endif
1286 #define WMULT_SHIFT 32
1289 * Shift right and round:
1291 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1294 * delta *= weight / lw
1296 static unsigned long
1297 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1298 struct load_weight *lw)
1300 u64 tmp;
1302 if (!lw->inv_weight) {
1303 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1304 lw->inv_weight = 1;
1305 else
1306 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1307 / (lw->weight+1);
1310 tmp = (u64)delta_exec * weight;
1312 * Check whether we'd overflow the 64-bit multiplication:
1314 if (unlikely(tmp > WMULT_CONST))
1315 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1316 WMULT_SHIFT/2);
1317 else
1318 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1320 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1323 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1325 lw->weight += inc;
1326 lw->inv_weight = 0;
1329 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1331 lw->weight -= dec;
1332 lw->inv_weight = 0;
1336 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1337 * of tasks with abnormal "nice" values across CPUs the contribution that
1338 * each task makes to its run queue's load is weighted according to its
1339 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1340 * scaled version of the new time slice allocation that they receive on time
1341 * slice expiry etc.
1344 #define WEIGHT_IDLEPRIO 3
1345 #define WMULT_IDLEPRIO 1431655765
1348 * Nice levels are multiplicative, with a gentle 10% change for every
1349 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1350 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1351 * that remained on nice 0.
1353 * The "10% effect" is relative and cumulative: from _any_ nice level,
1354 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1355 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1356 * If a task goes up by ~10% and another task goes down by ~10% then
1357 * the relative distance between them is ~25%.)
1359 static const int prio_to_weight[40] = {
1360 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1361 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1362 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1363 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1364 /* 0 */ 1024, 820, 655, 526, 423,
1365 /* 5 */ 335, 272, 215, 172, 137,
1366 /* 10 */ 110, 87, 70, 56, 45,
1367 /* 15 */ 36, 29, 23, 18, 15,
1371 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1373 * In cases where the weight does not change often, we can use the
1374 * precalculated inverse to speed up arithmetics by turning divisions
1375 * into multiplications:
1377 static const u32 prio_to_wmult[40] = {
1378 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1379 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1380 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1381 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1382 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1383 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1384 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1385 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1388 /* Time spent by the tasks of the cpu accounting group executing in ... */
1389 enum cpuacct_stat_index {
1390 CPUACCT_STAT_USER, /* ... user mode */
1391 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1393 CPUACCT_STAT_NSTATS,
1396 #ifdef CONFIG_CGROUP_CPUACCT
1397 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1398 static void cpuacct_update_stats(struct task_struct *tsk,
1399 enum cpuacct_stat_index idx, cputime_t val);
1400 #else
1401 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1402 static inline void cpuacct_update_stats(struct task_struct *tsk,
1403 enum cpuacct_stat_index idx, cputime_t val) {}
1404 #endif
1406 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1408 update_load_add(&rq->load, load);
1411 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1413 update_load_sub(&rq->load, load);
1416 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1417 typedef int (*tg_visitor)(struct task_group *, void *);
1420 * Iterate the full tree, calling @down when first entering a node and @up when
1421 * leaving it for the final time.
1423 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1425 struct task_group *parent, *child;
1426 int ret;
1428 rcu_read_lock();
1429 parent = &root_task_group;
1430 down:
1431 ret = (*down)(parent, data);
1432 if (ret)
1433 goto out_unlock;
1434 list_for_each_entry_rcu(child, &parent->children, siblings) {
1435 parent = child;
1436 goto down;
1439 continue;
1441 ret = (*up)(parent, data);
1442 if (ret)
1443 goto out_unlock;
1445 child = parent;
1446 parent = parent->parent;
1447 if (parent)
1448 goto up;
1449 out_unlock:
1450 rcu_read_unlock();
1452 return ret;
1455 static int tg_nop(struct task_group *tg, void *data)
1457 return 0;
1459 #endif
1461 #ifdef CONFIG_SMP
1462 /* Used instead of source_load when we know the type == 0 */
1463 static unsigned long weighted_cpuload(const int cpu)
1465 return cpu_rq(cpu)->load.weight;
1469 * Return a low guess at the load of a migration-source cpu weighted
1470 * according to the scheduling class and "nice" value.
1472 * We want to under-estimate the load of migration sources, to
1473 * balance conservatively.
1475 static unsigned long source_load(int cpu, int type)
1477 struct rq *rq = cpu_rq(cpu);
1478 unsigned long total = weighted_cpuload(cpu);
1480 if (type == 0 || !sched_feat(LB_BIAS))
1481 return total;
1483 return min(rq->cpu_load[type-1], total);
1487 * Return a high guess at the load of a migration-target cpu weighted
1488 * according to the scheduling class and "nice" value.
1490 static unsigned long target_load(int cpu, int type)
1492 struct rq *rq = cpu_rq(cpu);
1493 unsigned long total = weighted_cpuload(cpu);
1495 if (type == 0 || !sched_feat(LB_BIAS))
1496 return total;
1498 return max(rq->cpu_load[type-1], total);
1501 static unsigned long power_of(int cpu)
1503 return cpu_rq(cpu)->cpu_power;
1506 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1508 static unsigned long cpu_avg_load_per_task(int cpu)
1510 struct rq *rq = cpu_rq(cpu);
1511 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1513 if (nr_running)
1514 rq->avg_load_per_task = rq->load.weight / nr_running;
1515 else
1516 rq->avg_load_per_task = 0;
1518 return rq->avg_load_per_task;
1521 #ifdef CONFIG_FAIR_GROUP_SCHED
1523 static __read_mostly unsigned long __percpu *update_shares_data;
1525 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1528 * Calculate and set the cpu's group shares.
1530 static void update_group_shares_cpu(struct task_group *tg, int cpu,
1531 unsigned long sd_shares,
1532 unsigned long sd_rq_weight,
1533 unsigned long *usd_rq_weight)
1535 unsigned long shares, rq_weight;
1536 int boost = 0;
1538 rq_weight = usd_rq_weight[cpu];
1539 if (!rq_weight) {
1540 boost = 1;
1541 rq_weight = NICE_0_LOAD;
1545 * \Sum_j shares_j * rq_weight_i
1546 * shares_i = -----------------------------
1547 * \Sum_j rq_weight_j
1549 shares = (sd_shares * rq_weight) / sd_rq_weight;
1550 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1552 if (abs(shares - tg->se[cpu]->load.weight) >
1553 sysctl_sched_shares_thresh) {
1554 struct rq *rq = cpu_rq(cpu);
1555 unsigned long flags;
1557 raw_spin_lock_irqsave(&rq->lock, flags);
1558 tg->cfs_rq[cpu]->rq_weight = boost ? 0 : rq_weight;
1559 tg->cfs_rq[cpu]->shares = boost ? 0 : shares;
1560 __set_se_shares(tg->se[cpu], shares);
1561 raw_spin_unlock_irqrestore(&rq->lock, flags);
1566 * Re-compute the task group their per cpu shares over the given domain.
1567 * This needs to be done in a bottom-up fashion because the rq weight of a
1568 * parent group depends on the shares of its child groups.
1570 static int tg_shares_up(struct task_group *tg, void *data)
1572 unsigned long weight, rq_weight = 0, sum_weight = 0, shares = 0;
1573 unsigned long *usd_rq_weight;
1574 struct sched_domain *sd = data;
1575 unsigned long flags;
1576 int i;
1578 if (!tg->se[0])
1579 return 0;
1581 local_irq_save(flags);
1582 usd_rq_weight = per_cpu_ptr(update_shares_data, smp_processor_id());
1584 for_each_cpu(i, sched_domain_span(sd)) {
1585 weight = tg->cfs_rq[i]->load.weight;
1586 usd_rq_weight[i] = weight;
1588 rq_weight += weight;
1590 * If there are currently no tasks on the cpu pretend there
1591 * is one of average load so that when a new task gets to
1592 * run here it will not get delayed by group starvation.
1594 if (!weight)
1595 weight = NICE_0_LOAD;
1597 sum_weight += weight;
1598 shares += tg->cfs_rq[i]->shares;
1601 if (!rq_weight)
1602 rq_weight = sum_weight;
1604 if ((!shares && rq_weight) || shares > tg->shares)
1605 shares = tg->shares;
1607 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1608 shares = tg->shares;
1610 for_each_cpu(i, sched_domain_span(sd))
1611 update_group_shares_cpu(tg, i, shares, rq_weight, usd_rq_weight);
1613 local_irq_restore(flags);
1615 return 0;
1619 * Compute the cpu's hierarchical load factor for each task group.
1620 * This needs to be done in a top-down fashion because the load of a child
1621 * group is a fraction of its parents load.
1623 static int tg_load_down(struct task_group *tg, void *data)
1625 unsigned long load;
1626 long cpu = (long)data;
1628 if (!tg->parent) {
1629 load = cpu_rq(cpu)->load.weight;
1630 } else {
1631 load = tg->parent->cfs_rq[cpu]->h_load;
1632 load *= tg->cfs_rq[cpu]->shares;
1633 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1636 tg->cfs_rq[cpu]->h_load = load;
1638 return 0;
1641 static void update_shares(struct sched_domain *sd)
1643 s64 elapsed;
1644 u64 now;
1646 if (root_task_group_empty())
1647 return;
1649 now = cpu_clock(raw_smp_processor_id());
1650 elapsed = now - sd->last_update;
1652 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1653 sd->last_update = now;
1654 walk_tg_tree(tg_nop, tg_shares_up, sd);
1658 static void update_h_load(long cpu)
1660 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1663 #else
1665 static inline void update_shares(struct sched_domain *sd)
1669 #endif
1671 #ifdef CONFIG_PREEMPT
1673 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1676 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1677 * way at the expense of forcing extra atomic operations in all
1678 * invocations. This assures that the double_lock is acquired using the
1679 * same underlying policy as the spinlock_t on this architecture, which
1680 * reduces latency compared to the unfair variant below. However, it
1681 * also adds more overhead and therefore may reduce throughput.
1683 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1684 __releases(this_rq->lock)
1685 __acquires(busiest->lock)
1686 __acquires(this_rq->lock)
1688 raw_spin_unlock(&this_rq->lock);
1689 double_rq_lock(this_rq, busiest);
1691 return 1;
1694 #else
1696 * Unfair double_lock_balance: Optimizes throughput at the expense of
1697 * latency by eliminating extra atomic operations when the locks are
1698 * already in proper order on entry. This favors lower cpu-ids and will
1699 * grant the double lock to lower cpus over higher ids under contention,
1700 * regardless of entry order into the function.
1702 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1703 __releases(this_rq->lock)
1704 __acquires(busiest->lock)
1705 __acquires(this_rq->lock)
1707 int ret = 0;
1709 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1710 if (busiest < this_rq) {
1711 raw_spin_unlock(&this_rq->lock);
1712 raw_spin_lock(&busiest->lock);
1713 raw_spin_lock_nested(&this_rq->lock,
1714 SINGLE_DEPTH_NESTING);
1715 ret = 1;
1716 } else
1717 raw_spin_lock_nested(&busiest->lock,
1718 SINGLE_DEPTH_NESTING);
1720 return ret;
1723 #endif /* CONFIG_PREEMPT */
1726 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1728 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1730 if (unlikely(!irqs_disabled())) {
1731 /* printk() doesn't work good under rq->lock */
1732 raw_spin_unlock(&this_rq->lock);
1733 BUG_ON(1);
1736 return _double_lock_balance(this_rq, busiest);
1739 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1740 __releases(busiest->lock)
1742 raw_spin_unlock(&busiest->lock);
1743 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1747 * double_rq_lock - safely lock two runqueues
1749 * Note this does not disable interrupts like task_rq_lock,
1750 * you need to do so manually before calling.
1752 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1753 __acquires(rq1->lock)
1754 __acquires(rq2->lock)
1756 BUG_ON(!irqs_disabled());
1757 if (rq1 == rq2) {
1758 raw_spin_lock(&rq1->lock);
1759 __acquire(rq2->lock); /* Fake it out ;) */
1760 } else {
1761 if (rq1 < rq2) {
1762 raw_spin_lock(&rq1->lock);
1763 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1764 } else {
1765 raw_spin_lock(&rq2->lock);
1766 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1769 update_rq_clock(rq1);
1770 update_rq_clock(rq2);
1774 * double_rq_unlock - safely unlock two runqueues
1776 * Note this does not restore interrupts like task_rq_unlock,
1777 * you need to do so manually after calling.
1779 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1780 __releases(rq1->lock)
1781 __releases(rq2->lock)
1783 raw_spin_unlock(&rq1->lock);
1784 if (rq1 != rq2)
1785 raw_spin_unlock(&rq2->lock);
1786 else
1787 __release(rq2->lock);
1790 #endif
1792 #ifdef CONFIG_FAIR_GROUP_SCHED
1793 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1795 #ifdef CONFIG_SMP
1796 cfs_rq->shares = shares;
1797 #endif
1799 #endif
1801 static void calc_load_account_active(struct rq *this_rq);
1802 static void update_sysctl(void);
1803 static int get_update_sysctl_factor(void);
1805 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1807 set_task_rq(p, cpu);
1808 #ifdef CONFIG_SMP
1810 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1811 * successfuly executed on another CPU. We must ensure that updates of
1812 * per-task data have been completed by this moment.
1814 smp_wmb();
1815 task_thread_info(p)->cpu = cpu;
1816 #endif
1819 static const struct sched_class rt_sched_class;
1821 #define sched_class_highest (&rt_sched_class)
1822 #define for_each_class(class) \
1823 for (class = sched_class_highest; class; class = class->next)
1825 #include "sched_stats.h"
1827 static void inc_nr_running(struct rq *rq)
1829 rq->nr_running++;
1832 static void dec_nr_running(struct rq *rq)
1834 rq->nr_running--;
1837 static void set_load_weight(struct task_struct *p)
1839 if (task_has_rt_policy(p)) {
1840 p->se.load.weight = 0;
1841 p->se.load.inv_weight = WMULT_CONST;
1842 return;
1846 * SCHED_IDLE tasks get minimal weight:
1848 if (p->policy == SCHED_IDLE) {
1849 p->se.load.weight = WEIGHT_IDLEPRIO;
1850 p->se.load.inv_weight = WMULT_IDLEPRIO;
1851 return;
1854 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1855 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1858 static void update_avg(u64 *avg, u64 sample)
1860 s64 diff = sample - *avg;
1861 *avg += diff >> 3;
1864 static void
1865 enqueue_task(struct rq *rq, struct task_struct *p, int wakeup, bool head)
1867 if (wakeup)
1868 p->se.start_runtime = p->se.sum_exec_runtime;
1870 sched_info_queued(p);
1871 p->sched_class->enqueue_task(rq, p, wakeup, head);
1872 p->se.on_rq = 1;
1875 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1877 if (sleep) {
1878 if (p->se.last_wakeup) {
1879 update_avg(&p->se.avg_overlap,
1880 p->se.sum_exec_runtime - p->se.last_wakeup);
1881 p->se.last_wakeup = 0;
1882 } else {
1883 update_avg(&p->se.avg_wakeup,
1884 sysctl_sched_wakeup_granularity);
1888 sched_info_dequeued(p);
1889 p->sched_class->dequeue_task(rq, p, sleep);
1890 p->se.on_rq = 0;
1894 * activate_task - move a task to the runqueue.
1896 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1898 if (task_contributes_to_load(p))
1899 rq->nr_uninterruptible--;
1901 enqueue_task(rq, p, wakeup, false);
1902 inc_nr_running(rq);
1906 * deactivate_task - remove a task from the runqueue.
1908 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1910 if (task_contributes_to_load(p))
1911 rq->nr_uninterruptible++;
1913 dequeue_task(rq, p, sleep);
1914 dec_nr_running(rq);
1917 #include "sched_idletask.c"
1918 #include "sched_fair.c"
1919 #include "sched_rt.c"
1920 #ifdef CONFIG_SCHED_DEBUG
1921 # include "sched_debug.c"
1922 #endif
1925 * __normal_prio - return the priority that is based on the static prio
1927 static inline int __normal_prio(struct task_struct *p)
1929 return p->static_prio;
1933 * Calculate the expected normal priority: i.e. priority
1934 * without taking RT-inheritance into account. Might be
1935 * boosted by interactivity modifiers. Changes upon fork,
1936 * setprio syscalls, and whenever the interactivity
1937 * estimator recalculates.
1939 static inline int normal_prio(struct task_struct *p)
1941 int prio;
1943 if (task_has_rt_policy(p))
1944 prio = MAX_RT_PRIO-1 - p->rt_priority;
1945 else
1946 prio = __normal_prio(p);
1947 return prio;
1951 * Calculate the current priority, i.e. the priority
1952 * taken into account by the scheduler. This value might
1953 * be boosted by RT tasks, or might be boosted by
1954 * interactivity modifiers. Will be RT if the task got
1955 * RT-boosted. If not then it returns p->normal_prio.
1957 static int effective_prio(struct task_struct *p)
1959 p->normal_prio = normal_prio(p);
1961 * If we are RT tasks or we were boosted to RT priority,
1962 * keep the priority unchanged. Otherwise, update priority
1963 * to the normal priority:
1965 if (!rt_prio(p->prio))
1966 return p->normal_prio;
1967 return p->prio;
1971 * task_curr - is this task currently executing on a CPU?
1972 * @p: the task in question.
1974 inline int task_curr(const struct task_struct *p)
1976 return cpu_curr(task_cpu(p)) == p;
1979 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1980 const struct sched_class *prev_class,
1981 int oldprio, int running)
1983 if (prev_class != p->sched_class) {
1984 if (prev_class->switched_from)
1985 prev_class->switched_from(rq, p, running);
1986 p->sched_class->switched_to(rq, p, running);
1987 } else
1988 p->sched_class->prio_changed(rq, p, oldprio, running);
1991 #ifdef CONFIG_SMP
1993 * Is this task likely cache-hot:
1995 static int
1996 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1998 s64 delta;
2000 if (p->sched_class != &fair_sched_class)
2001 return 0;
2004 * Buddy candidates are cache hot:
2006 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2007 (&p->se == cfs_rq_of(&p->se)->next ||
2008 &p->se == cfs_rq_of(&p->se)->last))
2009 return 1;
2011 if (sysctl_sched_migration_cost == -1)
2012 return 1;
2013 if (sysctl_sched_migration_cost == 0)
2014 return 0;
2016 delta = now - p->se.exec_start;
2018 return delta < (s64)sysctl_sched_migration_cost;
2021 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2023 #ifdef CONFIG_SCHED_DEBUG
2025 * We should never call set_task_cpu() on a blocked task,
2026 * ttwu() will sort out the placement.
2028 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2029 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2030 #endif
2032 trace_sched_migrate_task(p, new_cpu);
2034 if (task_cpu(p) != new_cpu) {
2035 p->se.nr_migrations++;
2036 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2039 __set_task_cpu(p, new_cpu);
2042 struct migration_req {
2043 struct list_head list;
2045 struct task_struct *task;
2046 int dest_cpu;
2048 struct completion done;
2052 * The task's runqueue lock must be held.
2053 * Returns true if you have to wait for migration thread.
2055 static int
2056 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2058 struct rq *rq = task_rq(p);
2061 * If the task is not on a runqueue (and not running), then
2062 * the next wake-up will properly place the task.
2064 if (!p->se.on_rq && !task_running(rq, p))
2065 return 0;
2067 init_completion(&req->done);
2068 req->task = p;
2069 req->dest_cpu = dest_cpu;
2070 list_add(&req->list, &rq->migration_queue);
2072 return 1;
2076 * wait_task_context_switch - wait for a thread to complete at least one
2077 * context switch.
2079 * @p must not be current.
2081 void wait_task_context_switch(struct task_struct *p)
2083 unsigned long nvcsw, nivcsw, flags;
2084 int running;
2085 struct rq *rq;
2087 nvcsw = p->nvcsw;
2088 nivcsw = p->nivcsw;
2089 for (;;) {
2091 * The runqueue is assigned before the actual context
2092 * switch. We need to take the runqueue lock.
2094 * We could check initially without the lock but it is
2095 * very likely that we need to take the lock in every
2096 * iteration.
2098 rq = task_rq_lock(p, &flags);
2099 running = task_running(rq, p);
2100 task_rq_unlock(rq, &flags);
2102 if (likely(!running))
2103 break;
2105 * The switch count is incremented before the actual
2106 * context switch. We thus wait for two switches to be
2107 * sure at least one completed.
2109 if ((p->nvcsw - nvcsw) > 1)
2110 break;
2111 if ((p->nivcsw - nivcsw) > 1)
2112 break;
2114 cpu_relax();
2119 * wait_task_inactive - wait for a thread to unschedule.
2121 * If @match_state is nonzero, it's the @p->state value just checked and
2122 * not expected to change. If it changes, i.e. @p might have woken up,
2123 * then return zero. When we succeed in waiting for @p to be off its CPU,
2124 * we return a positive number (its total switch count). If a second call
2125 * a short while later returns the same number, the caller can be sure that
2126 * @p has remained unscheduled the whole time.
2128 * The caller must ensure that the task *will* unschedule sometime soon,
2129 * else this function might spin for a *long* time. This function can't
2130 * be called with interrupts off, or it may introduce deadlock with
2131 * smp_call_function() if an IPI is sent by the same process we are
2132 * waiting to become inactive.
2134 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2136 unsigned long flags;
2137 int running, on_rq;
2138 unsigned long ncsw;
2139 struct rq *rq;
2141 for (;;) {
2143 * We do the initial early heuristics without holding
2144 * any task-queue locks at all. We'll only try to get
2145 * the runqueue lock when things look like they will
2146 * work out!
2148 rq = task_rq(p);
2151 * If the task is actively running on another CPU
2152 * still, just relax and busy-wait without holding
2153 * any locks.
2155 * NOTE! Since we don't hold any locks, it's not
2156 * even sure that "rq" stays as the right runqueue!
2157 * But we don't care, since "task_running()" will
2158 * return false if the runqueue has changed and p
2159 * is actually now running somewhere else!
2161 while (task_running(rq, p)) {
2162 if (match_state && unlikely(p->state != match_state))
2163 return 0;
2164 cpu_relax();
2168 * Ok, time to look more closely! We need the rq
2169 * lock now, to be *sure*. If we're wrong, we'll
2170 * just go back and repeat.
2172 rq = task_rq_lock(p, &flags);
2173 trace_sched_wait_task(rq, p);
2174 running = task_running(rq, p);
2175 on_rq = p->se.on_rq;
2176 ncsw = 0;
2177 if (!match_state || p->state == match_state)
2178 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2179 task_rq_unlock(rq, &flags);
2182 * If it changed from the expected state, bail out now.
2184 if (unlikely(!ncsw))
2185 break;
2188 * Was it really running after all now that we
2189 * checked with the proper locks actually held?
2191 * Oops. Go back and try again..
2193 if (unlikely(running)) {
2194 cpu_relax();
2195 continue;
2199 * It's not enough that it's not actively running,
2200 * it must be off the runqueue _entirely_, and not
2201 * preempted!
2203 * So if it was still runnable (but just not actively
2204 * running right now), it's preempted, and we should
2205 * yield - it could be a while.
2207 if (unlikely(on_rq)) {
2208 schedule_timeout_uninterruptible(1);
2209 continue;
2213 * Ahh, all good. It wasn't running, and it wasn't
2214 * runnable, which means that it will never become
2215 * running in the future either. We're all done!
2217 break;
2220 return ncsw;
2223 /***
2224 * kick_process - kick a running thread to enter/exit the kernel
2225 * @p: the to-be-kicked thread
2227 * Cause a process which is running on another CPU to enter
2228 * kernel-mode, without any delay. (to get signals handled.)
2230 * NOTE: this function doesnt have to take the runqueue lock,
2231 * because all it wants to ensure is that the remote task enters
2232 * the kernel. If the IPI races and the task has been migrated
2233 * to another CPU then no harm is done and the purpose has been
2234 * achieved as well.
2236 void kick_process(struct task_struct *p)
2238 int cpu;
2240 preempt_disable();
2241 cpu = task_cpu(p);
2242 if ((cpu != smp_processor_id()) && task_curr(p))
2243 smp_send_reschedule(cpu);
2244 preempt_enable();
2246 EXPORT_SYMBOL_GPL(kick_process);
2247 #endif /* CONFIG_SMP */
2250 * task_oncpu_function_call - call a function on the cpu on which a task runs
2251 * @p: the task to evaluate
2252 * @func: the function to be called
2253 * @info: the function call argument
2255 * Calls the function @func when the task is currently running. This might
2256 * be on the current CPU, which just calls the function directly
2258 void task_oncpu_function_call(struct task_struct *p,
2259 void (*func) (void *info), void *info)
2261 int cpu;
2263 preempt_disable();
2264 cpu = task_cpu(p);
2265 if (task_curr(p))
2266 smp_call_function_single(cpu, func, info, 1);
2267 preempt_enable();
2270 #ifdef CONFIG_SMP
2272 * ->cpus_allowed is protected by either TASK_WAKING or rq->lock held.
2274 static int select_fallback_rq(int cpu, struct task_struct *p)
2276 int dest_cpu;
2277 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2279 /* Look for allowed, online CPU in same node. */
2280 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2281 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2282 return dest_cpu;
2284 /* Any allowed, online CPU? */
2285 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2286 if (dest_cpu < nr_cpu_ids)
2287 return dest_cpu;
2289 /* No more Mr. Nice Guy. */
2290 if (unlikely(dest_cpu >= nr_cpu_ids)) {
2291 dest_cpu = cpuset_cpus_allowed_fallback(p);
2293 * Don't tell them about moving exiting tasks or
2294 * kernel threads (both mm NULL), since they never
2295 * leave kernel.
2297 if (p->mm && printk_ratelimit()) {
2298 printk(KERN_INFO "process %d (%s) no "
2299 "longer affine to cpu%d\n",
2300 task_pid_nr(p), p->comm, cpu);
2304 return dest_cpu;
2308 * The caller (fork, wakeup) owns TASK_WAKING, ->cpus_allowed is stable.
2310 static inline
2311 int select_task_rq(struct rq *rq, struct task_struct *p, int sd_flags, int wake_flags)
2313 int cpu = p->sched_class->select_task_rq(rq, p, sd_flags, wake_flags);
2316 * In order not to call set_task_cpu() on a blocking task we need
2317 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2318 * cpu.
2320 * Since this is common to all placement strategies, this lives here.
2322 * [ this allows ->select_task() to simply return task_cpu(p) and
2323 * not worry about this generic constraint ]
2325 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2326 !cpu_online(cpu)))
2327 cpu = select_fallback_rq(task_cpu(p), p);
2329 return cpu;
2331 #endif
2333 /***
2334 * try_to_wake_up - wake up a thread
2335 * @p: the to-be-woken-up thread
2336 * @state: the mask of task states that can be woken
2337 * @sync: do a synchronous wakeup?
2339 * Put it on the run-queue if it's not already there. The "current"
2340 * thread is always on the run-queue (except when the actual
2341 * re-schedule is in progress), and as such you're allowed to do
2342 * the simpler "current->state = TASK_RUNNING" to mark yourself
2343 * runnable without the overhead of this.
2345 * returns failure only if the task is already active.
2347 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2348 int wake_flags)
2350 int cpu, orig_cpu, this_cpu, success = 0;
2351 unsigned long flags;
2352 struct rq *rq;
2354 if (!sched_feat(SYNC_WAKEUPS))
2355 wake_flags &= ~WF_SYNC;
2357 this_cpu = get_cpu();
2359 smp_wmb();
2360 rq = task_rq_lock(p, &flags);
2361 update_rq_clock(rq);
2362 if (!(p->state & state))
2363 goto out;
2365 if (p->se.on_rq)
2366 goto out_running;
2368 cpu = task_cpu(p);
2369 orig_cpu = cpu;
2371 #ifdef CONFIG_SMP
2372 if (unlikely(task_running(rq, p)))
2373 goto out_activate;
2376 * In order to handle concurrent wakeups and release the rq->lock
2377 * we put the task in TASK_WAKING state.
2379 * First fix up the nr_uninterruptible count:
2381 if (task_contributes_to_load(p)) {
2382 if (likely(cpu_online(orig_cpu)))
2383 rq->nr_uninterruptible--;
2384 else
2385 this_rq()->nr_uninterruptible--;
2387 p->state = TASK_WAKING;
2389 if (p->sched_class->task_waking)
2390 p->sched_class->task_waking(rq, p);
2392 cpu = select_task_rq(rq, p, SD_BALANCE_WAKE, wake_flags);
2393 if (cpu != orig_cpu)
2394 set_task_cpu(p, cpu);
2395 __task_rq_unlock(rq);
2397 rq = cpu_rq(cpu);
2398 raw_spin_lock(&rq->lock);
2399 update_rq_clock(rq);
2402 * We migrated the task without holding either rq->lock, however
2403 * since the task is not on the task list itself, nobody else
2404 * will try and migrate the task, hence the rq should match the
2405 * cpu we just moved it to.
2407 WARN_ON(task_cpu(p) != cpu);
2408 WARN_ON(p->state != TASK_WAKING);
2410 #ifdef CONFIG_SCHEDSTATS
2411 schedstat_inc(rq, ttwu_count);
2412 if (cpu == this_cpu)
2413 schedstat_inc(rq, ttwu_local);
2414 else {
2415 struct sched_domain *sd;
2416 for_each_domain(this_cpu, sd) {
2417 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2418 schedstat_inc(sd, ttwu_wake_remote);
2419 break;
2423 #endif /* CONFIG_SCHEDSTATS */
2425 out_activate:
2426 #endif /* CONFIG_SMP */
2427 schedstat_inc(p, se.nr_wakeups);
2428 if (wake_flags & WF_SYNC)
2429 schedstat_inc(p, se.nr_wakeups_sync);
2430 if (orig_cpu != cpu)
2431 schedstat_inc(p, se.nr_wakeups_migrate);
2432 if (cpu == this_cpu)
2433 schedstat_inc(p, se.nr_wakeups_local);
2434 else
2435 schedstat_inc(p, se.nr_wakeups_remote);
2436 activate_task(rq, p, 1);
2437 success = 1;
2440 * Only attribute actual wakeups done by this task.
2442 if (!in_interrupt()) {
2443 struct sched_entity *se = &current->se;
2444 u64 sample = se->sum_exec_runtime;
2446 if (se->last_wakeup)
2447 sample -= se->last_wakeup;
2448 else
2449 sample -= se->start_runtime;
2450 update_avg(&se->avg_wakeup, sample);
2452 se->last_wakeup = se->sum_exec_runtime;
2455 out_running:
2456 trace_sched_wakeup(rq, p, success);
2457 check_preempt_curr(rq, p, wake_flags);
2459 p->state = TASK_RUNNING;
2460 #ifdef CONFIG_SMP
2461 if (p->sched_class->task_woken)
2462 p->sched_class->task_woken(rq, p);
2464 if (unlikely(rq->idle_stamp)) {
2465 u64 delta = rq->clock - rq->idle_stamp;
2466 u64 max = 2*sysctl_sched_migration_cost;
2468 if (delta > max)
2469 rq->avg_idle = max;
2470 else
2471 update_avg(&rq->avg_idle, delta);
2472 rq->idle_stamp = 0;
2474 #endif
2475 out:
2476 task_rq_unlock(rq, &flags);
2477 put_cpu();
2479 return success;
2483 * wake_up_process - Wake up a specific process
2484 * @p: The process to be woken up.
2486 * Attempt to wake up the nominated process and move it to the set of runnable
2487 * processes. Returns 1 if the process was woken up, 0 if it was already
2488 * running.
2490 * It may be assumed that this function implies a write memory barrier before
2491 * changing the task state if and only if any tasks are woken up.
2493 int wake_up_process(struct task_struct *p)
2495 return try_to_wake_up(p, TASK_ALL, 0);
2497 EXPORT_SYMBOL(wake_up_process);
2499 int wake_up_state(struct task_struct *p, unsigned int state)
2501 return try_to_wake_up(p, state, 0);
2505 * Perform scheduler related setup for a newly forked process p.
2506 * p is forked by current.
2508 * __sched_fork() is basic setup used by init_idle() too:
2510 static void __sched_fork(struct task_struct *p)
2512 p->se.exec_start = 0;
2513 p->se.sum_exec_runtime = 0;
2514 p->se.prev_sum_exec_runtime = 0;
2515 p->se.nr_migrations = 0;
2516 p->se.last_wakeup = 0;
2517 p->se.avg_overlap = 0;
2518 p->se.start_runtime = 0;
2519 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2521 #ifdef CONFIG_SCHEDSTATS
2522 p->se.wait_start = 0;
2523 p->se.wait_max = 0;
2524 p->se.wait_count = 0;
2525 p->se.wait_sum = 0;
2527 p->se.sleep_start = 0;
2528 p->se.sleep_max = 0;
2529 p->se.sum_sleep_runtime = 0;
2531 p->se.block_start = 0;
2532 p->se.block_max = 0;
2533 p->se.exec_max = 0;
2534 p->se.slice_max = 0;
2536 p->se.nr_migrations_cold = 0;
2537 p->se.nr_failed_migrations_affine = 0;
2538 p->se.nr_failed_migrations_running = 0;
2539 p->se.nr_failed_migrations_hot = 0;
2540 p->se.nr_forced_migrations = 0;
2542 p->se.nr_wakeups = 0;
2543 p->se.nr_wakeups_sync = 0;
2544 p->se.nr_wakeups_migrate = 0;
2545 p->se.nr_wakeups_local = 0;
2546 p->se.nr_wakeups_remote = 0;
2547 p->se.nr_wakeups_affine = 0;
2548 p->se.nr_wakeups_affine_attempts = 0;
2549 p->se.nr_wakeups_passive = 0;
2550 p->se.nr_wakeups_idle = 0;
2552 #endif
2554 INIT_LIST_HEAD(&p->rt.run_list);
2555 p->se.on_rq = 0;
2556 INIT_LIST_HEAD(&p->se.group_node);
2558 #ifdef CONFIG_PREEMPT_NOTIFIERS
2559 INIT_HLIST_HEAD(&p->preempt_notifiers);
2560 #endif
2564 * fork()/clone()-time setup:
2566 void sched_fork(struct task_struct *p, int clone_flags)
2568 int cpu = get_cpu();
2570 __sched_fork(p);
2572 * We mark the process as running here. This guarantees that
2573 * nobody will actually run it, and a signal or other external
2574 * event cannot wake it up and insert it on the runqueue either.
2576 p->state = TASK_RUNNING;
2579 * Revert to default priority/policy on fork if requested.
2581 if (unlikely(p->sched_reset_on_fork)) {
2582 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2583 p->policy = SCHED_NORMAL;
2584 p->normal_prio = p->static_prio;
2587 if (PRIO_TO_NICE(p->static_prio) < 0) {
2588 p->static_prio = NICE_TO_PRIO(0);
2589 p->normal_prio = p->static_prio;
2590 set_load_weight(p);
2594 * We don't need the reset flag anymore after the fork. It has
2595 * fulfilled its duty:
2597 p->sched_reset_on_fork = 0;
2601 * Make sure we do not leak PI boosting priority to the child.
2603 p->prio = current->normal_prio;
2605 if (!rt_prio(p->prio))
2606 p->sched_class = &fair_sched_class;
2608 if (p->sched_class->task_fork)
2609 p->sched_class->task_fork(p);
2611 set_task_cpu(p, cpu);
2613 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2614 if (likely(sched_info_on()))
2615 memset(&p->sched_info, 0, sizeof(p->sched_info));
2616 #endif
2617 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2618 p->oncpu = 0;
2619 #endif
2620 #ifdef CONFIG_PREEMPT
2621 /* Want to start with kernel preemption disabled. */
2622 task_thread_info(p)->preempt_count = 1;
2623 #endif
2624 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2626 put_cpu();
2630 * wake_up_new_task - wake up a newly created task for the first time.
2632 * This function will do some initial scheduler statistics housekeeping
2633 * that must be done for every newly created context, then puts the task
2634 * on the runqueue and wakes it.
2636 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2638 unsigned long flags;
2639 struct rq *rq;
2640 int cpu __maybe_unused = get_cpu();
2642 #ifdef CONFIG_SMP
2643 rq = task_rq_lock(p, &flags);
2644 p->state = TASK_WAKING;
2647 * Fork balancing, do it here and not earlier because:
2648 * - cpus_allowed can change in the fork path
2649 * - any previously selected cpu might disappear through hotplug
2651 * We set TASK_WAKING so that select_task_rq() can drop rq->lock
2652 * without people poking at ->cpus_allowed.
2654 cpu = select_task_rq(rq, p, SD_BALANCE_FORK, 0);
2655 set_task_cpu(p, cpu);
2657 p->state = TASK_RUNNING;
2658 task_rq_unlock(rq, &flags);
2659 #endif
2661 rq = task_rq_lock(p, &flags);
2662 update_rq_clock(rq);
2663 activate_task(rq, p, 0);
2664 trace_sched_wakeup_new(rq, p, 1);
2665 check_preempt_curr(rq, p, WF_FORK);
2666 #ifdef CONFIG_SMP
2667 if (p->sched_class->task_woken)
2668 p->sched_class->task_woken(rq, p);
2669 #endif
2670 task_rq_unlock(rq, &flags);
2671 put_cpu();
2674 #ifdef CONFIG_PREEMPT_NOTIFIERS
2677 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2678 * @notifier: notifier struct to register
2680 void preempt_notifier_register(struct preempt_notifier *notifier)
2682 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2684 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2687 * preempt_notifier_unregister - no longer interested in preemption notifications
2688 * @notifier: notifier struct to unregister
2690 * This is safe to call from within a preemption notifier.
2692 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2694 hlist_del(&notifier->link);
2696 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2698 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2700 struct preempt_notifier *notifier;
2701 struct hlist_node *node;
2703 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2704 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2707 static void
2708 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2709 struct task_struct *next)
2711 struct preempt_notifier *notifier;
2712 struct hlist_node *node;
2714 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2715 notifier->ops->sched_out(notifier, next);
2718 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2720 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2724 static void
2725 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2726 struct task_struct *next)
2730 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2733 * prepare_task_switch - prepare to switch tasks
2734 * @rq: the runqueue preparing to switch
2735 * @prev: the current task that is being switched out
2736 * @next: the task we are going to switch to.
2738 * This is called with the rq lock held and interrupts off. It must
2739 * be paired with a subsequent finish_task_switch after the context
2740 * switch.
2742 * prepare_task_switch sets up locking and calls architecture specific
2743 * hooks.
2745 static inline void
2746 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2747 struct task_struct *next)
2749 fire_sched_out_preempt_notifiers(prev, next);
2750 prepare_lock_switch(rq, next);
2751 prepare_arch_switch(next);
2755 * finish_task_switch - clean up after a task-switch
2756 * @rq: runqueue associated with task-switch
2757 * @prev: the thread we just switched away from.
2759 * finish_task_switch must be called after the context switch, paired
2760 * with a prepare_task_switch call before the context switch.
2761 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2762 * and do any other architecture-specific cleanup actions.
2764 * Note that we may have delayed dropping an mm in context_switch(). If
2765 * so, we finish that here outside of the runqueue lock. (Doing it
2766 * with the lock held can cause deadlocks; see schedule() for
2767 * details.)
2769 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2770 __releases(rq->lock)
2772 struct mm_struct *mm = rq->prev_mm;
2773 long prev_state;
2775 rq->prev_mm = NULL;
2778 * A task struct has one reference for the use as "current".
2779 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2780 * schedule one last time. The schedule call will never return, and
2781 * the scheduled task must drop that reference.
2782 * The test for TASK_DEAD must occur while the runqueue locks are
2783 * still held, otherwise prev could be scheduled on another cpu, die
2784 * there before we look at prev->state, and then the reference would
2785 * be dropped twice.
2786 * Manfred Spraul <manfred@colorfullife.com>
2788 prev_state = prev->state;
2789 finish_arch_switch(prev);
2790 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2791 local_irq_disable();
2792 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2793 perf_event_task_sched_in(current);
2794 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2795 local_irq_enable();
2796 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2797 finish_lock_switch(rq, prev);
2799 fire_sched_in_preempt_notifiers(current);
2800 if (mm)
2801 mmdrop(mm);
2802 if (unlikely(prev_state == TASK_DEAD)) {
2804 * Remove function-return probe instances associated with this
2805 * task and put them back on the free list.
2807 kprobe_flush_task(prev);
2808 put_task_struct(prev);
2812 #ifdef CONFIG_SMP
2814 /* assumes rq->lock is held */
2815 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2817 if (prev->sched_class->pre_schedule)
2818 prev->sched_class->pre_schedule(rq, prev);
2821 /* rq->lock is NOT held, but preemption is disabled */
2822 static inline void post_schedule(struct rq *rq)
2824 if (rq->post_schedule) {
2825 unsigned long flags;
2827 raw_spin_lock_irqsave(&rq->lock, flags);
2828 if (rq->curr->sched_class->post_schedule)
2829 rq->curr->sched_class->post_schedule(rq);
2830 raw_spin_unlock_irqrestore(&rq->lock, flags);
2832 rq->post_schedule = 0;
2836 #else
2838 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2842 static inline void post_schedule(struct rq *rq)
2846 #endif
2849 * schedule_tail - first thing a freshly forked thread must call.
2850 * @prev: the thread we just switched away from.
2852 asmlinkage void schedule_tail(struct task_struct *prev)
2853 __releases(rq->lock)
2855 struct rq *rq = this_rq();
2857 finish_task_switch(rq, prev);
2860 * FIXME: do we need to worry about rq being invalidated by the
2861 * task_switch?
2863 post_schedule(rq);
2865 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2866 /* In this case, finish_task_switch does not reenable preemption */
2867 preempt_enable();
2868 #endif
2869 if (current->set_child_tid)
2870 put_user(task_pid_vnr(current), current->set_child_tid);
2874 * context_switch - switch to the new MM and the new
2875 * thread's register state.
2877 static inline void
2878 context_switch(struct rq *rq, struct task_struct *prev,
2879 struct task_struct *next)
2881 struct mm_struct *mm, *oldmm;
2883 prepare_task_switch(rq, prev, next);
2884 trace_sched_switch(rq, prev, next);
2885 mm = next->mm;
2886 oldmm = prev->active_mm;
2888 * For paravirt, this is coupled with an exit in switch_to to
2889 * combine the page table reload and the switch backend into
2890 * one hypercall.
2892 arch_start_context_switch(prev);
2894 if (likely(!mm)) {
2895 next->active_mm = oldmm;
2896 atomic_inc(&oldmm->mm_count);
2897 enter_lazy_tlb(oldmm, next);
2898 } else
2899 switch_mm(oldmm, mm, next);
2901 if (likely(!prev->mm)) {
2902 prev->active_mm = NULL;
2903 rq->prev_mm = oldmm;
2906 * Since the runqueue lock will be released by the next
2907 * task (which is an invalid locking op but in the case
2908 * of the scheduler it's an obvious special-case), so we
2909 * do an early lockdep release here:
2911 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2912 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2913 #endif
2915 /* Here we just switch the register state and the stack. */
2916 switch_to(prev, next, prev);
2918 barrier();
2920 * this_rq must be evaluated again because prev may have moved
2921 * CPUs since it called schedule(), thus the 'rq' on its stack
2922 * frame will be invalid.
2924 finish_task_switch(this_rq(), prev);
2928 * nr_running, nr_uninterruptible and nr_context_switches:
2930 * externally visible scheduler statistics: current number of runnable
2931 * threads, current number of uninterruptible-sleeping threads, total
2932 * number of context switches performed since bootup.
2934 unsigned long nr_running(void)
2936 unsigned long i, sum = 0;
2938 for_each_online_cpu(i)
2939 sum += cpu_rq(i)->nr_running;
2941 return sum;
2944 unsigned long nr_uninterruptible(void)
2946 unsigned long i, sum = 0;
2948 for_each_possible_cpu(i)
2949 sum += cpu_rq(i)->nr_uninterruptible;
2952 * Since we read the counters lockless, it might be slightly
2953 * inaccurate. Do not allow it to go below zero though:
2955 if (unlikely((long)sum < 0))
2956 sum = 0;
2958 return sum;
2961 unsigned long long nr_context_switches(void)
2963 int i;
2964 unsigned long long sum = 0;
2966 for_each_possible_cpu(i)
2967 sum += cpu_rq(i)->nr_switches;
2969 return sum;
2972 unsigned long nr_iowait(void)
2974 unsigned long i, sum = 0;
2976 for_each_possible_cpu(i)
2977 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2979 return sum;
2982 unsigned long nr_iowait_cpu(void)
2984 struct rq *this = this_rq();
2985 return atomic_read(&this->nr_iowait);
2988 unsigned long this_cpu_load(void)
2990 struct rq *this = this_rq();
2991 return this->cpu_load[0];
2995 /* Variables and functions for calc_load */
2996 static atomic_long_t calc_load_tasks;
2997 static unsigned long calc_load_update;
2998 unsigned long avenrun[3];
2999 EXPORT_SYMBOL(avenrun);
3002 * get_avenrun - get the load average array
3003 * @loads: pointer to dest load array
3004 * @offset: offset to add
3005 * @shift: shift count to shift the result left
3007 * These values are estimates at best, so no need for locking.
3009 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3011 loads[0] = (avenrun[0] + offset) << shift;
3012 loads[1] = (avenrun[1] + offset) << shift;
3013 loads[2] = (avenrun[2] + offset) << shift;
3016 static unsigned long
3017 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3019 load *= exp;
3020 load += active * (FIXED_1 - exp);
3021 return load >> FSHIFT;
3025 * calc_load - update the avenrun load estimates 10 ticks after the
3026 * CPUs have updated calc_load_tasks.
3028 void calc_global_load(void)
3030 unsigned long upd = calc_load_update + 10;
3031 long active;
3033 if (time_before(jiffies, upd))
3034 return;
3036 active = atomic_long_read(&calc_load_tasks);
3037 active = active > 0 ? active * FIXED_1 : 0;
3039 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3040 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3041 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3043 calc_load_update += LOAD_FREQ;
3047 * Either called from update_cpu_load() or from a cpu going idle
3049 static void calc_load_account_active(struct rq *this_rq)
3051 long nr_active, delta;
3053 nr_active = this_rq->nr_running;
3054 nr_active += (long) this_rq->nr_uninterruptible;
3056 if (nr_active != this_rq->calc_load_active) {
3057 delta = nr_active - this_rq->calc_load_active;
3058 this_rq->calc_load_active = nr_active;
3059 atomic_long_add(delta, &calc_load_tasks);
3064 * Update rq->cpu_load[] statistics. This function is usually called every
3065 * scheduler tick (TICK_NSEC).
3067 static void update_cpu_load(struct rq *this_rq)
3069 unsigned long this_load = this_rq->load.weight;
3070 int i, scale;
3072 this_rq->nr_load_updates++;
3074 /* Update our load: */
3075 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3076 unsigned long old_load, new_load;
3078 /* scale is effectively 1 << i now, and >> i divides by scale */
3080 old_load = this_rq->cpu_load[i];
3081 new_load = this_load;
3083 * Round up the averaging division if load is increasing. This
3084 * prevents us from getting stuck on 9 if the load is 10, for
3085 * example.
3087 if (new_load > old_load)
3088 new_load += scale-1;
3089 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3092 if (time_after_eq(jiffies, this_rq->calc_load_update)) {
3093 this_rq->calc_load_update += LOAD_FREQ;
3094 calc_load_account_active(this_rq);
3097 sched_avg_update(this_rq);
3100 #ifdef CONFIG_SMP
3103 * sched_exec - execve() is a valuable balancing opportunity, because at
3104 * this point the task has the smallest effective memory and cache footprint.
3106 void sched_exec(void)
3108 struct task_struct *p = current;
3109 struct migration_req req;
3110 unsigned long flags;
3111 struct rq *rq;
3112 int dest_cpu;
3114 rq = task_rq_lock(p, &flags);
3115 dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
3116 if (dest_cpu == smp_processor_id())
3117 goto unlock;
3120 * select_task_rq() can race against ->cpus_allowed
3122 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
3123 likely(cpu_active(dest_cpu)) &&
3124 migrate_task(p, dest_cpu, &req)) {
3125 /* Need to wait for migration thread (might exit: take ref). */
3126 struct task_struct *mt = rq->migration_thread;
3128 get_task_struct(mt);
3129 task_rq_unlock(rq, &flags);
3130 wake_up_process(mt);
3131 put_task_struct(mt);
3132 wait_for_completion(&req.done);
3134 return;
3136 unlock:
3137 task_rq_unlock(rq, &flags);
3140 #endif
3142 DEFINE_PER_CPU(struct kernel_stat, kstat);
3144 EXPORT_PER_CPU_SYMBOL(kstat);
3147 * Return any ns on the sched_clock that have not yet been accounted in
3148 * @p in case that task is currently running.
3150 * Called with task_rq_lock() held on @rq.
3152 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3154 u64 ns = 0;
3156 if (task_current(rq, p)) {
3157 update_rq_clock(rq);
3158 ns = rq->clock - p->se.exec_start;
3159 if ((s64)ns < 0)
3160 ns = 0;
3163 return ns;
3166 unsigned long long task_delta_exec(struct task_struct *p)
3168 unsigned long flags;
3169 struct rq *rq;
3170 u64 ns = 0;
3172 rq = task_rq_lock(p, &flags);
3173 ns = do_task_delta_exec(p, rq);
3174 task_rq_unlock(rq, &flags);
3176 return ns;
3180 * Return accounted runtime for the task.
3181 * In case the task is currently running, return the runtime plus current's
3182 * pending runtime that have not been accounted yet.
3184 unsigned long long task_sched_runtime(struct task_struct *p)
3186 unsigned long flags;
3187 struct rq *rq;
3188 u64 ns = 0;
3190 rq = task_rq_lock(p, &flags);
3191 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3192 task_rq_unlock(rq, &flags);
3194 return ns;
3198 * Return sum_exec_runtime for the thread group.
3199 * In case the task is currently running, return the sum plus current's
3200 * pending runtime that have not been accounted yet.
3202 * Note that the thread group might have other running tasks as well,
3203 * so the return value not includes other pending runtime that other
3204 * running tasks might have.
3206 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3208 struct task_cputime totals;
3209 unsigned long flags;
3210 struct rq *rq;
3211 u64 ns;
3213 rq = task_rq_lock(p, &flags);
3214 thread_group_cputime(p, &totals);
3215 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3216 task_rq_unlock(rq, &flags);
3218 return ns;
3222 * Account user cpu time to a process.
3223 * @p: the process that the cpu time gets accounted to
3224 * @cputime: the cpu time spent in user space since the last update
3225 * @cputime_scaled: cputime scaled by cpu frequency
3227 void account_user_time(struct task_struct *p, cputime_t cputime,
3228 cputime_t cputime_scaled)
3230 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3231 cputime64_t tmp;
3233 /* Add user time to process. */
3234 p->utime = cputime_add(p->utime, cputime);
3235 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3236 account_group_user_time(p, cputime);
3238 /* Add user time to cpustat. */
3239 tmp = cputime_to_cputime64(cputime);
3240 if (TASK_NICE(p) > 0)
3241 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3242 else
3243 cpustat->user = cputime64_add(cpustat->user, tmp);
3245 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3246 /* Account for user time used */
3247 acct_update_integrals(p);
3251 * Account guest cpu time to a process.
3252 * @p: the process that the cpu time gets accounted to
3253 * @cputime: the cpu time spent in virtual machine since the last update
3254 * @cputime_scaled: cputime scaled by cpu frequency
3256 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3257 cputime_t cputime_scaled)
3259 cputime64_t tmp;
3260 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3262 tmp = cputime_to_cputime64(cputime);
3264 /* Add guest time to process. */
3265 p->utime = cputime_add(p->utime, cputime);
3266 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3267 account_group_user_time(p, cputime);
3268 p->gtime = cputime_add(p->gtime, cputime);
3270 /* Add guest time to cpustat. */
3271 if (TASK_NICE(p) > 0) {
3272 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3273 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3274 } else {
3275 cpustat->user = cputime64_add(cpustat->user, tmp);
3276 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3281 * Account system cpu time to a process.
3282 * @p: the process that the cpu time gets accounted to
3283 * @hardirq_offset: the offset to subtract from hardirq_count()
3284 * @cputime: the cpu time spent in kernel space since the last update
3285 * @cputime_scaled: cputime scaled by cpu frequency
3287 void account_system_time(struct task_struct *p, int hardirq_offset,
3288 cputime_t cputime, cputime_t cputime_scaled)
3290 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3291 cputime64_t tmp;
3293 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3294 account_guest_time(p, cputime, cputime_scaled);
3295 return;
3298 /* Add system time to process. */
3299 p->stime = cputime_add(p->stime, cputime);
3300 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3301 account_group_system_time(p, cputime);
3303 /* Add system time to cpustat. */
3304 tmp = cputime_to_cputime64(cputime);
3305 if (hardirq_count() - hardirq_offset)
3306 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3307 else if (softirq_count())
3308 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3309 else
3310 cpustat->system = cputime64_add(cpustat->system, tmp);
3312 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3314 /* Account for system time used */
3315 acct_update_integrals(p);
3319 * Account for involuntary wait time.
3320 * @steal: the cpu time spent in involuntary wait
3322 void account_steal_time(cputime_t cputime)
3324 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3325 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3327 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3331 * Account for idle time.
3332 * @cputime: the cpu time spent in idle wait
3334 void account_idle_time(cputime_t cputime)
3336 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3337 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3338 struct rq *rq = this_rq();
3340 if (atomic_read(&rq->nr_iowait) > 0)
3341 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3342 else
3343 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3346 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3349 * Account a single tick of cpu time.
3350 * @p: the process that the cpu time gets accounted to
3351 * @user_tick: indicates if the tick is a user or a system tick
3353 void account_process_tick(struct task_struct *p, int user_tick)
3355 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3356 struct rq *rq = this_rq();
3358 if (user_tick)
3359 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3360 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3361 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3362 one_jiffy_scaled);
3363 else
3364 account_idle_time(cputime_one_jiffy);
3368 * Account multiple ticks of steal time.
3369 * @p: the process from which the cpu time has been stolen
3370 * @ticks: number of stolen ticks
3372 void account_steal_ticks(unsigned long ticks)
3374 account_steal_time(jiffies_to_cputime(ticks));
3378 * Account multiple ticks of idle time.
3379 * @ticks: number of stolen ticks
3381 void account_idle_ticks(unsigned long ticks)
3383 account_idle_time(jiffies_to_cputime(ticks));
3386 #endif
3389 * Use precise platform statistics if available:
3391 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
3392 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3394 *ut = p->utime;
3395 *st = p->stime;
3398 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3400 struct task_cputime cputime;
3402 thread_group_cputime(p, &cputime);
3404 *ut = cputime.utime;
3405 *st = cputime.stime;
3407 #else
3409 #ifndef nsecs_to_cputime
3410 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
3411 #endif
3413 static cputime_t scale_utime(cputime_t utime, cputime_t rtime, cputime_t total)
3415 u64 temp = (__force u64) rtime;
3417 temp *= (__force u64) utime;
3419 if (sizeof(cputime_t) == 4)
3420 temp = div_u64(temp, (__force u32) total);
3421 else
3422 temp = div64_u64(temp, (__force u64) total);
3424 return (__force cputime_t) temp;
3427 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3429 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
3432 * Use CFS's precise accounting:
3434 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
3436 if (total)
3437 utime = scale_utime(utime, rtime, total);
3438 else
3439 utime = rtime;
3442 * Compare with previous values, to keep monotonicity:
3444 p->prev_utime = max(p->prev_utime, utime);
3445 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
3447 *ut = p->prev_utime;
3448 *st = p->prev_stime;
3452 * Must be called with siglock held.
3454 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3456 struct signal_struct *sig = p->signal;
3457 struct task_cputime cputime;
3458 cputime_t rtime, utime, total;
3460 thread_group_cputime(p, &cputime);
3462 total = cputime_add(cputime.utime, cputime.stime);
3463 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
3465 if (total)
3466 utime = scale_utime(cputime.utime, rtime, total);
3467 else
3468 utime = rtime;
3470 sig->prev_utime = max(sig->prev_utime, utime);
3471 sig->prev_stime = max(sig->prev_stime,
3472 cputime_sub(rtime, sig->prev_utime));
3474 *ut = sig->prev_utime;
3475 *st = sig->prev_stime;
3477 #endif
3480 * This function gets called by the timer code, with HZ frequency.
3481 * We call it with interrupts disabled.
3483 * It also gets called by the fork code, when changing the parent's
3484 * timeslices.
3486 void scheduler_tick(void)
3488 int cpu = smp_processor_id();
3489 struct rq *rq = cpu_rq(cpu);
3490 struct task_struct *curr = rq->curr;
3492 sched_clock_tick();
3494 raw_spin_lock(&rq->lock);
3495 update_rq_clock(rq);
3496 update_cpu_load(rq);
3497 curr->sched_class->task_tick(rq, curr, 0);
3498 raw_spin_unlock(&rq->lock);
3500 perf_event_task_tick(curr);
3502 #ifdef CONFIG_SMP
3503 rq->idle_at_tick = idle_cpu(cpu);
3504 trigger_load_balance(rq, cpu);
3505 #endif
3508 notrace unsigned long get_parent_ip(unsigned long addr)
3510 if (in_lock_functions(addr)) {
3511 addr = CALLER_ADDR2;
3512 if (in_lock_functions(addr))
3513 addr = CALLER_ADDR3;
3515 return addr;
3518 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3519 defined(CONFIG_PREEMPT_TRACER))
3521 void __kprobes add_preempt_count(int val)
3523 #ifdef CONFIG_DEBUG_PREEMPT
3525 * Underflow?
3527 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3528 return;
3529 #endif
3530 preempt_count() += val;
3531 #ifdef CONFIG_DEBUG_PREEMPT
3533 * Spinlock count overflowing soon?
3535 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3536 PREEMPT_MASK - 10);
3537 #endif
3538 if (preempt_count() == val)
3539 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3541 EXPORT_SYMBOL(add_preempt_count);
3543 void __kprobes sub_preempt_count(int val)
3545 #ifdef CONFIG_DEBUG_PREEMPT
3547 * Underflow?
3549 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3550 return;
3552 * Is the spinlock portion underflowing?
3554 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3555 !(preempt_count() & PREEMPT_MASK)))
3556 return;
3557 #endif
3559 if (preempt_count() == val)
3560 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3561 preempt_count() -= val;
3563 EXPORT_SYMBOL(sub_preempt_count);
3565 #endif
3568 * Print scheduling while atomic bug:
3570 static noinline void __schedule_bug(struct task_struct *prev)
3572 struct pt_regs *regs = get_irq_regs();
3574 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3575 prev->comm, prev->pid, preempt_count());
3577 debug_show_held_locks(prev);
3578 print_modules();
3579 if (irqs_disabled())
3580 print_irqtrace_events(prev);
3582 if (regs)
3583 show_regs(regs);
3584 else
3585 dump_stack();
3589 * Various schedule()-time debugging checks and statistics:
3591 static inline void schedule_debug(struct task_struct *prev)
3594 * Test if we are atomic. Since do_exit() needs to call into
3595 * schedule() atomically, we ignore that path for now.
3596 * Otherwise, whine if we are scheduling when we should not be.
3598 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
3599 __schedule_bug(prev);
3601 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3603 schedstat_inc(this_rq(), sched_count);
3604 #ifdef CONFIG_SCHEDSTATS
3605 if (unlikely(prev->lock_depth >= 0)) {
3606 schedstat_inc(this_rq(), bkl_count);
3607 schedstat_inc(prev, sched_info.bkl_count);
3609 #endif
3612 static void put_prev_task(struct rq *rq, struct task_struct *prev)
3614 if (prev->state == TASK_RUNNING) {
3615 u64 runtime = prev->se.sum_exec_runtime;
3617 runtime -= prev->se.prev_sum_exec_runtime;
3618 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
3621 * In order to avoid avg_overlap growing stale when we are
3622 * indeed overlapping and hence not getting put to sleep, grow
3623 * the avg_overlap on preemption.
3625 * We use the average preemption runtime because that
3626 * correlates to the amount of cache footprint a task can
3627 * build up.
3629 update_avg(&prev->se.avg_overlap, runtime);
3631 prev->sched_class->put_prev_task(rq, prev);
3635 * Pick up the highest-prio task:
3637 static inline struct task_struct *
3638 pick_next_task(struct rq *rq)
3640 const struct sched_class *class;
3641 struct task_struct *p;
3644 * Optimization: we know that if all tasks are in
3645 * the fair class we can call that function directly:
3647 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3648 p = fair_sched_class.pick_next_task(rq);
3649 if (likely(p))
3650 return p;
3653 class = sched_class_highest;
3654 for ( ; ; ) {
3655 p = class->pick_next_task(rq);
3656 if (p)
3657 return p;
3659 * Will never be NULL as the idle class always
3660 * returns a non-NULL p:
3662 class = class->next;
3667 * schedule() is the main scheduler function.
3669 asmlinkage void __sched schedule(void)
3671 struct task_struct *prev, *next;
3672 unsigned long *switch_count;
3673 struct rq *rq;
3674 int cpu;
3676 need_resched:
3677 preempt_disable();
3678 cpu = smp_processor_id();
3679 rq = cpu_rq(cpu);
3680 rcu_sched_qs(cpu);
3681 prev = rq->curr;
3682 switch_count = &prev->nivcsw;
3684 release_kernel_lock(prev);
3685 need_resched_nonpreemptible:
3687 schedule_debug(prev);
3689 if (sched_feat(HRTICK))
3690 hrtick_clear(rq);
3692 raw_spin_lock_irq(&rq->lock);
3693 update_rq_clock(rq);
3694 clear_tsk_need_resched(prev);
3696 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3697 if (unlikely(signal_pending_state(prev->state, prev)))
3698 prev->state = TASK_RUNNING;
3699 else
3700 deactivate_task(rq, prev, 1);
3701 switch_count = &prev->nvcsw;
3704 pre_schedule(rq, prev);
3706 if (unlikely(!rq->nr_running))
3707 idle_balance(cpu, rq);
3709 put_prev_task(rq, prev);
3710 next = pick_next_task(rq);
3712 if (likely(prev != next)) {
3713 sched_info_switch(prev, next);
3714 perf_event_task_sched_out(prev, next);
3716 rq->nr_switches++;
3717 rq->curr = next;
3718 ++*switch_count;
3720 context_switch(rq, prev, next); /* unlocks the rq */
3722 * the context switch might have flipped the stack from under
3723 * us, hence refresh the local variables.
3725 cpu = smp_processor_id();
3726 rq = cpu_rq(cpu);
3727 } else
3728 raw_spin_unlock_irq(&rq->lock);
3730 post_schedule(rq);
3732 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3733 prev = rq->curr;
3734 switch_count = &prev->nivcsw;
3735 goto need_resched_nonpreemptible;
3738 preempt_enable_no_resched();
3739 if (need_resched())
3740 goto need_resched;
3742 EXPORT_SYMBOL(schedule);
3744 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
3746 * Look out! "owner" is an entirely speculative pointer
3747 * access and not reliable.
3749 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
3751 unsigned int cpu;
3752 struct rq *rq;
3754 if (!sched_feat(OWNER_SPIN))
3755 return 0;
3757 #ifdef CONFIG_DEBUG_PAGEALLOC
3759 * Need to access the cpu field knowing that
3760 * DEBUG_PAGEALLOC could have unmapped it if
3761 * the mutex owner just released it and exited.
3763 if (probe_kernel_address(&owner->cpu, cpu))
3764 return 0;
3765 #else
3766 cpu = owner->cpu;
3767 #endif
3770 * Even if the access succeeded (likely case),
3771 * the cpu field may no longer be valid.
3773 if (cpu >= nr_cpumask_bits)
3774 return 0;
3777 * We need to validate that we can do a
3778 * get_cpu() and that we have the percpu area.
3780 if (!cpu_online(cpu))
3781 return 0;
3783 rq = cpu_rq(cpu);
3785 for (;;) {
3787 * Owner changed, break to re-assess state.
3789 if (lock->owner != owner)
3790 break;
3793 * Is that owner really running on that cpu?
3795 if (task_thread_info(rq->curr) != owner || need_resched())
3796 return 0;
3798 cpu_relax();
3801 return 1;
3803 #endif
3805 #ifdef CONFIG_PREEMPT
3807 * this is the entry point to schedule() from in-kernel preemption
3808 * off of preempt_enable. Kernel preemptions off return from interrupt
3809 * occur there and call schedule directly.
3811 asmlinkage void __sched preempt_schedule(void)
3813 struct thread_info *ti = current_thread_info();
3816 * If there is a non-zero preempt_count or interrupts are disabled,
3817 * we do not want to preempt the current task. Just return..
3819 if (likely(ti->preempt_count || irqs_disabled()))
3820 return;
3822 do {
3823 add_preempt_count(PREEMPT_ACTIVE);
3824 schedule();
3825 sub_preempt_count(PREEMPT_ACTIVE);
3828 * Check again in case we missed a preemption opportunity
3829 * between schedule and now.
3831 barrier();
3832 } while (need_resched());
3834 EXPORT_SYMBOL(preempt_schedule);
3837 * this is the entry point to schedule() from kernel preemption
3838 * off of irq context.
3839 * Note, that this is called and return with irqs disabled. This will
3840 * protect us against recursive calling from irq.
3842 asmlinkage void __sched preempt_schedule_irq(void)
3844 struct thread_info *ti = current_thread_info();
3846 /* Catch callers which need to be fixed */
3847 BUG_ON(ti->preempt_count || !irqs_disabled());
3849 do {
3850 add_preempt_count(PREEMPT_ACTIVE);
3851 local_irq_enable();
3852 schedule();
3853 local_irq_disable();
3854 sub_preempt_count(PREEMPT_ACTIVE);
3857 * Check again in case we missed a preemption opportunity
3858 * between schedule and now.
3860 barrier();
3861 } while (need_resched());
3864 #endif /* CONFIG_PREEMPT */
3866 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3867 void *key)
3869 return try_to_wake_up(curr->private, mode, wake_flags);
3871 EXPORT_SYMBOL(default_wake_function);
3874 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3875 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3876 * number) then we wake all the non-exclusive tasks and one exclusive task.
3878 * There are circumstances in which we can try to wake a task which has already
3879 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3880 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3882 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3883 int nr_exclusive, int wake_flags, void *key)
3885 wait_queue_t *curr, *next;
3887 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3888 unsigned flags = curr->flags;
3890 if (curr->func(curr, mode, wake_flags, key) &&
3891 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3892 break;
3897 * __wake_up - wake up threads blocked on a waitqueue.
3898 * @q: the waitqueue
3899 * @mode: which threads
3900 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3901 * @key: is directly passed to the wakeup function
3903 * It may be assumed that this function implies a write memory barrier before
3904 * changing the task state if and only if any tasks are woken up.
3906 void __wake_up(wait_queue_head_t *q, unsigned int mode,
3907 int nr_exclusive, void *key)
3909 unsigned long flags;
3911 spin_lock_irqsave(&q->lock, flags);
3912 __wake_up_common(q, mode, nr_exclusive, 0, key);
3913 spin_unlock_irqrestore(&q->lock, flags);
3915 EXPORT_SYMBOL(__wake_up);
3918 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3920 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3922 __wake_up_common(q, mode, 1, 0, NULL);
3925 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
3927 __wake_up_common(q, mode, 1, 0, key);
3931 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
3932 * @q: the waitqueue
3933 * @mode: which threads
3934 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3935 * @key: opaque value to be passed to wakeup targets
3937 * The sync wakeup differs that the waker knows that it will schedule
3938 * away soon, so while the target thread will be woken up, it will not
3939 * be migrated to another CPU - ie. the two threads are 'synchronized'
3940 * with each other. This can prevent needless bouncing between CPUs.
3942 * On UP it can prevent extra preemption.
3944 * It may be assumed that this function implies a write memory barrier before
3945 * changing the task state if and only if any tasks are woken up.
3947 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
3948 int nr_exclusive, void *key)
3950 unsigned long flags;
3951 int wake_flags = WF_SYNC;
3953 if (unlikely(!q))
3954 return;
3956 if (unlikely(!nr_exclusive))
3957 wake_flags = 0;
3959 spin_lock_irqsave(&q->lock, flags);
3960 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
3961 spin_unlock_irqrestore(&q->lock, flags);
3963 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
3966 * __wake_up_sync - see __wake_up_sync_key()
3968 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3970 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
3972 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3975 * complete: - signals a single thread waiting on this completion
3976 * @x: holds the state of this particular completion
3978 * This will wake up a single thread waiting on this completion. Threads will be
3979 * awakened in the same order in which they were queued.
3981 * See also complete_all(), wait_for_completion() and related routines.
3983 * It may be assumed that this function implies a write memory barrier before
3984 * changing the task state if and only if any tasks are woken up.
3986 void complete(struct completion *x)
3988 unsigned long flags;
3990 spin_lock_irqsave(&x->wait.lock, flags);
3991 x->done++;
3992 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
3993 spin_unlock_irqrestore(&x->wait.lock, flags);
3995 EXPORT_SYMBOL(complete);
3998 * complete_all: - signals all threads waiting on this completion
3999 * @x: holds the state of this particular completion
4001 * This will wake up all threads waiting on this particular completion event.
4003 * It may be assumed that this function implies a write memory barrier before
4004 * changing the task state if and only if any tasks are woken up.
4006 void complete_all(struct completion *x)
4008 unsigned long flags;
4010 spin_lock_irqsave(&x->wait.lock, flags);
4011 x->done += UINT_MAX/2;
4012 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4013 spin_unlock_irqrestore(&x->wait.lock, flags);
4015 EXPORT_SYMBOL(complete_all);
4017 static inline long __sched
4018 do_wait_for_common(struct completion *x, long timeout, int state)
4020 if (!x->done) {
4021 DECLARE_WAITQUEUE(wait, current);
4023 wait.flags |= WQ_FLAG_EXCLUSIVE;
4024 __add_wait_queue_tail(&x->wait, &wait);
4025 do {
4026 if (signal_pending_state(state, current)) {
4027 timeout = -ERESTARTSYS;
4028 break;
4030 __set_current_state(state);
4031 spin_unlock_irq(&x->wait.lock);
4032 timeout = schedule_timeout(timeout);
4033 spin_lock_irq(&x->wait.lock);
4034 } while (!x->done && timeout);
4035 __remove_wait_queue(&x->wait, &wait);
4036 if (!x->done)
4037 return timeout;
4039 x->done--;
4040 return timeout ?: 1;
4043 static long __sched
4044 wait_for_common(struct completion *x, long timeout, int state)
4046 might_sleep();
4048 spin_lock_irq(&x->wait.lock);
4049 timeout = do_wait_for_common(x, timeout, state);
4050 spin_unlock_irq(&x->wait.lock);
4051 return timeout;
4055 * wait_for_completion: - waits for completion of a task
4056 * @x: holds the state of this particular completion
4058 * This waits to be signaled for completion of a specific task. It is NOT
4059 * interruptible and there is no timeout.
4061 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4062 * and interrupt capability. Also see complete().
4064 void __sched wait_for_completion(struct completion *x)
4066 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4068 EXPORT_SYMBOL(wait_for_completion);
4071 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4072 * @x: holds the state of this particular completion
4073 * @timeout: timeout value in jiffies
4075 * This waits for either a completion of a specific task to be signaled or for a
4076 * specified timeout to expire. The timeout is in jiffies. It is not
4077 * interruptible.
4079 unsigned long __sched
4080 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4082 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4084 EXPORT_SYMBOL(wait_for_completion_timeout);
4087 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4088 * @x: holds the state of this particular completion
4090 * This waits for completion of a specific task to be signaled. It is
4091 * interruptible.
4093 int __sched wait_for_completion_interruptible(struct completion *x)
4095 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4096 if (t == -ERESTARTSYS)
4097 return t;
4098 return 0;
4100 EXPORT_SYMBOL(wait_for_completion_interruptible);
4103 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4104 * @x: holds the state of this particular completion
4105 * @timeout: timeout value in jiffies
4107 * This waits for either a completion of a specific task to be signaled or for a
4108 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4110 unsigned long __sched
4111 wait_for_completion_interruptible_timeout(struct completion *x,
4112 unsigned long timeout)
4114 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4116 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4119 * wait_for_completion_killable: - waits for completion of a task (killable)
4120 * @x: holds the state of this particular completion
4122 * This waits to be signaled for completion of a specific task. It can be
4123 * interrupted by a kill signal.
4125 int __sched wait_for_completion_killable(struct completion *x)
4127 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4128 if (t == -ERESTARTSYS)
4129 return t;
4130 return 0;
4132 EXPORT_SYMBOL(wait_for_completion_killable);
4135 * try_wait_for_completion - try to decrement a completion without blocking
4136 * @x: completion structure
4138 * Returns: 0 if a decrement cannot be done without blocking
4139 * 1 if a decrement succeeded.
4141 * If a completion is being used as a counting completion,
4142 * attempt to decrement the counter without blocking. This
4143 * enables us to avoid waiting if the resource the completion
4144 * is protecting is not available.
4146 bool try_wait_for_completion(struct completion *x)
4148 unsigned long flags;
4149 int ret = 1;
4151 spin_lock_irqsave(&x->wait.lock, flags);
4152 if (!x->done)
4153 ret = 0;
4154 else
4155 x->done--;
4156 spin_unlock_irqrestore(&x->wait.lock, flags);
4157 return ret;
4159 EXPORT_SYMBOL(try_wait_for_completion);
4162 * completion_done - Test to see if a completion has any waiters
4163 * @x: completion structure
4165 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4166 * 1 if there are no waiters.
4169 bool completion_done(struct completion *x)
4171 unsigned long flags;
4172 int ret = 1;
4174 spin_lock_irqsave(&x->wait.lock, flags);
4175 if (!x->done)
4176 ret = 0;
4177 spin_unlock_irqrestore(&x->wait.lock, flags);
4178 return ret;
4180 EXPORT_SYMBOL(completion_done);
4182 static long __sched
4183 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4185 unsigned long flags;
4186 wait_queue_t wait;
4188 init_waitqueue_entry(&wait, current);
4190 __set_current_state(state);
4192 spin_lock_irqsave(&q->lock, flags);
4193 __add_wait_queue(q, &wait);
4194 spin_unlock(&q->lock);
4195 timeout = schedule_timeout(timeout);
4196 spin_lock_irq(&q->lock);
4197 __remove_wait_queue(q, &wait);
4198 spin_unlock_irqrestore(&q->lock, flags);
4200 return timeout;
4203 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4205 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4207 EXPORT_SYMBOL(interruptible_sleep_on);
4209 long __sched
4210 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4212 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4214 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4216 void __sched sleep_on(wait_queue_head_t *q)
4218 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4220 EXPORT_SYMBOL(sleep_on);
4222 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4224 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4226 EXPORT_SYMBOL(sleep_on_timeout);
4228 #ifdef CONFIG_RT_MUTEXES
4231 * rt_mutex_setprio - set the current priority of a task
4232 * @p: task
4233 * @prio: prio value (kernel-internal form)
4235 * This function changes the 'effective' priority of a task. It does
4236 * not touch ->normal_prio like __setscheduler().
4238 * Used by the rt_mutex code to implement priority inheritance logic.
4240 void rt_mutex_setprio(struct task_struct *p, int prio)
4242 unsigned long flags;
4243 int oldprio, on_rq, running;
4244 struct rq *rq;
4245 const struct sched_class *prev_class;
4247 BUG_ON(prio < 0 || prio > MAX_PRIO);
4249 rq = task_rq_lock(p, &flags);
4250 update_rq_clock(rq);
4252 oldprio = p->prio;
4253 prev_class = p->sched_class;
4254 on_rq = p->se.on_rq;
4255 running = task_current(rq, p);
4256 if (on_rq)
4257 dequeue_task(rq, p, 0);
4258 if (running)
4259 p->sched_class->put_prev_task(rq, p);
4261 if (rt_prio(prio))
4262 p->sched_class = &rt_sched_class;
4263 else
4264 p->sched_class = &fair_sched_class;
4266 p->prio = prio;
4268 if (running)
4269 p->sched_class->set_curr_task(rq);
4270 if (on_rq) {
4271 enqueue_task(rq, p, 0, oldprio < prio);
4273 check_class_changed(rq, p, prev_class, oldprio, running);
4275 task_rq_unlock(rq, &flags);
4278 #endif
4280 void set_user_nice(struct task_struct *p, long nice)
4282 int old_prio, delta, on_rq;
4283 unsigned long flags;
4284 struct rq *rq;
4286 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4287 return;
4289 * We have to be careful, if called from sys_setpriority(),
4290 * the task might be in the middle of scheduling on another CPU.
4292 rq = task_rq_lock(p, &flags);
4293 update_rq_clock(rq);
4295 * The RT priorities are set via sched_setscheduler(), but we still
4296 * allow the 'normal' nice value to be set - but as expected
4297 * it wont have any effect on scheduling until the task is
4298 * SCHED_FIFO/SCHED_RR:
4300 if (task_has_rt_policy(p)) {
4301 p->static_prio = NICE_TO_PRIO(nice);
4302 goto out_unlock;
4304 on_rq = p->se.on_rq;
4305 if (on_rq)
4306 dequeue_task(rq, p, 0);
4308 p->static_prio = NICE_TO_PRIO(nice);
4309 set_load_weight(p);
4310 old_prio = p->prio;
4311 p->prio = effective_prio(p);
4312 delta = p->prio - old_prio;
4314 if (on_rq) {
4315 enqueue_task(rq, p, 0, false);
4317 * If the task increased its priority or is running and
4318 * lowered its priority, then reschedule its CPU:
4320 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4321 resched_task(rq->curr);
4323 out_unlock:
4324 task_rq_unlock(rq, &flags);
4326 EXPORT_SYMBOL(set_user_nice);
4329 * can_nice - check if a task can reduce its nice value
4330 * @p: task
4331 * @nice: nice value
4333 int can_nice(const struct task_struct *p, const int nice)
4335 /* convert nice value [19,-20] to rlimit style value [1,40] */
4336 int nice_rlim = 20 - nice;
4338 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4339 capable(CAP_SYS_NICE));
4342 #ifdef __ARCH_WANT_SYS_NICE
4345 * sys_nice - change the priority of the current process.
4346 * @increment: priority increment
4348 * sys_setpriority is a more generic, but much slower function that
4349 * does similar things.
4351 SYSCALL_DEFINE1(nice, int, increment)
4353 long nice, retval;
4356 * Setpriority might change our priority at the same moment.
4357 * We don't have to worry. Conceptually one call occurs first
4358 * and we have a single winner.
4360 if (increment < -40)
4361 increment = -40;
4362 if (increment > 40)
4363 increment = 40;
4365 nice = TASK_NICE(current) + increment;
4366 if (nice < -20)
4367 nice = -20;
4368 if (nice > 19)
4369 nice = 19;
4371 if (increment < 0 && !can_nice(current, nice))
4372 return -EPERM;
4374 retval = security_task_setnice(current, nice);
4375 if (retval)
4376 return retval;
4378 set_user_nice(current, nice);
4379 return 0;
4382 #endif
4385 * task_prio - return the priority value of a given task.
4386 * @p: the task in question.
4388 * This is the priority value as seen by users in /proc.
4389 * RT tasks are offset by -200. Normal tasks are centered
4390 * around 0, value goes from -16 to +15.
4392 int task_prio(const struct task_struct *p)
4394 return p->prio - MAX_RT_PRIO;
4398 * task_nice - return the nice value of a given task.
4399 * @p: the task in question.
4401 int task_nice(const struct task_struct *p)
4403 return TASK_NICE(p);
4405 EXPORT_SYMBOL(task_nice);
4408 * idle_cpu - is a given cpu idle currently?
4409 * @cpu: the processor in question.
4411 int idle_cpu(int cpu)
4413 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4417 * idle_task - return the idle task for a given cpu.
4418 * @cpu: the processor in question.
4420 struct task_struct *idle_task(int cpu)
4422 return cpu_rq(cpu)->idle;
4426 * find_process_by_pid - find a process with a matching PID value.
4427 * @pid: the pid in question.
4429 static struct task_struct *find_process_by_pid(pid_t pid)
4431 return pid ? find_task_by_vpid(pid) : current;
4434 /* Actually do priority change: must hold rq lock. */
4435 static void
4436 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4438 BUG_ON(p->se.on_rq);
4440 p->policy = policy;
4441 p->rt_priority = prio;
4442 p->normal_prio = normal_prio(p);
4443 /* we are holding p->pi_lock already */
4444 p->prio = rt_mutex_getprio(p);
4445 if (rt_prio(p->prio))
4446 p->sched_class = &rt_sched_class;
4447 else
4448 p->sched_class = &fair_sched_class;
4449 set_load_weight(p);
4453 * check the target process has a UID that matches the current process's
4455 static bool check_same_owner(struct task_struct *p)
4457 const struct cred *cred = current_cred(), *pcred;
4458 bool match;
4460 rcu_read_lock();
4461 pcred = __task_cred(p);
4462 match = (cred->euid == pcred->euid ||
4463 cred->euid == pcred->uid);
4464 rcu_read_unlock();
4465 return match;
4468 static int __sched_setscheduler(struct task_struct *p, int policy,
4469 struct sched_param *param, bool user)
4471 int retval, oldprio, oldpolicy = -1, on_rq, running;
4472 unsigned long flags;
4473 const struct sched_class *prev_class;
4474 struct rq *rq;
4475 int reset_on_fork;
4477 /* may grab non-irq protected spin_locks */
4478 BUG_ON(in_interrupt());
4479 recheck:
4480 /* double check policy once rq lock held */
4481 if (policy < 0) {
4482 reset_on_fork = p->sched_reset_on_fork;
4483 policy = oldpolicy = p->policy;
4484 } else {
4485 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4486 policy &= ~SCHED_RESET_ON_FORK;
4488 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4489 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4490 policy != SCHED_IDLE)
4491 return -EINVAL;
4495 * Valid priorities for SCHED_FIFO and SCHED_RR are
4496 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4497 * SCHED_BATCH and SCHED_IDLE is 0.
4499 if (param->sched_priority < 0 ||
4500 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4501 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4502 return -EINVAL;
4503 if (rt_policy(policy) != (param->sched_priority != 0))
4504 return -EINVAL;
4507 * Allow unprivileged RT tasks to decrease priority:
4509 if (user && !capable(CAP_SYS_NICE)) {
4510 if (rt_policy(policy)) {
4511 unsigned long rlim_rtprio;
4513 if (!lock_task_sighand(p, &flags))
4514 return -ESRCH;
4515 rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO);
4516 unlock_task_sighand(p, &flags);
4518 /* can't set/change the rt policy */
4519 if (policy != p->policy && !rlim_rtprio)
4520 return -EPERM;
4522 /* can't increase priority */
4523 if (param->sched_priority > p->rt_priority &&
4524 param->sched_priority > rlim_rtprio)
4525 return -EPERM;
4528 * Like positive nice levels, dont allow tasks to
4529 * move out of SCHED_IDLE either:
4531 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4532 return -EPERM;
4534 /* can't change other user's priorities */
4535 if (!check_same_owner(p))
4536 return -EPERM;
4538 /* Normal users shall not reset the sched_reset_on_fork flag */
4539 if (p->sched_reset_on_fork && !reset_on_fork)
4540 return -EPERM;
4543 if (user) {
4544 #ifdef CONFIG_RT_GROUP_SCHED
4546 * Do not allow realtime tasks into groups that have no runtime
4547 * assigned.
4549 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4550 task_group(p)->rt_bandwidth.rt_runtime == 0)
4551 return -EPERM;
4552 #endif
4554 retval = security_task_setscheduler(p, policy, param);
4555 if (retval)
4556 return retval;
4560 * make sure no PI-waiters arrive (or leave) while we are
4561 * changing the priority of the task:
4563 raw_spin_lock_irqsave(&p->pi_lock, flags);
4565 * To be able to change p->policy safely, the apropriate
4566 * runqueue lock must be held.
4568 rq = __task_rq_lock(p);
4569 /* recheck policy now with rq lock held */
4570 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4571 policy = oldpolicy = -1;
4572 __task_rq_unlock(rq);
4573 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4574 goto recheck;
4576 update_rq_clock(rq);
4577 on_rq = p->se.on_rq;
4578 running = task_current(rq, p);
4579 if (on_rq)
4580 deactivate_task(rq, p, 0);
4581 if (running)
4582 p->sched_class->put_prev_task(rq, p);
4584 p->sched_reset_on_fork = reset_on_fork;
4586 oldprio = p->prio;
4587 prev_class = p->sched_class;
4588 __setscheduler(rq, p, policy, param->sched_priority);
4590 if (running)
4591 p->sched_class->set_curr_task(rq);
4592 if (on_rq) {
4593 activate_task(rq, p, 0);
4595 check_class_changed(rq, p, prev_class, oldprio, running);
4597 __task_rq_unlock(rq);
4598 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4600 rt_mutex_adjust_pi(p);
4602 return 0;
4606 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4607 * @p: the task in question.
4608 * @policy: new policy.
4609 * @param: structure containing the new RT priority.
4611 * NOTE that the task may be already dead.
4613 int sched_setscheduler(struct task_struct *p, int policy,
4614 struct sched_param *param)
4616 return __sched_setscheduler(p, policy, param, true);
4618 EXPORT_SYMBOL_GPL(sched_setscheduler);
4621 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4622 * @p: the task in question.
4623 * @policy: new policy.
4624 * @param: structure containing the new RT priority.
4626 * Just like sched_setscheduler, only don't bother checking if the
4627 * current context has permission. For example, this is needed in
4628 * stop_machine(): we create temporary high priority worker threads,
4629 * but our caller might not have that capability.
4631 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4632 struct sched_param *param)
4634 return __sched_setscheduler(p, policy, param, false);
4637 static int
4638 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4640 struct sched_param lparam;
4641 struct task_struct *p;
4642 int retval;
4644 if (!param || pid < 0)
4645 return -EINVAL;
4646 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4647 return -EFAULT;
4649 rcu_read_lock();
4650 retval = -ESRCH;
4651 p = find_process_by_pid(pid);
4652 if (p != NULL)
4653 retval = sched_setscheduler(p, policy, &lparam);
4654 rcu_read_unlock();
4656 return retval;
4660 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4661 * @pid: the pid in question.
4662 * @policy: new policy.
4663 * @param: structure containing the new RT priority.
4665 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4666 struct sched_param __user *, param)
4668 /* negative values for policy are not valid */
4669 if (policy < 0)
4670 return -EINVAL;
4672 return do_sched_setscheduler(pid, policy, param);
4676 * sys_sched_setparam - set/change the RT priority of a thread
4677 * @pid: the pid in question.
4678 * @param: structure containing the new RT priority.
4680 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4682 return do_sched_setscheduler(pid, -1, param);
4686 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4687 * @pid: the pid in question.
4689 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4691 struct task_struct *p;
4692 int retval;
4694 if (pid < 0)
4695 return -EINVAL;
4697 retval = -ESRCH;
4698 rcu_read_lock();
4699 p = find_process_by_pid(pid);
4700 if (p) {
4701 retval = security_task_getscheduler(p);
4702 if (!retval)
4703 retval = p->policy
4704 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4706 rcu_read_unlock();
4707 return retval;
4711 * sys_sched_getparam - get the RT priority of a thread
4712 * @pid: the pid in question.
4713 * @param: structure containing the RT priority.
4715 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4717 struct sched_param lp;
4718 struct task_struct *p;
4719 int retval;
4721 if (!param || pid < 0)
4722 return -EINVAL;
4724 rcu_read_lock();
4725 p = find_process_by_pid(pid);
4726 retval = -ESRCH;
4727 if (!p)
4728 goto out_unlock;
4730 retval = security_task_getscheduler(p);
4731 if (retval)
4732 goto out_unlock;
4734 lp.sched_priority = p->rt_priority;
4735 rcu_read_unlock();
4738 * This one might sleep, we cannot do it with a spinlock held ...
4740 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4742 return retval;
4744 out_unlock:
4745 rcu_read_unlock();
4746 return retval;
4749 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4751 cpumask_var_t cpus_allowed, new_mask;
4752 struct task_struct *p;
4753 int retval;
4755 get_online_cpus();
4756 rcu_read_lock();
4758 p = find_process_by_pid(pid);
4759 if (!p) {
4760 rcu_read_unlock();
4761 put_online_cpus();
4762 return -ESRCH;
4765 /* Prevent p going away */
4766 get_task_struct(p);
4767 rcu_read_unlock();
4769 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4770 retval = -ENOMEM;
4771 goto out_put_task;
4773 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4774 retval = -ENOMEM;
4775 goto out_free_cpus_allowed;
4777 retval = -EPERM;
4778 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
4779 goto out_unlock;
4781 retval = security_task_setscheduler(p, 0, NULL);
4782 if (retval)
4783 goto out_unlock;
4785 cpuset_cpus_allowed(p, cpus_allowed);
4786 cpumask_and(new_mask, in_mask, cpus_allowed);
4787 again:
4788 retval = set_cpus_allowed_ptr(p, new_mask);
4790 if (!retval) {
4791 cpuset_cpus_allowed(p, cpus_allowed);
4792 if (!cpumask_subset(new_mask, cpus_allowed)) {
4794 * We must have raced with a concurrent cpuset
4795 * update. Just reset the cpus_allowed to the
4796 * cpuset's cpus_allowed
4798 cpumask_copy(new_mask, cpus_allowed);
4799 goto again;
4802 out_unlock:
4803 free_cpumask_var(new_mask);
4804 out_free_cpus_allowed:
4805 free_cpumask_var(cpus_allowed);
4806 out_put_task:
4807 put_task_struct(p);
4808 put_online_cpus();
4809 return retval;
4812 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4813 struct cpumask *new_mask)
4815 if (len < cpumask_size())
4816 cpumask_clear(new_mask);
4817 else if (len > cpumask_size())
4818 len = cpumask_size();
4820 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4824 * sys_sched_setaffinity - set the cpu affinity of a process
4825 * @pid: pid of the process
4826 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4827 * @user_mask_ptr: user-space pointer to the new cpu mask
4829 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4830 unsigned long __user *, user_mask_ptr)
4832 cpumask_var_t new_mask;
4833 int retval;
4835 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4836 return -ENOMEM;
4838 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4839 if (retval == 0)
4840 retval = sched_setaffinity(pid, new_mask);
4841 free_cpumask_var(new_mask);
4842 return retval;
4845 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4847 struct task_struct *p;
4848 unsigned long flags;
4849 struct rq *rq;
4850 int retval;
4852 get_online_cpus();
4853 rcu_read_lock();
4855 retval = -ESRCH;
4856 p = find_process_by_pid(pid);
4857 if (!p)
4858 goto out_unlock;
4860 retval = security_task_getscheduler(p);
4861 if (retval)
4862 goto out_unlock;
4864 rq = task_rq_lock(p, &flags);
4865 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4866 task_rq_unlock(rq, &flags);
4868 out_unlock:
4869 rcu_read_unlock();
4870 put_online_cpus();
4872 return retval;
4876 * sys_sched_getaffinity - get the cpu affinity of a process
4877 * @pid: pid of the process
4878 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4879 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4881 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4882 unsigned long __user *, user_mask_ptr)
4884 int ret;
4885 cpumask_var_t mask;
4887 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4888 return -EINVAL;
4889 if (len & (sizeof(unsigned long)-1))
4890 return -EINVAL;
4892 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4893 return -ENOMEM;
4895 ret = sched_getaffinity(pid, mask);
4896 if (ret == 0) {
4897 size_t retlen = min_t(size_t, len, cpumask_size());
4899 if (copy_to_user(user_mask_ptr, mask, retlen))
4900 ret = -EFAULT;
4901 else
4902 ret = retlen;
4904 free_cpumask_var(mask);
4906 return ret;
4910 * sys_sched_yield - yield the current processor to other threads.
4912 * This function yields the current CPU to other tasks. If there are no
4913 * other threads running on this CPU then this function will return.
4915 SYSCALL_DEFINE0(sched_yield)
4917 struct rq *rq = this_rq_lock();
4919 schedstat_inc(rq, yld_count);
4920 current->sched_class->yield_task(rq);
4923 * Since we are going to call schedule() anyway, there's
4924 * no need to preempt or enable interrupts:
4926 __release(rq->lock);
4927 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4928 do_raw_spin_unlock(&rq->lock);
4929 preempt_enable_no_resched();
4931 schedule();
4933 return 0;
4936 static inline int should_resched(void)
4938 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
4941 static void __cond_resched(void)
4943 add_preempt_count(PREEMPT_ACTIVE);
4944 schedule();
4945 sub_preempt_count(PREEMPT_ACTIVE);
4948 int __sched _cond_resched(void)
4950 if (should_resched()) {
4951 __cond_resched();
4952 return 1;
4954 return 0;
4956 EXPORT_SYMBOL(_cond_resched);
4959 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4960 * call schedule, and on return reacquire the lock.
4962 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4963 * operations here to prevent schedule() from being called twice (once via
4964 * spin_unlock(), once by hand).
4966 int __cond_resched_lock(spinlock_t *lock)
4968 int resched = should_resched();
4969 int ret = 0;
4971 lockdep_assert_held(lock);
4973 if (spin_needbreak(lock) || resched) {
4974 spin_unlock(lock);
4975 if (resched)
4976 __cond_resched();
4977 else
4978 cpu_relax();
4979 ret = 1;
4980 spin_lock(lock);
4982 return ret;
4984 EXPORT_SYMBOL(__cond_resched_lock);
4986 int __sched __cond_resched_softirq(void)
4988 BUG_ON(!in_softirq());
4990 if (should_resched()) {
4991 local_bh_enable();
4992 __cond_resched();
4993 local_bh_disable();
4994 return 1;
4996 return 0;
4998 EXPORT_SYMBOL(__cond_resched_softirq);
5001 * yield - yield the current processor to other threads.
5003 * This is a shortcut for kernel-space yielding - it marks the
5004 * thread runnable and calls sys_sched_yield().
5006 void __sched yield(void)
5008 set_current_state(TASK_RUNNING);
5009 sys_sched_yield();
5011 EXPORT_SYMBOL(yield);
5014 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5015 * that process accounting knows that this is a task in IO wait state.
5017 void __sched io_schedule(void)
5019 struct rq *rq = raw_rq();
5021 delayacct_blkio_start();
5022 atomic_inc(&rq->nr_iowait);
5023 current->in_iowait = 1;
5024 schedule();
5025 current->in_iowait = 0;
5026 atomic_dec(&rq->nr_iowait);
5027 delayacct_blkio_end();
5029 EXPORT_SYMBOL(io_schedule);
5031 long __sched io_schedule_timeout(long timeout)
5033 struct rq *rq = raw_rq();
5034 long ret;
5036 delayacct_blkio_start();
5037 atomic_inc(&rq->nr_iowait);
5038 current->in_iowait = 1;
5039 ret = schedule_timeout(timeout);
5040 current->in_iowait = 0;
5041 atomic_dec(&rq->nr_iowait);
5042 delayacct_blkio_end();
5043 return ret;
5047 * sys_sched_get_priority_max - return maximum RT priority.
5048 * @policy: scheduling class.
5050 * this syscall returns the maximum rt_priority that can be used
5051 * by a given scheduling class.
5053 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5055 int ret = -EINVAL;
5057 switch (policy) {
5058 case SCHED_FIFO:
5059 case SCHED_RR:
5060 ret = MAX_USER_RT_PRIO-1;
5061 break;
5062 case SCHED_NORMAL:
5063 case SCHED_BATCH:
5064 case SCHED_IDLE:
5065 ret = 0;
5066 break;
5068 return ret;
5072 * sys_sched_get_priority_min - return minimum RT priority.
5073 * @policy: scheduling class.
5075 * this syscall returns the minimum rt_priority that can be used
5076 * by a given scheduling class.
5078 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5080 int ret = -EINVAL;
5082 switch (policy) {
5083 case SCHED_FIFO:
5084 case SCHED_RR:
5085 ret = 1;
5086 break;
5087 case SCHED_NORMAL:
5088 case SCHED_BATCH:
5089 case SCHED_IDLE:
5090 ret = 0;
5092 return ret;
5096 * sys_sched_rr_get_interval - return the default timeslice of a process.
5097 * @pid: pid of the process.
5098 * @interval: userspace pointer to the timeslice value.
5100 * this syscall writes the default timeslice value of a given process
5101 * into the user-space timespec buffer. A value of '0' means infinity.
5103 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5104 struct timespec __user *, interval)
5106 struct task_struct *p;
5107 unsigned int time_slice;
5108 unsigned long flags;
5109 struct rq *rq;
5110 int retval;
5111 struct timespec t;
5113 if (pid < 0)
5114 return -EINVAL;
5116 retval = -ESRCH;
5117 rcu_read_lock();
5118 p = find_process_by_pid(pid);
5119 if (!p)
5120 goto out_unlock;
5122 retval = security_task_getscheduler(p);
5123 if (retval)
5124 goto out_unlock;
5126 rq = task_rq_lock(p, &flags);
5127 time_slice = p->sched_class->get_rr_interval(rq, p);
5128 task_rq_unlock(rq, &flags);
5130 rcu_read_unlock();
5131 jiffies_to_timespec(time_slice, &t);
5132 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5133 return retval;
5135 out_unlock:
5136 rcu_read_unlock();
5137 return retval;
5140 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5142 void sched_show_task(struct task_struct *p)
5144 unsigned long free = 0;
5145 unsigned state;
5147 state = p->state ? __ffs(p->state) + 1 : 0;
5148 printk(KERN_INFO "%-13.13s %c", p->comm,
5149 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5150 #if BITS_PER_LONG == 32
5151 if (state == TASK_RUNNING)
5152 printk(KERN_CONT " running ");
5153 else
5154 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5155 #else
5156 if (state == TASK_RUNNING)
5157 printk(KERN_CONT " running task ");
5158 else
5159 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5160 #endif
5161 #ifdef CONFIG_DEBUG_STACK_USAGE
5162 free = stack_not_used(p);
5163 #endif
5164 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5165 task_pid_nr(p), task_pid_nr(p->real_parent),
5166 (unsigned long)task_thread_info(p)->flags);
5168 show_stack(p, NULL);
5171 void show_state_filter(unsigned long state_filter)
5173 struct task_struct *g, *p;
5175 #if BITS_PER_LONG == 32
5176 printk(KERN_INFO
5177 " task PC stack pid father\n");
5178 #else
5179 printk(KERN_INFO
5180 " task PC stack pid father\n");
5181 #endif
5182 read_lock(&tasklist_lock);
5183 do_each_thread(g, p) {
5185 * reset the NMI-timeout, listing all files on a slow
5186 * console might take alot of time:
5188 touch_nmi_watchdog();
5189 if (!state_filter || (p->state & state_filter))
5190 sched_show_task(p);
5191 } while_each_thread(g, p);
5193 touch_all_softlockup_watchdogs();
5195 #ifdef CONFIG_SCHED_DEBUG
5196 sysrq_sched_debug_show();
5197 #endif
5198 read_unlock(&tasklist_lock);
5200 * Only show locks if all tasks are dumped:
5202 if (!state_filter)
5203 debug_show_all_locks();
5206 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5208 idle->sched_class = &idle_sched_class;
5212 * init_idle - set up an idle thread for a given CPU
5213 * @idle: task in question
5214 * @cpu: cpu the idle task belongs to
5216 * NOTE: this function does not set the idle thread's NEED_RESCHED
5217 * flag, to make booting more robust.
5219 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5221 struct rq *rq = cpu_rq(cpu);
5222 unsigned long flags;
5224 raw_spin_lock_irqsave(&rq->lock, flags);
5226 __sched_fork(idle);
5227 idle->state = TASK_RUNNING;
5228 idle->se.exec_start = sched_clock();
5230 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
5232 * We're having a chicken and egg problem, even though we are
5233 * holding rq->lock, the cpu isn't yet set to this cpu so the
5234 * lockdep check in task_group() will fail.
5236 * Similar case to sched_fork(). / Alternatively we could
5237 * use task_rq_lock() here and obtain the other rq->lock.
5239 * Silence PROVE_RCU
5241 rcu_read_lock();
5242 __set_task_cpu(idle, cpu);
5243 rcu_read_unlock();
5245 rq->curr = rq->idle = idle;
5246 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5247 idle->oncpu = 1;
5248 #endif
5249 raw_spin_unlock_irqrestore(&rq->lock, flags);
5251 /* Set the preempt count _outside_ the spinlocks! */
5252 #if defined(CONFIG_PREEMPT)
5253 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5254 #else
5255 task_thread_info(idle)->preempt_count = 0;
5256 #endif
5258 * The idle tasks have their own, simple scheduling class:
5260 idle->sched_class = &idle_sched_class;
5261 ftrace_graph_init_idle_task(idle, cpu);
5265 * In a system that switches off the HZ timer nohz_cpu_mask
5266 * indicates which cpus entered this state. This is used
5267 * in the rcu update to wait only for active cpus. For system
5268 * which do not switch off the HZ timer nohz_cpu_mask should
5269 * always be CPU_BITS_NONE.
5271 cpumask_var_t nohz_cpu_mask;
5274 * Increase the granularity value when there are more CPUs,
5275 * because with more CPUs the 'effective latency' as visible
5276 * to users decreases. But the relationship is not linear,
5277 * so pick a second-best guess by going with the log2 of the
5278 * number of CPUs.
5280 * This idea comes from the SD scheduler of Con Kolivas:
5282 static int get_update_sysctl_factor(void)
5284 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5285 unsigned int factor;
5287 switch (sysctl_sched_tunable_scaling) {
5288 case SCHED_TUNABLESCALING_NONE:
5289 factor = 1;
5290 break;
5291 case SCHED_TUNABLESCALING_LINEAR:
5292 factor = cpus;
5293 break;
5294 case SCHED_TUNABLESCALING_LOG:
5295 default:
5296 factor = 1 + ilog2(cpus);
5297 break;
5300 return factor;
5303 static void update_sysctl(void)
5305 unsigned int factor = get_update_sysctl_factor();
5307 #define SET_SYSCTL(name) \
5308 (sysctl_##name = (factor) * normalized_sysctl_##name)
5309 SET_SYSCTL(sched_min_granularity);
5310 SET_SYSCTL(sched_latency);
5311 SET_SYSCTL(sched_wakeup_granularity);
5312 SET_SYSCTL(sched_shares_ratelimit);
5313 #undef SET_SYSCTL
5316 static inline void sched_init_granularity(void)
5318 update_sysctl();
5321 #ifdef CONFIG_SMP
5323 * This is how migration works:
5325 * 1) we queue a struct migration_req structure in the source CPU's
5326 * runqueue and wake up that CPU's migration thread.
5327 * 2) we down() the locked semaphore => thread blocks.
5328 * 3) migration thread wakes up (implicitly it forces the migrated
5329 * thread off the CPU)
5330 * 4) it gets the migration request and checks whether the migrated
5331 * task is still in the wrong runqueue.
5332 * 5) if it's in the wrong runqueue then the migration thread removes
5333 * it and puts it into the right queue.
5334 * 6) migration thread up()s the semaphore.
5335 * 7) we wake up and the migration is done.
5339 * Change a given task's CPU affinity. Migrate the thread to a
5340 * proper CPU and schedule it away if the CPU it's executing on
5341 * is removed from the allowed bitmask.
5343 * NOTE: the caller must have a valid reference to the task, the
5344 * task must not exit() & deallocate itself prematurely. The
5345 * call is not atomic; no spinlocks may be held.
5347 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
5349 struct migration_req req;
5350 unsigned long flags;
5351 struct rq *rq;
5352 int ret = 0;
5355 * Serialize against TASK_WAKING so that ttwu() and wunt() can
5356 * drop the rq->lock and still rely on ->cpus_allowed.
5358 again:
5359 while (task_is_waking(p))
5360 cpu_relax();
5361 rq = task_rq_lock(p, &flags);
5362 if (task_is_waking(p)) {
5363 task_rq_unlock(rq, &flags);
5364 goto again;
5367 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
5368 ret = -EINVAL;
5369 goto out;
5372 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5373 !cpumask_equal(&p->cpus_allowed, new_mask))) {
5374 ret = -EINVAL;
5375 goto out;
5378 if (p->sched_class->set_cpus_allowed)
5379 p->sched_class->set_cpus_allowed(p, new_mask);
5380 else {
5381 cpumask_copy(&p->cpus_allowed, new_mask);
5382 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
5385 /* Can the task run on the task's current CPU? If so, we're done */
5386 if (cpumask_test_cpu(task_cpu(p), new_mask))
5387 goto out;
5389 if (migrate_task(p, cpumask_any_and(cpu_active_mask, new_mask), &req)) {
5390 /* Need help from migration thread: drop lock and wait. */
5391 struct task_struct *mt = rq->migration_thread;
5393 get_task_struct(mt);
5394 task_rq_unlock(rq, &flags);
5395 wake_up_process(mt);
5396 put_task_struct(mt);
5397 wait_for_completion(&req.done);
5398 tlb_migrate_finish(p->mm);
5399 return 0;
5401 out:
5402 task_rq_unlock(rq, &flags);
5404 return ret;
5406 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5409 * Move (not current) task off this cpu, onto dest cpu. We're doing
5410 * this because either it can't run here any more (set_cpus_allowed()
5411 * away from this CPU, or CPU going down), or because we're
5412 * attempting to rebalance this task on exec (sched_exec).
5414 * So we race with normal scheduler movements, but that's OK, as long
5415 * as the task is no longer on this CPU.
5417 * Returns non-zero if task was successfully migrated.
5419 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5421 struct rq *rq_dest, *rq_src;
5422 int ret = 0;
5424 if (unlikely(!cpu_active(dest_cpu)))
5425 return ret;
5427 rq_src = cpu_rq(src_cpu);
5428 rq_dest = cpu_rq(dest_cpu);
5430 double_rq_lock(rq_src, rq_dest);
5431 /* Already moved. */
5432 if (task_cpu(p) != src_cpu)
5433 goto done;
5434 /* Affinity changed (again). */
5435 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5436 goto fail;
5439 * If we're not on a rq, the next wake-up will ensure we're
5440 * placed properly.
5442 if (p->se.on_rq) {
5443 deactivate_task(rq_src, p, 0);
5444 set_task_cpu(p, dest_cpu);
5445 activate_task(rq_dest, p, 0);
5446 check_preempt_curr(rq_dest, p, 0);
5448 done:
5449 ret = 1;
5450 fail:
5451 double_rq_unlock(rq_src, rq_dest);
5452 return ret;
5455 #define RCU_MIGRATION_IDLE 0
5456 #define RCU_MIGRATION_NEED_QS 1
5457 #define RCU_MIGRATION_GOT_QS 2
5458 #define RCU_MIGRATION_MUST_SYNC 3
5461 * migration_thread - this is a highprio system thread that performs
5462 * thread migration by bumping thread off CPU then 'pushing' onto
5463 * another runqueue.
5465 static int migration_thread(void *data)
5467 int badcpu;
5468 int cpu = (long)data;
5469 struct rq *rq;
5471 rq = cpu_rq(cpu);
5472 BUG_ON(rq->migration_thread != current);
5474 set_current_state(TASK_INTERRUPTIBLE);
5475 while (!kthread_should_stop()) {
5476 struct migration_req *req;
5477 struct list_head *head;
5479 raw_spin_lock_irq(&rq->lock);
5481 if (cpu_is_offline(cpu)) {
5482 raw_spin_unlock_irq(&rq->lock);
5483 break;
5486 if (rq->active_balance) {
5487 active_load_balance(rq, cpu);
5488 rq->active_balance = 0;
5491 head = &rq->migration_queue;
5493 if (list_empty(head)) {
5494 raw_spin_unlock_irq(&rq->lock);
5495 schedule();
5496 set_current_state(TASK_INTERRUPTIBLE);
5497 continue;
5499 req = list_entry(head->next, struct migration_req, list);
5500 list_del_init(head->next);
5502 if (req->task != NULL) {
5503 raw_spin_unlock(&rq->lock);
5504 __migrate_task(req->task, cpu, req->dest_cpu);
5505 } else if (likely(cpu == (badcpu = smp_processor_id()))) {
5506 req->dest_cpu = RCU_MIGRATION_GOT_QS;
5507 raw_spin_unlock(&rq->lock);
5508 } else {
5509 req->dest_cpu = RCU_MIGRATION_MUST_SYNC;
5510 raw_spin_unlock(&rq->lock);
5511 WARN_ONCE(1, "migration_thread() on CPU %d, expected %d\n", badcpu, cpu);
5513 local_irq_enable();
5515 complete(&req->done);
5517 __set_current_state(TASK_RUNNING);
5519 return 0;
5522 #ifdef CONFIG_HOTPLUG_CPU
5524 * Figure out where task on dead CPU should go, use force if necessary.
5526 void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5528 struct rq *rq = cpu_rq(dead_cpu);
5529 int needs_cpu, uninitialized_var(dest_cpu);
5530 unsigned long flags;
5532 local_irq_save(flags);
5534 raw_spin_lock(&rq->lock);
5535 needs_cpu = (task_cpu(p) == dead_cpu) && (p->state != TASK_WAKING);
5536 if (needs_cpu)
5537 dest_cpu = select_fallback_rq(dead_cpu, p);
5538 raw_spin_unlock(&rq->lock);
5540 * It can only fail if we race with set_cpus_allowed(),
5541 * in the racer should migrate the task anyway.
5543 if (needs_cpu)
5544 __migrate_task(p, dead_cpu, dest_cpu);
5545 local_irq_restore(flags);
5549 * While a dead CPU has no uninterruptible tasks queued at this point,
5550 * it might still have a nonzero ->nr_uninterruptible counter, because
5551 * for performance reasons the counter is not stricly tracking tasks to
5552 * their home CPUs. So we just add the counter to another CPU's counter,
5553 * to keep the global sum constant after CPU-down:
5555 static void migrate_nr_uninterruptible(struct rq *rq_src)
5557 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
5558 unsigned long flags;
5560 local_irq_save(flags);
5561 double_rq_lock(rq_src, rq_dest);
5562 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5563 rq_src->nr_uninterruptible = 0;
5564 double_rq_unlock(rq_src, rq_dest);
5565 local_irq_restore(flags);
5568 /* Run through task list and migrate tasks from the dead cpu. */
5569 static void migrate_live_tasks(int src_cpu)
5571 struct task_struct *p, *t;
5573 read_lock(&tasklist_lock);
5575 do_each_thread(t, p) {
5576 if (p == current)
5577 continue;
5579 if (task_cpu(p) == src_cpu)
5580 move_task_off_dead_cpu(src_cpu, p);
5581 } while_each_thread(t, p);
5583 read_unlock(&tasklist_lock);
5587 * Schedules idle task to be the next runnable task on current CPU.
5588 * It does so by boosting its priority to highest possible.
5589 * Used by CPU offline code.
5591 void sched_idle_next(void)
5593 int this_cpu = smp_processor_id();
5594 struct rq *rq = cpu_rq(this_cpu);
5595 struct task_struct *p = rq->idle;
5596 unsigned long flags;
5598 /* cpu has to be offline */
5599 BUG_ON(cpu_online(this_cpu));
5602 * Strictly not necessary since rest of the CPUs are stopped by now
5603 * and interrupts disabled on the current cpu.
5605 raw_spin_lock_irqsave(&rq->lock, flags);
5607 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5609 update_rq_clock(rq);
5610 activate_task(rq, p, 0);
5612 raw_spin_unlock_irqrestore(&rq->lock, flags);
5616 * Ensures that the idle task is using init_mm right before its cpu goes
5617 * offline.
5619 void idle_task_exit(void)
5621 struct mm_struct *mm = current->active_mm;
5623 BUG_ON(cpu_online(smp_processor_id()));
5625 if (mm != &init_mm)
5626 switch_mm(mm, &init_mm, current);
5627 mmdrop(mm);
5630 /* called under rq->lock with disabled interrupts */
5631 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5633 struct rq *rq = cpu_rq(dead_cpu);
5635 /* Must be exiting, otherwise would be on tasklist. */
5636 BUG_ON(!p->exit_state);
5638 /* Cannot have done final schedule yet: would have vanished. */
5639 BUG_ON(p->state == TASK_DEAD);
5641 get_task_struct(p);
5644 * Drop lock around migration; if someone else moves it,
5645 * that's OK. No task can be added to this CPU, so iteration is
5646 * fine.
5648 raw_spin_unlock_irq(&rq->lock);
5649 move_task_off_dead_cpu(dead_cpu, p);
5650 raw_spin_lock_irq(&rq->lock);
5652 put_task_struct(p);
5655 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5656 static void migrate_dead_tasks(unsigned int dead_cpu)
5658 struct rq *rq = cpu_rq(dead_cpu);
5659 struct task_struct *next;
5661 for ( ; ; ) {
5662 if (!rq->nr_running)
5663 break;
5664 update_rq_clock(rq);
5665 next = pick_next_task(rq);
5666 if (!next)
5667 break;
5668 next->sched_class->put_prev_task(rq, next);
5669 migrate_dead(dead_cpu, next);
5675 * remove the tasks which were accounted by rq from calc_load_tasks.
5677 static void calc_global_load_remove(struct rq *rq)
5679 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
5680 rq->calc_load_active = 0;
5682 #endif /* CONFIG_HOTPLUG_CPU */
5684 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5686 static struct ctl_table sd_ctl_dir[] = {
5688 .procname = "sched_domain",
5689 .mode = 0555,
5694 static struct ctl_table sd_ctl_root[] = {
5696 .procname = "kernel",
5697 .mode = 0555,
5698 .child = sd_ctl_dir,
5703 static struct ctl_table *sd_alloc_ctl_entry(int n)
5705 struct ctl_table *entry =
5706 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5708 return entry;
5711 static void sd_free_ctl_entry(struct ctl_table **tablep)
5713 struct ctl_table *entry;
5716 * In the intermediate directories, both the child directory and
5717 * procname are dynamically allocated and could fail but the mode
5718 * will always be set. In the lowest directory the names are
5719 * static strings and all have proc handlers.
5721 for (entry = *tablep; entry->mode; entry++) {
5722 if (entry->child)
5723 sd_free_ctl_entry(&entry->child);
5724 if (entry->proc_handler == NULL)
5725 kfree(entry->procname);
5728 kfree(*tablep);
5729 *tablep = NULL;
5732 static void
5733 set_table_entry(struct ctl_table *entry,
5734 const char *procname, void *data, int maxlen,
5735 mode_t mode, proc_handler *proc_handler)
5737 entry->procname = procname;
5738 entry->data = data;
5739 entry->maxlen = maxlen;
5740 entry->mode = mode;
5741 entry->proc_handler = proc_handler;
5744 static struct ctl_table *
5745 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5747 struct ctl_table *table = sd_alloc_ctl_entry(13);
5749 if (table == NULL)
5750 return NULL;
5752 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5753 sizeof(long), 0644, proc_doulongvec_minmax);
5754 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5755 sizeof(long), 0644, proc_doulongvec_minmax);
5756 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5757 sizeof(int), 0644, proc_dointvec_minmax);
5758 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5759 sizeof(int), 0644, proc_dointvec_minmax);
5760 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5761 sizeof(int), 0644, proc_dointvec_minmax);
5762 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5763 sizeof(int), 0644, proc_dointvec_minmax);
5764 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5765 sizeof(int), 0644, proc_dointvec_minmax);
5766 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5767 sizeof(int), 0644, proc_dointvec_minmax);
5768 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5769 sizeof(int), 0644, proc_dointvec_minmax);
5770 set_table_entry(&table[9], "cache_nice_tries",
5771 &sd->cache_nice_tries,
5772 sizeof(int), 0644, proc_dointvec_minmax);
5773 set_table_entry(&table[10], "flags", &sd->flags,
5774 sizeof(int), 0644, proc_dointvec_minmax);
5775 set_table_entry(&table[11], "name", sd->name,
5776 CORENAME_MAX_SIZE, 0444, proc_dostring);
5777 /* &table[12] is terminator */
5779 return table;
5782 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5784 struct ctl_table *entry, *table;
5785 struct sched_domain *sd;
5786 int domain_num = 0, i;
5787 char buf[32];
5789 for_each_domain(cpu, sd)
5790 domain_num++;
5791 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5792 if (table == NULL)
5793 return NULL;
5795 i = 0;
5796 for_each_domain(cpu, sd) {
5797 snprintf(buf, 32, "domain%d", i);
5798 entry->procname = kstrdup(buf, GFP_KERNEL);
5799 entry->mode = 0555;
5800 entry->child = sd_alloc_ctl_domain_table(sd);
5801 entry++;
5802 i++;
5804 return table;
5807 static struct ctl_table_header *sd_sysctl_header;
5808 static void register_sched_domain_sysctl(void)
5810 int i, cpu_num = num_possible_cpus();
5811 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5812 char buf[32];
5814 WARN_ON(sd_ctl_dir[0].child);
5815 sd_ctl_dir[0].child = entry;
5817 if (entry == NULL)
5818 return;
5820 for_each_possible_cpu(i) {
5821 snprintf(buf, 32, "cpu%d", i);
5822 entry->procname = kstrdup(buf, GFP_KERNEL);
5823 entry->mode = 0555;
5824 entry->child = sd_alloc_ctl_cpu_table(i);
5825 entry++;
5828 WARN_ON(sd_sysctl_header);
5829 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5832 /* may be called multiple times per register */
5833 static void unregister_sched_domain_sysctl(void)
5835 if (sd_sysctl_header)
5836 unregister_sysctl_table(sd_sysctl_header);
5837 sd_sysctl_header = NULL;
5838 if (sd_ctl_dir[0].child)
5839 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5841 #else
5842 static void register_sched_domain_sysctl(void)
5845 static void unregister_sched_domain_sysctl(void)
5848 #endif
5850 static void set_rq_online(struct rq *rq)
5852 if (!rq->online) {
5853 const struct sched_class *class;
5855 cpumask_set_cpu(rq->cpu, rq->rd->online);
5856 rq->online = 1;
5858 for_each_class(class) {
5859 if (class->rq_online)
5860 class->rq_online(rq);
5865 static void set_rq_offline(struct rq *rq)
5867 if (rq->online) {
5868 const struct sched_class *class;
5870 for_each_class(class) {
5871 if (class->rq_offline)
5872 class->rq_offline(rq);
5875 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5876 rq->online = 0;
5881 * migration_call - callback that gets triggered when a CPU is added.
5882 * Here we can start up the necessary migration thread for the new CPU.
5884 static int __cpuinit
5885 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5887 struct task_struct *p;
5888 int cpu = (long)hcpu;
5889 unsigned long flags;
5890 struct rq *rq;
5892 switch (action) {
5894 case CPU_UP_PREPARE:
5895 case CPU_UP_PREPARE_FROZEN:
5896 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5897 if (IS_ERR(p))
5898 return NOTIFY_BAD;
5899 kthread_bind(p, cpu);
5900 /* Must be high prio: stop_machine expects to yield to it. */
5901 rq = task_rq_lock(p, &flags);
5902 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5903 task_rq_unlock(rq, &flags);
5904 get_task_struct(p);
5905 cpu_rq(cpu)->migration_thread = p;
5906 rq->calc_load_update = calc_load_update;
5907 break;
5909 case CPU_ONLINE:
5910 case CPU_ONLINE_FROZEN:
5911 /* Strictly unnecessary, as first user will wake it. */
5912 wake_up_process(cpu_rq(cpu)->migration_thread);
5914 /* Update our root-domain */
5915 rq = cpu_rq(cpu);
5916 raw_spin_lock_irqsave(&rq->lock, flags);
5917 if (rq->rd) {
5918 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5920 set_rq_online(rq);
5922 raw_spin_unlock_irqrestore(&rq->lock, flags);
5923 break;
5925 #ifdef CONFIG_HOTPLUG_CPU
5926 case CPU_UP_CANCELED:
5927 case CPU_UP_CANCELED_FROZEN:
5928 if (!cpu_rq(cpu)->migration_thread)
5929 break;
5930 /* Unbind it from offline cpu so it can run. Fall thru. */
5931 kthread_bind(cpu_rq(cpu)->migration_thread,
5932 cpumask_any(cpu_online_mask));
5933 kthread_stop(cpu_rq(cpu)->migration_thread);
5934 put_task_struct(cpu_rq(cpu)->migration_thread);
5935 cpu_rq(cpu)->migration_thread = NULL;
5936 break;
5938 case CPU_DEAD:
5939 case CPU_DEAD_FROZEN:
5940 migrate_live_tasks(cpu);
5941 rq = cpu_rq(cpu);
5942 kthread_stop(rq->migration_thread);
5943 put_task_struct(rq->migration_thread);
5944 rq->migration_thread = NULL;
5945 /* Idle task back to normal (off runqueue, low prio) */
5946 raw_spin_lock_irq(&rq->lock);
5947 update_rq_clock(rq);
5948 deactivate_task(rq, rq->idle, 0);
5949 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5950 rq->idle->sched_class = &idle_sched_class;
5951 migrate_dead_tasks(cpu);
5952 raw_spin_unlock_irq(&rq->lock);
5953 migrate_nr_uninterruptible(rq);
5954 BUG_ON(rq->nr_running != 0);
5955 calc_global_load_remove(rq);
5957 * No need to migrate the tasks: it was best-effort if
5958 * they didn't take sched_hotcpu_mutex. Just wake up
5959 * the requestors.
5961 raw_spin_lock_irq(&rq->lock);
5962 while (!list_empty(&rq->migration_queue)) {
5963 struct migration_req *req;
5965 req = list_entry(rq->migration_queue.next,
5966 struct migration_req, list);
5967 list_del_init(&req->list);
5968 raw_spin_unlock_irq(&rq->lock);
5969 complete(&req->done);
5970 raw_spin_lock_irq(&rq->lock);
5972 raw_spin_unlock_irq(&rq->lock);
5973 break;
5975 case CPU_DYING:
5976 case CPU_DYING_FROZEN:
5977 /* Update our root-domain */
5978 rq = cpu_rq(cpu);
5979 raw_spin_lock_irqsave(&rq->lock, flags);
5980 if (rq->rd) {
5981 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5982 set_rq_offline(rq);
5984 raw_spin_unlock_irqrestore(&rq->lock, flags);
5985 break;
5986 #endif
5988 return NOTIFY_OK;
5992 * Register at high priority so that task migration (migrate_all_tasks)
5993 * happens before everything else. This has to be lower priority than
5994 * the notifier in the perf_event subsystem, though.
5996 static struct notifier_block __cpuinitdata migration_notifier = {
5997 .notifier_call = migration_call,
5998 .priority = 10
6001 static int __init migration_init(void)
6003 void *cpu = (void *)(long)smp_processor_id();
6004 int err;
6006 /* Start one for the boot CPU: */
6007 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6008 BUG_ON(err == NOTIFY_BAD);
6009 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6010 register_cpu_notifier(&migration_notifier);
6012 return 0;
6014 early_initcall(migration_init);
6015 #endif
6017 #ifdef CONFIG_SMP
6019 #ifdef CONFIG_SCHED_DEBUG
6021 static __read_mostly int sched_domain_debug_enabled;
6023 static int __init sched_domain_debug_setup(char *str)
6025 sched_domain_debug_enabled = 1;
6027 return 0;
6029 early_param("sched_debug", sched_domain_debug_setup);
6031 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6032 struct cpumask *groupmask)
6034 struct sched_group *group = sd->groups;
6035 char str[256];
6037 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6038 cpumask_clear(groupmask);
6040 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6042 if (!(sd->flags & SD_LOAD_BALANCE)) {
6043 printk("does not load-balance\n");
6044 if (sd->parent)
6045 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6046 " has parent");
6047 return -1;
6050 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6052 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6053 printk(KERN_ERR "ERROR: domain->span does not contain "
6054 "CPU%d\n", cpu);
6056 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6057 printk(KERN_ERR "ERROR: domain->groups does not contain"
6058 " CPU%d\n", cpu);
6061 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6062 do {
6063 if (!group) {
6064 printk("\n");
6065 printk(KERN_ERR "ERROR: group is NULL\n");
6066 break;
6069 if (!group->cpu_power) {
6070 printk(KERN_CONT "\n");
6071 printk(KERN_ERR "ERROR: domain->cpu_power not "
6072 "set\n");
6073 break;
6076 if (!cpumask_weight(sched_group_cpus(group))) {
6077 printk(KERN_CONT "\n");
6078 printk(KERN_ERR "ERROR: empty group\n");
6079 break;
6082 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6083 printk(KERN_CONT "\n");
6084 printk(KERN_ERR "ERROR: repeated CPUs\n");
6085 break;
6088 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6090 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6092 printk(KERN_CONT " %s", str);
6093 if (group->cpu_power != SCHED_LOAD_SCALE) {
6094 printk(KERN_CONT " (cpu_power = %d)",
6095 group->cpu_power);
6098 group = group->next;
6099 } while (group != sd->groups);
6100 printk(KERN_CONT "\n");
6102 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6103 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6105 if (sd->parent &&
6106 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6107 printk(KERN_ERR "ERROR: parent span is not a superset "
6108 "of domain->span\n");
6109 return 0;
6112 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6114 cpumask_var_t groupmask;
6115 int level = 0;
6117 if (!sched_domain_debug_enabled)
6118 return;
6120 if (!sd) {
6121 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6122 return;
6125 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6127 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6128 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6129 return;
6132 for (;;) {
6133 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6134 break;
6135 level++;
6136 sd = sd->parent;
6137 if (!sd)
6138 break;
6140 free_cpumask_var(groupmask);
6142 #else /* !CONFIG_SCHED_DEBUG */
6143 # define sched_domain_debug(sd, cpu) do { } while (0)
6144 #endif /* CONFIG_SCHED_DEBUG */
6146 static int sd_degenerate(struct sched_domain *sd)
6148 if (cpumask_weight(sched_domain_span(sd)) == 1)
6149 return 1;
6151 /* Following flags need at least 2 groups */
6152 if (sd->flags & (SD_LOAD_BALANCE |
6153 SD_BALANCE_NEWIDLE |
6154 SD_BALANCE_FORK |
6155 SD_BALANCE_EXEC |
6156 SD_SHARE_CPUPOWER |
6157 SD_SHARE_PKG_RESOURCES)) {
6158 if (sd->groups != sd->groups->next)
6159 return 0;
6162 /* Following flags don't use groups */
6163 if (sd->flags & (SD_WAKE_AFFINE))
6164 return 0;
6166 return 1;
6169 static int
6170 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6172 unsigned long cflags = sd->flags, pflags = parent->flags;
6174 if (sd_degenerate(parent))
6175 return 1;
6177 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6178 return 0;
6180 /* Flags needing groups don't count if only 1 group in parent */
6181 if (parent->groups == parent->groups->next) {
6182 pflags &= ~(SD_LOAD_BALANCE |
6183 SD_BALANCE_NEWIDLE |
6184 SD_BALANCE_FORK |
6185 SD_BALANCE_EXEC |
6186 SD_SHARE_CPUPOWER |
6187 SD_SHARE_PKG_RESOURCES);
6188 if (nr_node_ids == 1)
6189 pflags &= ~SD_SERIALIZE;
6191 if (~cflags & pflags)
6192 return 0;
6194 return 1;
6197 static void free_rootdomain(struct root_domain *rd)
6199 synchronize_sched();
6201 cpupri_cleanup(&rd->cpupri);
6203 free_cpumask_var(rd->rto_mask);
6204 free_cpumask_var(rd->online);
6205 free_cpumask_var(rd->span);
6206 kfree(rd);
6209 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6211 struct root_domain *old_rd = NULL;
6212 unsigned long flags;
6214 raw_spin_lock_irqsave(&rq->lock, flags);
6216 if (rq->rd) {
6217 old_rd = rq->rd;
6219 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6220 set_rq_offline(rq);
6222 cpumask_clear_cpu(rq->cpu, old_rd->span);
6225 * If we dont want to free the old_rt yet then
6226 * set old_rd to NULL to skip the freeing later
6227 * in this function:
6229 if (!atomic_dec_and_test(&old_rd->refcount))
6230 old_rd = NULL;
6233 atomic_inc(&rd->refcount);
6234 rq->rd = rd;
6236 cpumask_set_cpu(rq->cpu, rd->span);
6237 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6238 set_rq_online(rq);
6240 raw_spin_unlock_irqrestore(&rq->lock, flags);
6242 if (old_rd)
6243 free_rootdomain(old_rd);
6246 static int init_rootdomain(struct root_domain *rd, bool bootmem)
6248 gfp_t gfp = GFP_KERNEL;
6250 memset(rd, 0, sizeof(*rd));
6252 if (bootmem)
6253 gfp = GFP_NOWAIT;
6255 if (!alloc_cpumask_var(&rd->span, gfp))
6256 goto out;
6257 if (!alloc_cpumask_var(&rd->online, gfp))
6258 goto free_span;
6259 if (!alloc_cpumask_var(&rd->rto_mask, gfp))
6260 goto free_online;
6262 if (cpupri_init(&rd->cpupri, bootmem) != 0)
6263 goto free_rto_mask;
6264 return 0;
6266 free_rto_mask:
6267 free_cpumask_var(rd->rto_mask);
6268 free_online:
6269 free_cpumask_var(rd->online);
6270 free_span:
6271 free_cpumask_var(rd->span);
6272 out:
6273 return -ENOMEM;
6276 static void init_defrootdomain(void)
6278 init_rootdomain(&def_root_domain, true);
6280 atomic_set(&def_root_domain.refcount, 1);
6283 static struct root_domain *alloc_rootdomain(void)
6285 struct root_domain *rd;
6287 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6288 if (!rd)
6289 return NULL;
6291 if (init_rootdomain(rd, false) != 0) {
6292 kfree(rd);
6293 return NULL;
6296 return rd;
6300 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6301 * hold the hotplug lock.
6303 static void
6304 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6306 struct rq *rq = cpu_rq(cpu);
6307 struct sched_domain *tmp;
6309 for (tmp = sd; tmp; tmp = tmp->parent)
6310 tmp->span_weight = cpumask_weight(sched_domain_span(tmp));
6312 /* Remove the sched domains which do not contribute to scheduling. */
6313 for (tmp = sd; tmp; ) {
6314 struct sched_domain *parent = tmp->parent;
6315 if (!parent)
6316 break;
6318 if (sd_parent_degenerate(tmp, parent)) {
6319 tmp->parent = parent->parent;
6320 if (parent->parent)
6321 parent->parent->child = tmp;
6322 } else
6323 tmp = tmp->parent;
6326 if (sd && sd_degenerate(sd)) {
6327 sd = sd->parent;
6328 if (sd)
6329 sd->child = NULL;
6332 sched_domain_debug(sd, cpu);
6334 rq_attach_root(rq, rd);
6335 rcu_assign_pointer(rq->sd, sd);
6338 /* cpus with isolated domains */
6339 static cpumask_var_t cpu_isolated_map;
6341 /* Setup the mask of cpus configured for isolated domains */
6342 static int __init isolated_cpu_setup(char *str)
6344 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6345 cpulist_parse(str, cpu_isolated_map);
6346 return 1;
6349 __setup("isolcpus=", isolated_cpu_setup);
6352 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6353 * to a function which identifies what group(along with sched group) a CPU
6354 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
6355 * (due to the fact that we keep track of groups covered with a struct cpumask).
6357 * init_sched_build_groups will build a circular linked list of the groups
6358 * covered by the given span, and will set each group's ->cpumask correctly,
6359 * and ->cpu_power to 0.
6361 static void
6362 init_sched_build_groups(const struct cpumask *span,
6363 const struct cpumask *cpu_map,
6364 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
6365 struct sched_group **sg,
6366 struct cpumask *tmpmask),
6367 struct cpumask *covered, struct cpumask *tmpmask)
6369 struct sched_group *first = NULL, *last = NULL;
6370 int i;
6372 cpumask_clear(covered);
6374 for_each_cpu(i, span) {
6375 struct sched_group *sg;
6376 int group = group_fn(i, cpu_map, &sg, tmpmask);
6377 int j;
6379 if (cpumask_test_cpu(i, covered))
6380 continue;
6382 cpumask_clear(sched_group_cpus(sg));
6383 sg->cpu_power = 0;
6385 for_each_cpu(j, span) {
6386 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6387 continue;
6389 cpumask_set_cpu(j, covered);
6390 cpumask_set_cpu(j, sched_group_cpus(sg));
6392 if (!first)
6393 first = sg;
6394 if (last)
6395 last->next = sg;
6396 last = sg;
6398 last->next = first;
6401 #define SD_NODES_PER_DOMAIN 16
6403 #ifdef CONFIG_NUMA
6406 * find_next_best_node - find the next node to include in a sched_domain
6407 * @node: node whose sched_domain we're building
6408 * @used_nodes: nodes already in the sched_domain
6410 * Find the next node to include in a given scheduling domain. Simply
6411 * finds the closest node not already in the @used_nodes map.
6413 * Should use nodemask_t.
6415 static int find_next_best_node(int node, nodemask_t *used_nodes)
6417 int i, n, val, min_val, best_node = 0;
6419 min_val = INT_MAX;
6421 for (i = 0; i < nr_node_ids; i++) {
6422 /* Start at @node */
6423 n = (node + i) % nr_node_ids;
6425 if (!nr_cpus_node(n))
6426 continue;
6428 /* Skip already used nodes */
6429 if (node_isset(n, *used_nodes))
6430 continue;
6432 /* Simple min distance search */
6433 val = node_distance(node, n);
6435 if (val < min_val) {
6436 min_val = val;
6437 best_node = n;
6441 node_set(best_node, *used_nodes);
6442 return best_node;
6446 * sched_domain_node_span - get a cpumask for a node's sched_domain
6447 * @node: node whose cpumask we're constructing
6448 * @span: resulting cpumask
6450 * Given a node, construct a good cpumask for its sched_domain to span. It
6451 * should be one that prevents unnecessary balancing, but also spreads tasks
6452 * out optimally.
6454 static void sched_domain_node_span(int node, struct cpumask *span)
6456 nodemask_t used_nodes;
6457 int i;
6459 cpumask_clear(span);
6460 nodes_clear(used_nodes);
6462 cpumask_or(span, span, cpumask_of_node(node));
6463 node_set(node, used_nodes);
6465 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6466 int next_node = find_next_best_node(node, &used_nodes);
6468 cpumask_or(span, span, cpumask_of_node(next_node));
6471 #endif /* CONFIG_NUMA */
6473 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6476 * The cpus mask in sched_group and sched_domain hangs off the end.
6478 * ( See the the comments in include/linux/sched.h:struct sched_group
6479 * and struct sched_domain. )
6481 struct static_sched_group {
6482 struct sched_group sg;
6483 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
6486 struct static_sched_domain {
6487 struct sched_domain sd;
6488 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
6491 struct s_data {
6492 #ifdef CONFIG_NUMA
6493 int sd_allnodes;
6494 cpumask_var_t domainspan;
6495 cpumask_var_t covered;
6496 cpumask_var_t notcovered;
6497 #endif
6498 cpumask_var_t nodemask;
6499 cpumask_var_t this_sibling_map;
6500 cpumask_var_t this_core_map;
6501 cpumask_var_t send_covered;
6502 cpumask_var_t tmpmask;
6503 struct sched_group **sched_group_nodes;
6504 struct root_domain *rd;
6507 enum s_alloc {
6508 sa_sched_groups = 0,
6509 sa_rootdomain,
6510 sa_tmpmask,
6511 sa_send_covered,
6512 sa_this_core_map,
6513 sa_this_sibling_map,
6514 sa_nodemask,
6515 sa_sched_group_nodes,
6516 #ifdef CONFIG_NUMA
6517 sa_notcovered,
6518 sa_covered,
6519 sa_domainspan,
6520 #endif
6521 sa_none,
6525 * SMT sched-domains:
6527 #ifdef CONFIG_SCHED_SMT
6528 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
6529 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
6531 static int
6532 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
6533 struct sched_group **sg, struct cpumask *unused)
6535 if (sg)
6536 *sg = &per_cpu(sched_groups, cpu).sg;
6537 return cpu;
6539 #endif /* CONFIG_SCHED_SMT */
6542 * multi-core sched-domains:
6544 #ifdef CONFIG_SCHED_MC
6545 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
6546 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
6547 #endif /* CONFIG_SCHED_MC */
6549 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6550 static int
6551 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6552 struct sched_group **sg, struct cpumask *mask)
6554 int group;
6556 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6557 group = cpumask_first(mask);
6558 if (sg)
6559 *sg = &per_cpu(sched_group_core, group).sg;
6560 return group;
6562 #elif defined(CONFIG_SCHED_MC)
6563 static int
6564 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6565 struct sched_group **sg, struct cpumask *unused)
6567 if (sg)
6568 *sg = &per_cpu(sched_group_core, cpu).sg;
6569 return cpu;
6571 #endif
6573 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
6574 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
6576 static int
6577 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
6578 struct sched_group **sg, struct cpumask *mask)
6580 int group;
6581 #ifdef CONFIG_SCHED_MC
6582 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6583 group = cpumask_first(mask);
6584 #elif defined(CONFIG_SCHED_SMT)
6585 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6586 group = cpumask_first(mask);
6587 #else
6588 group = cpu;
6589 #endif
6590 if (sg)
6591 *sg = &per_cpu(sched_group_phys, group).sg;
6592 return group;
6595 #ifdef CONFIG_NUMA
6597 * The init_sched_build_groups can't handle what we want to do with node
6598 * groups, so roll our own. Now each node has its own list of groups which
6599 * gets dynamically allocated.
6601 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
6602 static struct sched_group ***sched_group_nodes_bycpu;
6604 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
6605 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
6607 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
6608 struct sched_group **sg,
6609 struct cpumask *nodemask)
6611 int group;
6613 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
6614 group = cpumask_first(nodemask);
6616 if (sg)
6617 *sg = &per_cpu(sched_group_allnodes, group).sg;
6618 return group;
6621 static void init_numa_sched_groups_power(struct sched_group *group_head)
6623 struct sched_group *sg = group_head;
6624 int j;
6626 if (!sg)
6627 return;
6628 do {
6629 for_each_cpu(j, sched_group_cpus(sg)) {
6630 struct sched_domain *sd;
6632 sd = &per_cpu(phys_domains, j).sd;
6633 if (j != group_first_cpu(sd->groups)) {
6635 * Only add "power" once for each
6636 * physical package.
6638 continue;
6641 sg->cpu_power += sd->groups->cpu_power;
6643 sg = sg->next;
6644 } while (sg != group_head);
6647 static int build_numa_sched_groups(struct s_data *d,
6648 const struct cpumask *cpu_map, int num)
6650 struct sched_domain *sd;
6651 struct sched_group *sg, *prev;
6652 int n, j;
6654 cpumask_clear(d->covered);
6655 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
6656 if (cpumask_empty(d->nodemask)) {
6657 d->sched_group_nodes[num] = NULL;
6658 goto out;
6661 sched_domain_node_span(num, d->domainspan);
6662 cpumask_and(d->domainspan, d->domainspan, cpu_map);
6664 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6665 GFP_KERNEL, num);
6666 if (!sg) {
6667 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
6668 num);
6669 return -ENOMEM;
6671 d->sched_group_nodes[num] = sg;
6673 for_each_cpu(j, d->nodemask) {
6674 sd = &per_cpu(node_domains, j).sd;
6675 sd->groups = sg;
6678 sg->cpu_power = 0;
6679 cpumask_copy(sched_group_cpus(sg), d->nodemask);
6680 sg->next = sg;
6681 cpumask_or(d->covered, d->covered, d->nodemask);
6683 prev = sg;
6684 for (j = 0; j < nr_node_ids; j++) {
6685 n = (num + j) % nr_node_ids;
6686 cpumask_complement(d->notcovered, d->covered);
6687 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
6688 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
6689 if (cpumask_empty(d->tmpmask))
6690 break;
6691 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
6692 if (cpumask_empty(d->tmpmask))
6693 continue;
6694 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6695 GFP_KERNEL, num);
6696 if (!sg) {
6697 printk(KERN_WARNING
6698 "Can not alloc domain group for node %d\n", j);
6699 return -ENOMEM;
6701 sg->cpu_power = 0;
6702 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
6703 sg->next = prev->next;
6704 cpumask_or(d->covered, d->covered, d->tmpmask);
6705 prev->next = sg;
6706 prev = sg;
6708 out:
6709 return 0;
6711 #endif /* CONFIG_NUMA */
6713 #ifdef CONFIG_NUMA
6714 /* Free memory allocated for various sched_group structures */
6715 static void free_sched_groups(const struct cpumask *cpu_map,
6716 struct cpumask *nodemask)
6718 int cpu, i;
6720 for_each_cpu(cpu, cpu_map) {
6721 struct sched_group **sched_group_nodes
6722 = sched_group_nodes_bycpu[cpu];
6724 if (!sched_group_nodes)
6725 continue;
6727 for (i = 0; i < nr_node_ids; i++) {
6728 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6730 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
6731 if (cpumask_empty(nodemask))
6732 continue;
6734 if (sg == NULL)
6735 continue;
6736 sg = sg->next;
6737 next_sg:
6738 oldsg = sg;
6739 sg = sg->next;
6740 kfree(oldsg);
6741 if (oldsg != sched_group_nodes[i])
6742 goto next_sg;
6744 kfree(sched_group_nodes);
6745 sched_group_nodes_bycpu[cpu] = NULL;
6748 #else /* !CONFIG_NUMA */
6749 static void free_sched_groups(const struct cpumask *cpu_map,
6750 struct cpumask *nodemask)
6753 #endif /* CONFIG_NUMA */
6756 * Initialize sched groups cpu_power.
6758 * cpu_power indicates the capacity of sched group, which is used while
6759 * distributing the load between different sched groups in a sched domain.
6760 * Typically cpu_power for all the groups in a sched domain will be same unless
6761 * there are asymmetries in the topology. If there are asymmetries, group
6762 * having more cpu_power will pickup more load compared to the group having
6763 * less cpu_power.
6765 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6767 struct sched_domain *child;
6768 struct sched_group *group;
6769 long power;
6770 int weight;
6772 WARN_ON(!sd || !sd->groups);
6774 if (cpu != group_first_cpu(sd->groups))
6775 return;
6777 child = sd->child;
6779 sd->groups->cpu_power = 0;
6781 if (!child) {
6782 power = SCHED_LOAD_SCALE;
6783 weight = cpumask_weight(sched_domain_span(sd));
6785 * SMT siblings share the power of a single core.
6786 * Usually multiple threads get a better yield out of
6787 * that one core than a single thread would have,
6788 * reflect that in sd->smt_gain.
6790 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
6791 power *= sd->smt_gain;
6792 power /= weight;
6793 power >>= SCHED_LOAD_SHIFT;
6795 sd->groups->cpu_power += power;
6796 return;
6800 * Add cpu_power of each child group to this groups cpu_power.
6802 group = child->groups;
6803 do {
6804 sd->groups->cpu_power += group->cpu_power;
6805 group = group->next;
6806 } while (group != child->groups);
6810 * Initializers for schedule domains
6811 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6814 #ifdef CONFIG_SCHED_DEBUG
6815 # define SD_INIT_NAME(sd, type) sd->name = #type
6816 #else
6817 # define SD_INIT_NAME(sd, type) do { } while (0)
6818 #endif
6820 #define SD_INIT(sd, type) sd_init_##type(sd)
6822 #define SD_INIT_FUNC(type) \
6823 static noinline void sd_init_##type(struct sched_domain *sd) \
6825 memset(sd, 0, sizeof(*sd)); \
6826 *sd = SD_##type##_INIT; \
6827 sd->level = SD_LV_##type; \
6828 SD_INIT_NAME(sd, type); \
6831 SD_INIT_FUNC(CPU)
6832 #ifdef CONFIG_NUMA
6833 SD_INIT_FUNC(ALLNODES)
6834 SD_INIT_FUNC(NODE)
6835 #endif
6836 #ifdef CONFIG_SCHED_SMT
6837 SD_INIT_FUNC(SIBLING)
6838 #endif
6839 #ifdef CONFIG_SCHED_MC
6840 SD_INIT_FUNC(MC)
6841 #endif
6843 static int default_relax_domain_level = -1;
6845 static int __init setup_relax_domain_level(char *str)
6847 unsigned long val;
6849 val = simple_strtoul(str, NULL, 0);
6850 if (val < SD_LV_MAX)
6851 default_relax_domain_level = val;
6853 return 1;
6855 __setup("relax_domain_level=", setup_relax_domain_level);
6857 static void set_domain_attribute(struct sched_domain *sd,
6858 struct sched_domain_attr *attr)
6860 int request;
6862 if (!attr || attr->relax_domain_level < 0) {
6863 if (default_relax_domain_level < 0)
6864 return;
6865 else
6866 request = default_relax_domain_level;
6867 } else
6868 request = attr->relax_domain_level;
6869 if (request < sd->level) {
6870 /* turn off idle balance on this domain */
6871 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6872 } else {
6873 /* turn on idle balance on this domain */
6874 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6878 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6879 const struct cpumask *cpu_map)
6881 switch (what) {
6882 case sa_sched_groups:
6883 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
6884 d->sched_group_nodes = NULL;
6885 case sa_rootdomain:
6886 free_rootdomain(d->rd); /* fall through */
6887 case sa_tmpmask:
6888 free_cpumask_var(d->tmpmask); /* fall through */
6889 case sa_send_covered:
6890 free_cpumask_var(d->send_covered); /* fall through */
6891 case sa_this_core_map:
6892 free_cpumask_var(d->this_core_map); /* fall through */
6893 case sa_this_sibling_map:
6894 free_cpumask_var(d->this_sibling_map); /* fall through */
6895 case sa_nodemask:
6896 free_cpumask_var(d->nodemask); /* fall through */
6897 case sa_sched_group_nodes:
6898 #ifdef CONFIG_NUMA
6899 kfree(d->sched_group_nodes); /* fall through */
6900 case sa_notcovered:
6901 free_cpumask_var(d->notcovered); /* fall through */
6902 case sa_covered:
6903 free_cpumask_var(d->covered); /* fall through */
6904 case sa_domainspan:
6905 free_cpumask_var(d->domainspan); /* fall through */
6906 #endif
6907 case sa_none:
6908 break;
6912 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6913 const struct cpumask *cpu_map)
6915 #ifdef CONFIG_NUMA
6916 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
6917 return sa_none;
6918 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
6919 return sa_domainspan;
6920 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
6921 return sa_covered;
6922 /* Allocate the per-node list of sched groups */
6923 d->sched_group_nodes = kcalloc(nr_node_ids,
6924 sizeof(struct sched_group *), GFP_KERNEL);
6925 if (!d->sched_group_nodes) {
6926 printk(KERN_WARNING "Can not alloc sched group node list\n");
6927 return sa_notcovered;
6929 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
6930 #endif
6931 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
6932 return sa_sched_group_nodes;
6933 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
6934 return sa_nodemask;
6935 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
6936 return sa_this_sibling_map;
6937 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
6938 return sa_this_core_map;
6939 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
6940 return sa_send_covered;
6941 d->rd = alloc_rootdomain();
6942 if (!d->rd) {
6943 printk(KERN_WARNING "Cannot alloc root domain\n");
6944 return sa_tmpmask;
6946 return sa_rootdomain;
6949 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
6950 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
6952 struct sched_domain *sd = NULL;
6953 #ifdef CONFIG_NUMA
6954 struct sched_domain *parent;
6956 d->sd_allnodes = 0;
6957 if (cpumask_weight(cpu_map) >
6958 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
6959 sd = &per_cpu(allnodes_domains, i).sd;
6960 SD_INIT(sd, ALLNODES);
6961 set_domain_attribute(sd, attr);
6962 cpumask_copy(sched_domain_span(sd), cpu_map);
6963 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
6964 d->sd_allnodes = 1;
6966 parent = sd;
6968 sd = &per_cpu(node_domains, i).sd;
6969 SD_INIT(sd, NODE);
6970 set_domain_attribute(sd, attr);
6971 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
6972 sd->parent = parent;
6973 if (parent)
6974 parent->child = sd;
6975 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
6976 #endif
6977 return sd;
6980 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
6981 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6982 struct sched_domain *parent, int i)
6984 struct sched_domain *sd;
6985 sd = &per_cpu(phys_domains, i).sd;
6986 SD_INIT(sd, CPU);
6987 set_domain_attribute(sd, attr);
6988 cpumask_copy(sched_domain_span(sd), d->nodemask);
6989 sd->parent = parent;
6990 if (parent)
6991 parent->child = sd;
6992 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
6993 return sd;
6996 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
6997 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6998 struct sched_domain *parent, int i)
7000 struct sched_domain *sd = parent;
7001 #ifdef CONFIG_SCHED_MC
7002 sd = &per_cpu(core_domains, i).sd;
7003 SD_INIT(sd, MC);
7004 set_domain_attribute(sd, attr);
7005 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
7006 sd->parent = parent;
7007 parent->child = sd;
7008 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
7009 #endif
7010 return sd;
7013 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
7014 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7015 struct sched_domain *parent, int i)
7017 struct sched_domain *sd = parent;
7018 #ifdef CONFIG_SCHED_SMT
7019 sd = &per_cpu(cpu_domains, i).sd;
7020 SD_INIT(sd, SIBLING);
7021 set_domain_attribute(sd, attr);
7022 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
7023 sd->parent = parent;
7024 parent->child = sd;
7025 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
7026 #endif
7027 return sd;
7030 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
7031 const struct cpumask *cpu_map, int cpu)
7033 switch (l) {
7034 #ifdef CONFIG_SCHED_SMT
7035 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
7036 cpumask_and(d->this_sibling_map, cpu_map,
7037 topology_thread_cpumask(cpu));
7038 if (cpu == cpumask_first(d->this_sibling_map))
7039 init_sched_build_groups(d->this_sibling_map, cpu_map,
7040 &cpu_to_cpu_group,
7041 d->send_covered, d->tmpmask);
7042 break;
7043 #endif
7044 #ifdef CONFIG_SCHED_MC
7045 case SD_LV_MC: /* set up multi-core groups */
7046 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
7047 if (cpu == cpumask_first(d->this_core_map))
7048 init_sched_build_groups(d->this_core_map, cpu_map,
7049 &cpu_to_core_group,
7050 d->send_covered, d->tmpmask);
7051 break;
7052 #endif
7053 case SD_LV_CPU: /* set up physical groups */
7054 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
7055 if (!cpumask_empty(d->nodemask))
7056 init_sched_build_groups(d->nodemask, cpu_map,
7057 &cpu_to_phys_group,
7058 d->send_covered, d->tmpmask);
7059 break;
7060 #ifdef CONFIG_NUMA
7061 case SD_LV_ALLNODES:
7062 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
7063 d->send_covered, d->tmpmask);
7064 break;
7065 #endif
7066 default:
7067 break;
7072 * Build sched domains for a given set of cpus and attach the sched domains
7073 * to the individual cpus
7075 static int __build_sched_domains(const struct cpumask *cpu_map,
7076 struct sched_domain_attr *attr)
7078 enum s_alloc alloc_state = sa_none;
7079 struct s_data d;
7080 struct sched_domain *sd;
7081 int i;
7082 #ifdef CONFIG_NUMA
7083 d.sd_allnodes = 0;
7084 #endif
7086 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7087 if (alloc_state != sa_rootdomain)
7088 goto error;
7089 alloc_state = sa_sched_groups;
7092 * Set up domains for cpus specified by the cpu_map.
7094 for_each_cpu(i, cpu_map) {
7095 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
7096 cpu_map);
7098 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
7099 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
7100 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
7101 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
7104 for_each_cpu(i, cpu_map) {
7105 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
7106 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
7109 /* Set up physical groups */
7110 for (i = 0; i < nr_node_ids; i++)
7111 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
7113 #ifdef CONFIG_NUMA
7114 /* Set up node groups */
7115 if (d.sd_allnodes)
7116 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
7118 for (i = 0; i < nr_node_ids; i++)
7119 if (build_numa_sched_groups(&d, cpu_map, i))
7120 goto error;
7121 #endif
7123 /* Calculate CPU power for physical packages and nodes */
7124 #ifdef CONFIG_SCHED_SMT
7125 for_each_cpu(i, cpu_map) {
7126 sd = &per_cpu(cpu_domains, i).sd;
7127 init_sched_groups_power(i, sd);
7129 #endif
7130 #ifdef CONFIG_SCHED_MC
7131 for_each_cpu(i, cpu_map) {
7132 sd = &per_cpu(core_domains, i).sd;
7133 init_sched_groups_power(i, sd);
7135 #endif
7137 for_each_cpu(i, cpu_map) {
7138 sd = &per_cpu(phys_domains, i).sd;
7139 init_sched_groups_power(i, sd);
7142 #ifdef CONFIG_NUMA
7143 for (i = 0; i < nr_node_ids; i++)
7144 init_numa_sched_groups_power(d.sched_group_nodes[i]);
7146 if (d.sd_allnodes) {
7147 struct sched_group *sg;
7149 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7150 d.tmpmask);
7151 init_numa_sched_groups_power(sg);
7153 #endif
7155 /* Attach the domains */
7156 for_each_cpu(i, cpu_map) {
7157 #ifdef CONFIG_SCHED_SMT
7158 sd = &per_cpu(cpu_domains, i).sd;
7159 #elif defined(CONFIG_SCHED_MC)
7160 sd = &per_cpu(core_domains, i).sd;
7161 #else
7162 sd = &per_cpu(phys_domains, i).sd;
7163 #endif
7164 cpu_attach_domain(sd, d.rd, i);
7167 d.sched_group_nodes = NULL; /* don't free this we still need it */
7168 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
7169 return 0;
7171 error:
7172 __free_domain_allocs(&d, alloc_state, cpu_map);
7173 return -ENOMEM;
7176 static int build_sched_domains(const struct cpumask *cpu_map)
7178 return __build_sched_domains(cpu_map, NULL);
7181 static cpumask_var_t *doms_cur; /* current sched domains */
7182 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7183 static struct sched_domain_attr *dattr_cur;
7184 /* attribues of custom domains in 'doms_cur' */
7187 * Special case: If a kmalloc of a doms_cur partition (array of
7188 * cpumask) fails, then fallback to a single sched domain,
7189 * as determined by the single cpumask fallback_doms.
7191 static cpumask_var_t fallback_doms;
7194 * arch_update_cpu_topology lets virtualized architectures update the
7195 * cpu core maps. It is supposed to return 1 if the topology changed
7196 * or 0 if it stayed the same.
7198 int __attribute__((weak)) arch_update_cpu_topology(void)
7200 return 0;
7203 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7205 int i;
7206 cpumask_var_t *doms;
7208 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7209 if (!doms)
7210 return NULL;
7211 for (i = 0; i < ndoms; i++) {
7212 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7213 free_sched_domains(doms, i);
7214 return NULL;
7217 return doms;
7220 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7222 unsigned int i;
7223 for (i = 0; i < ndoms; i++)
7224 free_cpumask_var(doms[i]);
7225 kfree(doms);
7229 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7230 * For now this just excludes isolated cpus, but could be used to
7231 * exclude other special cases in the future.
7233 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7235 int err;
7237 arch_update_cpu_topology();
7238 ndoms_cur = 1;
7239 doms_cur = alloc_sched_domains(ndoms_cur);
7240 if (!doms_cur)
7241 doms_cur = &fallback_doms;
7242 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7243 dattr_cur = NULL;
7244 err = build_sched_domains(doms_cur[0]);
7245 register_sched_domain_sysctl();
7247 return err;
7250 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7251 struct cpumask *tmpmask)
7253 free_sched_groups(cpu_map, tmpmask);
7257 * Detach sched domains from a group of cpus specified in cpu_map
7258 * These cpus will now be attached to the NULL domain
7260 static void detach_destroy_domains(const struct cpumask *cpu_map)
7262 /* Save because hotplug lock held. */
7263 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7264 int i;
7266 for_each_cpu(i, cpu_map)
7267 cpu_attach_domain(NULL, &def_root_domain, i);
7268 synchronize_sched();
7269 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7272 /* handle null as "default" */
7273 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7274 struct sched_domain_attr *new, int idx_new)
7276 struct sched_domain_attr tmp;
7278 /* fast path */
7279 if (!new && !cur)
7280 return 1;
7282 tmp = SD_ATTR_INIT;
7283 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7284 new ? (new + idx_new) : &tmp,
7285 sizeof(struct sched_domain_attr));
7289 * Partition sched domains as specified by the 'ndoms_new'
7290 * cpumasks in the array doms_new[] of cpumasks. This compares
7291 * doms_new[] to the current sched domain partitioning, doms_cur[].
7292 * It destroys each deleted domain and builds each new domain.
7294 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7295 * The masks don't intersect (don't overlap.) We should setup one
7296 * sched domain for each mask. CPUs not in any of the cpumasks will
7297 * not be load balanced. If the same cpumask appears both in the
7298 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7299 * it as it is.
7301 * The passed in 'doms_new' should be allocated using
7302 * alloc_sched_domains. This routine takes ownership of it and will
7303 * free_sched_domains it when done with it. If the caller failed the
7304 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7305 * and partition_sched_domains() will fallback to the single partition
7306 * 'fallback_doms', it also forces the domains to be rebuilt.
7308 * If doms_new == NULL it will be replaced with cpu_online_mask.
7309 * ndoms_new == 0 is a special case for destroying existing domains,
7310 * and it will not create the default domain.
7312 * Call with hotplug lock held
7314 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7315 struct sched_domain_attr *dattr_new)
7317 int i, j, n;
7318 int new_topology;
7320 mutex_lock(&sched_domains_mutex);
7322 /* always unregister in case we don't destroy any domains */
7323 unregister_sched_domain_sysctl();
7325 /* Let architecture update cpu core mappings. */
7326 new_topology = arch_update_cpu_topology();
7328 n = doms_new ? ndoms_new : 0;
7330 /* Destroy deleted domains */
7331 for (i = 0; i < ndoms_cur; i++) {
7332 for (j = 0; j < n && !new_topology; j++) {
7333 if (cpumask_equal(doms_cur[i], doms_new[j])
7334 && dattrs_equal(dattr_cur, i, dattr_new, j))
7335 goto match1;
7337 /* no match - a current sched domain not in new doms_new[] */
7338 detach_destroy_domains(doms_cur[i]);
7339 match1:
7343 if (doms_new == NULL) {
7344 ndoms_cur = 0;
7345 doms_new = &fallback_doms;
7346 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7347 WARN_ON_ONCE(dattr_new);
7350 /* Build new domains */
7351 for (i = 0; i < ndoms_new; i++) {
7352 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7353 if (cpumask_equal(doms_new[i], doms_cur[j])
7354 && dattrs_equal(dattr_new, i, dattr_cur, j))
7355 goto match2;
7357 /* no match - add a new doms_new */
7358 __build_sched_domains(doms_new[i],
7359 dattr_new ? dattr_new + i : NULL);
7360 match2:
7364 /* Remember the new sched domains */
7365 if (doms_cur != &fallback_doms)
7366 free_sched_domains(doms_cur, ndoms_cur);
7367 kfree(dattr_cur); /* kfree(NULL) is safe */
7368 doms_cur = doms_new;
7369 dattr_cur = dattr_new;
7370 ndoms_cur = ndoms_new;
7372 register_sched_domain_sysctl();
7374 mutex_unlock(&sched_domains_mutex);
7377 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7378 static void arch_reinit_sched_domains(void)
7380 get_online_cpus();
7382 /* Destroy domains first to force the rebuild */
7383 partition_sched_domains(0, NULL, NULL);
7385 rebuild_sched_domains();
7386 put_online_cpus();
7389 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7391 unsigned int level = 0;
7393 if (sscanf(buf, "%u", &level) != 1)
7394 return -EINVAL;
7397 * level is always be positive so don't check for
7398 * level < POWERSAVINGS_BALANCE_NONE which is 0
7399 * What happens on 0 or 1 byte write,
7400 * need to check for count as well?
7403 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7404 return -EINVAL;
7406 if (smt)
7407 sched_smt_power_savings = level;
7408 else
7409 sched_mc_power_savings = level;
7411 arch_reinit_sched_domains();
7413 return count;
7416 #ifdef CONFIG_SCHED_MC
7417 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7418 struct sysdev_class_attribute *attr,
7419 char *page)
7421 return sprintf(page, "%u\n", sched_mc_power_savings);
7423 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7424 struct sysdev_class_attribute *attr,
7425 const char *buf, size_t count)
7427 return sched_power_savings_store(buf, count, 0);
7429 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7430 sched_mc_power_savings_show,
7431 sched_mc_power_savings_store);
7432 #endif
7434 #ifdef CONFIG_SCHED_SMT
7435 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7436 struct sysdev_class_attribute *attr,
7437 char *page)
7439 return sprintf(page, "%u\n", sched_smt_power_savings);
7441 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7442 struct sysdev_class_attribute *attr,
7443 const char *buf, size_t count)
7445 return sched_power_savings_store(buf, count, 1);
7447 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7448 sched_smt_power_savings_show,
7449 sched_smt_power_savings_store);
7450 #endif
7452 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7454 int err = 0;
7456 #ifdef CONFIG_SCHED_SMT
7457 if (smt_capable())
7458 err = sysfs_create_file(&cls->kset.kobj,
7459 &attr_sched_smt_power_savings.attr);
7460 #endif
7461 #ifdef CONFIG_SCHED_MC
7462 if (!err && mc_capable())
7463 err = sysfs_create_file(&cls->kset.kobj,
7464 &attr_sched_mc_power_savings.attr);
7465 #endif
7466 return err;
7468 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7470 #ifndef CONFIG_CPUSETS
7472 * Add online and remove offline CPUs from the scheduler domains.
7473 * When cpusets are enabled they take over this function.
7475 static int update_sched_domains(struct notifier_block *nfb,
7476 unsigned long action, void *hcpu)
7478 switch (action) {
7479 case CPU_ONLINE:
7480 case CPU_ONLINE_FROZEN:
7481 case CPU_DOWN_PREPARE:
7482 case CPU_DOWN_PREPARE_FROZEN:
7483 case CPU_DOWN_FAILED:
7484 case CPU_DOWN_FAILED_FROZEN:
7485 partition_sched_domains(1, NULL, NULL);
7486 return NOTIFY_OK;
7488 default:
7489 return NOTIFY_DONE;
7492 #endif
7494 static int update_runtime(struct notifier_block *nfb,
7495 unsigned long action, void *hcpu)
7497 int cpu = (int)(long)hcpu;
7499 switch (action) {
7500 case CPU_DOWN_PREPARE:
7501 case CPU_DOWN_PREPARE_FROZEN:
7502 disable_runtime(cpu_rq(cpu));
7503 return NOTIFY_OK;
7505 case CPU_DOWN_FAILED:
7506 case CPU_DOWN_FAILED_FROZEN:
7507 case CPU_ONLINE:
7508 case CPU_ONLINE_FROZEN:
7509 enable_runtime(cpu_rq(cpu));
7510 return NOTIFY_OK;
7512 default:
7513 return NOTIFY_DONE;
7517 void __init sched_init_smp(void)
7519 cpumask_var_t non_isolated_cpus;
7521 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7522 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7524 #if defined(CONFIG_NUMA)
7525 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7526 GFP_KERNEL);
7527 BUG_ON(sched_group_nodes_bycpu == NULL);
7528 #endif
7529 get_online_cpus();
7530 mutex_lock(&sched_domains_mutex);
7531 arch_init_sched_domains(cpu_active_mask);
7532 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7533 if (cpumask_empty(non_isolated_cpus))
7534 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7535 mutex_unlock(&sched_domains_mutex);
7536 put_online_cpus();
7538 #ifndef CONFIG_CPUSETS
7539 /* XXX: Theoretical race here - CPU may be hotplugged now */
7540 hotcpu_notifier(update_sched_domains, 0);
7541 #endif
7543 /* RT runtime code needs to handle some hotplug events */
7544 hotcpu_notifier(update_runtime, 0);
7546 init_hrtick();
7548 /* Move init over to a non-isolated CPU */
7549 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7550 BUG();
7551 sched_init_granularity();
7552 free_cpumask_var(non_isolated_cpus);
7554 init_sched_rt_class();
7556 #else
7557 void __init sched_init_smp(void)
7559 sched_init_granularity();
7561 #endif /* CONFIG_SMP */
7563 const_debug unsigned int sysctl_timer_migration = 1;
7565 int in_sched_functions(unsigned long addr)
7567 return in_lock_functions(addr) ||
7568 (addr >= (unsigned long)__sched_text_start
7569 && addr < (unsigned long)__sched_text_end);
7572 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7574 cfs_rq->tasks_timeline = RB_ROOT;
7575 INIT_LIST_HEAD(&cfs_rq->tasks);
7576 #ifdef CONFIG_FAIR_GROUP_SCHED
7577 cfs_rq->rq = rq;
7578 #endif
7579 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7582 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7584 struct rt_prio_array *array;
7585 int i;
7587 array = &rt_rq->active;
7588 for (i = 0; i < MAX_RT_PRIO; i++) {
7589 INIT_LIST_HEAD(array->queue + i);
7590 __clear_bit(i, array->bitmap);
7592 /* delimiter for bitsearch: */
7593 __set_bit(MAX_RT_PRIO, array->bitmap);
7595 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7596 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7597 #ifdef CONFIG_SMP
7598 rt_rq->highest_prio.next = MAX_RT_PRIO;
7599 #endif
7600 #endif
7601 #ifdef CONFIG_SMP
7602 rt_rq->rt_nr_migratory = 0;
7603 rt_rq->overloaded = 0;
7604 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
7605 #endif
7607 rt_rq->rt_time = 0;
7608 rt_rq->rt_throttled = 0;
7609 rt_rq->rt_runtime = 0;
7610 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7612 #ifdef CONFIG_RT_GROUP_SCHED
7613 rt_rq->rt_nr_boosted = 0;
7614 rt_rq->rq = rq;
7615 #endif
7618 #ifdef CONFIG_FAIR_GROUP_SCHED
7619 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7620 struct sched_entity *se, int cpu, int add,
7621 struct sched_entity *parent)
7623 struct rq *rq = cpu_rq(cpu);
7624 tg->cfs_rq[cpu] = cfs_rq;
7625 init_cfs_rq(cfs_rq, rq);
7626 cfs_rq->tg = tg;
7627 if (add)
7628 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7630 tg->se[cpu] = se;
7631 /* se could be NULL for init_task_group */
7632 if (!se)
7633 return;
7635 if (!parent)
7636 se->cfs_rq = &rq->cfs;
7637 else
7638 se->cfs_rq = parent->my_q;
7640 se->my_q = cfs_rq;
7641 se->load.weight = tg->shares;
7642 se->load.inv_weight = 0;
7643 se->parent = parent;
7645 #endif
7647 #ifdef CONFIG_RT_GROUP_SCHED
7648 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7649 struct sched_rt_entity *rt_se, int cpu, int add,
7650 struct sched_rt_entity *parent)
7652 struct rq *rq = cpu_rq(cpu);
7654 tg->rt_rq[cpu] = rt_rq;
7655 init_rt_rq(rt_rq, rq);
7656 rt_rq->tg = tg;
7657 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7658 if (add)
7659 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7661 tg->rt_se[cpu] = rt_se;
7662 if (!rt_se)
7663 return;
7665 if (!parent)
7666 rt_se->rt_rq = &rq->rt;
7667 else
7668 rt_se->rt_rq = parent->my_q;
7670 rt_se->my_q = rt_rq;
7671 rt_se->parent = parent;
7672 INIT_LIST_HEAD(&rt_se->run_list);
7674 #endif
7676 void __init sched_init(void)
7678 int i, j;
7679 unsigned long alloc_size = 0, ptr;
7681 #ifdef CONFIG_FAIR_GROUP_SCHED
7682 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7683 #endif
7684 #ifdef CONFIG_RT_GROUP_SCHED
7685 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7686 #endif
7687 #ifdef CONFIG_CPUMASK_OFFSTACK
7688 alloc_size += num_possible_cpus() * cpumask_size();
7689 #endif
7690 if (alloc_size) {
7691 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7693 #ifdef CONFIG_FAIR_GROUP_SCHED
7694 init_task_group.se = (struct sched_entity **)ptr;
7695 ptr += nr_cpu_ids * sizeof(void **);
7697 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7698 ptr += nr_cpu_ids * sizeof(void **);
7700 #endif /* CONFIG_FAIR_GROUP_SCHED */
7701 #ifdef CONFIG_RT_GROUP_SCHED
7702 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7703 ptr += nr_cpu_ids * sizeof(void **);
7705 init_task_group.rt_rq = (struct rt_rq **)ptr;
7706 ptr += nr_cpu_ids * sizeof(void **);
7708 #endif /* CONFIG_RT_GROUP_SCHED */
7709 #ifdef CONFIG_CPUMASK_OFFSTACK
7710 for_each_possible_cpu(i) {
7711 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
7712 ptr += cpumask_size();
7714 #endif /* CONFIG_CPUMASK_OFFSTACK */
7717 #ifdef CONFIG_SMP
7718 init_defrootdomain();
7719 #endif
7721 init_rt_bandwidth(&def_rt_bandwidth,
7722 global_rt_period(), global_rt_runtime());
7724 #ifdef CONFIG_RT_GROUP_SCHED
7725 init_rt_bandwidth(&init_task_group.rt_bandwidth,
7726 global_rt_period(), global_rt_runtime());
7727 #endif /* CONFIG_RT_GROUP_SCHED */
7729 #ifdef CONFIG_CGROUP_SCHED
7730 list_add(&init_task_group.list, &task_groups);
7731 INIT_LIST_HEAD(&init_task_group.children);
7733 #endif /* CONFIG_CGROUP_SCHED */
7735 #if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP
7736 update_shares_data = __alloc_percpu(nr_cpu_ids * sizeof(unsigned long),
7737 __alignof__(unsigned long));
7738 #endif
7739 for_each_possible_cpu(i) {
7740 struct rq *rq;
7742 rq = cpu_rq(i);
7743 raw_spin_lock_init(&rq->lock);
7744 rq->nr_running = 0;
7745 rq->calc_load_active = 0;
7746 rq->calc_load_update = jiffies + LOAD_FREQ;
7747 init_cfs_rq(&rq->cfs, rq);
7748 init_rt_rq(&rq->rt, rq);
7749 #ifdef CONFIG_FAIR_GROUP_SCHED
7750 init_task_group.shares = init_task_group_load;
7751 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7752 #ifdef CONFIG_CGROUP_SCHED
7754 * How much cpu bandwidth does init_task_group get?
7756 * In case of task-groups formed thr' the cgroup filesystem, it
7757 * gets 100% of the cpu resources in the system. This overall
7758 * system cpu resource is divided among the tasks of
7759 * init_task_group and its child task-groups in a fair manner,
7760 * based on each entity's (task or task-group's) weight
7761 * (se->load.weight).
7763 * In other words, if init_task_group has 10 tasks of weight
7764 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7765 * then A0's share of the cpu resource is:
7767 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7769 * We achieve this by letting init_task_group's tasks sit
7770 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7772 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
7773 #endif
7774 #endif /* CONFIG_FAIR_GROUP_SCHED */
7776 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7777 #ifdef CONFIG_RT_GROUP_SCHED
7778 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7779 #ifdef CONFIG_CGROUP_SCHED
7780 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
7781 #endif
7782 #endif
7784 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7785 rq->cpu_load[j] = 0;
7786 #ifdef CONFIG_SMP
7787 rq->sd = NULL;
7788 rq->rd = NULL;
7789 rq->cpu_power = SCHED_LOAD_SCALE;
7790 rq->post_schedule = 0;
7791 rq->active_balance = 0;
7792 rq->next_balance = jiffies;
7793 rq->push_cpu = 0;
7794 rq->cpu = i;
7795 rq->online = 0;
7796 rq->migration_thread = NULL;
7797 rq->idle_stamp = 0;
7798 rq->avg_idle = 2*sysctl_sched_migration_cost;
7799 INIT_LIST_HEAD(&rq->migration_queue);
7800 rq_attach_root(rq, &def_root_domain);
7801 #endif
7802 init_rq_hrtick(rq);
7803 atomic_set(&rq->nr_iowait, 0);
7806 set_load_weight(&init_task);
7808 #ifdef CONFIG_PREEMPT_NOTIFIERS
7809 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7810 #endif
7812 #ifdef CONFIG_SMP
7813 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7814 #endif
7816 #ifdef CONFIG_RT_MUTEXES
7817 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
7818 #endif
7821 * The boot idle thread does lazy MMU switching as well:
7823 atomic_inc(&init_mm.mm_count);
7824 enter_lazy_tlb(&init_mm, current);
7827 * Make us the idle thread. Technically, schedule() should not be
7828 * called from this thread, however somewhere below it might be,
7829 * but because we are the idle thread, we just pick up running again
7830 * when this runqueue becomes "idle".
7832 init_idle(current, smp_processor_id());
7834 calc_load_update = jiffies + LOAD_FREQ;
7837 * During early bootup we pretend to be a normal task:
7839 current->sched_class = &fair_sched_class;
7841 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
7842 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
7843 #ifdef CONFIG_SMP
7844 #ifdef CONFIG_NO_HZ
7845 zalloc_cpumask_var(&nohz.cpu_mask, GFP_NOWAIT);
7846 alloc_cpumask_var(&nohz.ilb_grp_nohz_mask, GFP_NOWAIT);
7847 #endif
7848 /* May be allocated at isolcpus cmdline parse time */
7849 if (cpu_isolated_map == NULL)
7850 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7851 #endif /* SMP */
7853 perf_event_init();
7855 scheduler_running = 1;
7858 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7859 static inline int preempt_count_equals(int preempt_offset)
7861 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7863 return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
7866 void __might_sleep(const char *file, int line, int preempt_offset)
7868 #ifdef in_atomic
7869 static unsigned long prev_jiffy; /* ratelimiting */
7871 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7872 system_state != SYSTEM_RUNNING || oops_in_progress)
7873 return;
7874 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7875 return;
7876 prev_jiffy = jiffies;
7878 printk(KERN_ERR
7879 "BUG: sleeping function called from invalid context at %s:%d\n",
7880 file, line);
7881 printk(KERN_ERR
7882 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7883 in_atomic(), irqs_disabled(),
7884 current->pid, current->comm);
7886 debug_show_held_locks(current);
7887 if (irqs_disabled())
7888 print_irqtrace_events(current);
7889 dump_stack();
7890 #endif
7892 EXPORT_SYMBOL(__might_sleep);
7893 #endif
7895 #ifdef CONFIG_MAGIC_SYSRQ
7896 static void normalize_task(struct rq *rq, struct task_struct *p)
7898 int on_rq;
7900 update_rq_clock(rq);
7901 on_rq = p->se.on_rq;
7902 if (on_rq)
7903 deactivate_task(rq, p, 0);
7904 __setscheduler(rq, p, SCHED_NORMAL, 0);
7905 if (on_rq) {
7906 activate_task(rq, p, 0);
7907 resched_task(rq->curr);
7911 void normalize_rt_tasks(void)
7913 struct task_struct *g, *p;
7914 unsigned long flags;
7915 struct rq *rq;
7917 read_lock_irqsave(&tasklist_lock, flags);
7918 do_each_thread(g, p) {
7920 * Only normalize user tasks:
7922 if (!p->mm)
7923 continue;
7925 p->se.exec_start = 0;
7926 #ifdef CONFIG_SCHEDSTATS
7927 p->se.wait_start = 0;
7928 p->se.sleep_start = 0;
7929 p->se.block_start = 0;
7930 #endif
7932 if (!rt_task(p)) {
7934 * Renice negative nice level userspace
7935 * tasks back to 0:
7937 if (TASK_NICE(p) < 0 && p->mm)
7938 set_user_nice(p, 0);
7939 continue;
7942 raw_spin_lock(&p->pi_lock);
7943 rq = __task_rq_lock(p);
7945 normalize_task(rq, p);
7947 __task_rq_unlock(rq);
7948 raw_spin_unlock(&p->pi_lock);
7949 } while_each_thread(g, p);
7951 read_unlock_irqrestore(&tasklist_lock, flags);
7954 #endif /* CONFIG_MAGIC_SYSRQ */
7956 #ifdef CONFIG_IA64
7958 * These functions are only useful for the IA64 MCA handling.
7960 * They can only be called when the whole system has been
7961 * stopped - every CPU needs to be quiescent, and no scheduling
7962 * activity can take place. Using them for anything else would
7963 * be a serious bug, and as a result, they aren't even visible
7964 * under any other configuration.
7968 * curr_task - return the current task for a given cpu.
7969 * @cpu: the processor in question.
7971 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7973 struct task_struct *curr_task(int cpu)
7975 return cpu_curr(cpu);
7979 * set_curr_task - set the current task for a given cpu.
7980 * @cpu: the processor in question.
7981 * @p: the task pointer to set.
7983 * Description: This function must only be used when non-maskable interrupts
7984 * are serviced on a separate stack. It allows the architecture to switch the
7985 * notion of the current task on a cpu in a non-blocking manner. This function
7986 * must be called with all CPU's synchronized, and interrupts disabled, the
7987 * and caller must save the original value of the current task (see
7988 * curr_task() above) and restore that value before reenabling interrupts and
7989 * re-starting the system.
7991 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7993 void set_curr_task(int cpu, struct task_struct *p)
7995 cpu_curr(cpu) = p;
7998 #endif
8000 #ifdef CONFIG_FAIR_GROUP_SCHED
8001 static void free_fair_sched_group(struct task_group *tg)
8003 int i;
8005 for_each_possible_cpu(i) {
8006 if (tg->cfs_rq)
8007 kfree(tg->cfs_rq[i]);
8008 if (tg->se)
8009 kfree(tg->se[i]);
8012 kfree(tg->cfs_rq);
8013 kfree(tg->se);
8016 static
8017 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8019 struct cfs_rq *cfs_rq;
8020 struct sched_entity *se;
8021 struct rq *rq;
8022 int i;
8024 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8025 if (!tg->cfs_rq)
8026 goto err;
8027 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8028 if (!tg->se)
8029 goto err;
8031 tg->shares = NICE_0_LOAD;
8033 for_each_possible_cpu(i) {
8034 rq = cpu_rq(i);
8036 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8037 GFP_KERNEL, cpu_to_node(i));
8038 if (!cfs_rq)
8039 goto err;
8041 se = kzalloc_node(sizeof(struct sched_entity),
8042 GFP_KERNEL, cpu_to_node(i));
8043 if (!se)
8044 goto err_free_rq;
8046 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
8049 return 1;
8051 err_free_rq:
8052 kfree(cfs_rq);
8053 err:
8054 return 0;
8057 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8059 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8060 &cpu_rq(cpu)->leaf_cfs_rq_list);
8063 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8065 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8067 #else /* !CONFG_FAIR_GROUP_SCHED */
8068 static inline void free_fair_sched_group(struct task_group *tg)
8072 static inline
8073 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8075 return 1;
8078 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8082 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8085 #endif /* CONFIG_FAIR_GROUP_SCHED */
8087 #ifdef CONFIG_RT_GROUP_SCHED
8088 static void free_rt_sched_group(struct task_group *tg)
8090 int i;
8092 destroy_rt_bandwidth(&tg->rt_bandwidth);
8094 for_each_possible_cpu(i) {
8095 if (tg->rt_rq)
8096 kfree(tg->rt_rq[i]);
8097 if (tg->rt_se)
8098 kfree(tg->rt_se[i]);
8101 kfree(tg->rt_rq);
8102 kfree(tg->rt_se);
8105 static
8106 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8108 struct rt_rq *rt_rq;
8109 struct sched_rt_entity *rt_se;
8110 struct rq *rq;
8111 int i;
8113 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8114 if (!tg->rt_rq)
8115 goto err;
8116 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8117 if (!tg->rt_se)
8118 goto err;
8120 init_rt_bandwidth(&tg->rt_bandwidth,
8121 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8123 for_each_possible_cpu(i) {
8124 rq = cpu_rq(i);
8126 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8127 GFP_KERNEL, cpu_to_node(i));
8128 if (!rt_rq)
8129 goto err;
8131 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8132 GFP_KERNEL, cpu_to_node(i));
8133 if (!rt_se)
8134 goto err_free_rq;
8136 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
8139 return 1;
8141 err_free_rq:
8142 kfree(rt_rq);
8143 err:
8144 return 0;
8147 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8149 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8150 &cpu_rq(cpu)->leaf_rt_rq_list);
8153 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8155 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8157 #else /* !CONFIG_RT_GROUP_SCHED */
8158 static inline void free_rt_sched_group(struct task_group *tg)
8162 static inline
8163 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8165 return 1;
8168 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8172 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8175 #endif /* CONFIG_RT_GROUP_SCHED */
8177 #ifdef CONFIG_CGROUP_SCHED
8178 static void free_sched_group(struct task_group *tg)
8180 free_fair_sched_group(tg);
8181 free_rt_sched_group(tg);
8182 kfree(tg);
8185 /* allocate runqueue etc for a new task group */
8186 struct task_group *sched_create_group(struct task_group *parent)
8188 struct task_group *tg;
8189 unsigned long flags;
8190 int i;
8192 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8193 if (!tg)
8194 return ERR_PTR(-ENOMEM);
8196 if (!alloc_fair_sched_group(tg, parent))
8197 goto err;
8199 if (!alloc_rt_sched_group(tg, parent))
8200 goto err;
8202 spin_lock_irqsave(&task_group_lock, flags);
8203 for_each_possible_cpu(i) {
8204 register_fair_sched_group(tg, i);
8205 register_rt_sched_group(tg, i);
8207 list_add_rcu(&tg->list, &task_groups);
8209 WARN_ON(!parent); /* root should already exist */
8211 tg->parent = parent;
8212 INIT_LIST_HEAD(&tg->children);
8213 list_add_rcu(&tg->siblings, &parent->children);
8214 spin_unlock_irqrestore(&task_group_lock, flags);
8216 return tg;
8218 err:
8219 free_sched_group(tg);
8220 return ERR_PTR(-ENOMEM);
8223 /* rcu callback to free various structures associated with a task group */
8224 static void free_sched_group_rcu(struct rcu_head *rhp)
8226 /* now it should be safe to free those cfs_rqs */
8227 free_sched_group(container_of(rhp, struct task_group, rcu));
8230 /* Destroy runqueue etc associated with a task group */
8231 void sched_destroy_group(struct task_group *tg)
8233 unsigned long flags;
8234 int i;
8236 spin_lock_irqsave(&task_group_lock, flags);
8237 for_each_possible_cpu(i) {
8238 unregister_fair_sched_group(tg, i);
8239 unregister_rt_sched_group(tg, i);
8241 list_del_rcu(&tg->list);
8242 list_del_rcu(&tg->siblings);
8243 spin_unlock_irqrestore(&task_group_lock, flags);
8245 /* wait for possible concurrent references to cfs_rqs complete */
8246 call_rcu(&tg->rcu, free_sched_group_rcu);
8249 /* change task's runqueue when it moves between groups.
8250 * The caller of this function should have put the task in its new group
8251 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8252 * reflect its new group.
8254 void sched_move_task(struct task_struct *tsk)
8256 int on_rq, running;
8257 unsigned long flags;
8258 struct rq *rq;
8260 rq = task_rq_lock(tsk, &flags);
8262 update_rq_clock(rq);
8264 running = task_current(rq, tsk);
8265 on_rq = tsk->se.on_rq;
8267 if (on_rq)
8268 dequeue_task(rq, tsk, 0);
8269 if (unlikely(running))
8270 tsk->sched_class->put_prev_task(rq, tsk);
8272 #ifdef CONFIG_FAIR_GROUP_SCHED
8273 if (tsk->sched_class->task_move_group)
8274 tsk->sched_class->task_move_group(tsk, on_rq);
8275 else
8276 #endif
8277 set_task_rq(tsk, task_cpu(tsk));
8279 if (unlikely(running))
8280 tsk->sched_class->set_curr_task(rq);
8281 if (on_rq)
8282 enqueue_task(rq, tsk, 0, false);
8284 task_rq_unlock(rq, &flags);
8286 #endif /* CONFIG_CGROUP_SCHED */
8288 #ifdef CONFIG_FAIR_GROUP_SCHED
8289 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8291 struct cfs_rq *cfs_rq = se->cfs_rq;
8292 int on_rq;
8294 on_rq = se->on_rq;
8295 if (on_rq)
8296 dequeue_entity(cfs_rq, se, 0);
8298 se->load.weight = shares;
8299 se->load.inv_weight = 0;
8301 if (on_rq)
8302 enqueue_entity(cfs_rq, se, 0);
8305 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8307 struct cfs_rq *cfs_rq = se->cfs_rq;
8308 struct rq *rq = cfs_rq->rq;
8309 unsigned long flags;
8311 raw_spin_lock_irqsave(&rq->lock, flags);
8312 __set_se_shares(se, shares);
8313 raw_spin_unlock_irqrestore(&rq->lock, flags);
8316 static DEFINE_MUTEX(shares_mutex);
8318 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8320 int i;
8321 unsigned long flags;
8324 * We can't change the weight of the root cgroup.
8326 if (!tg->se[0])
8327 return -EINVAL;
8329 if (shares < MIN_SHARES)
8330 shares = MIN_SHARES;
8331 else if (shares > MAX_SHARES)
8332 shares = MAX_SHARES;
8334 mutex_lock(&shares_mutex);
8335 if (tg->shares == shares)
8336 goto done;
8338 spin_lock_irqsave(&task_group_lock, flags);
8339 for_each_possible_cpu(i)
8340 unregister_fair_sched_group(tg, i);
8341 list_del_rcu(&tg->siblings);
8342 spin_unlock_irqrestore(&task_group_lock, flags);
8344 /* wait for any ongoing reference to this group to finish */
8345 synchronize_sched();
8348 * Now we are free to modify the group's share on each cpu
8349 * w/o tripping rebalance_share or load_balance_fair.
8351 tg->shares = shares;
8352 for_each_possible_cpu(i) {
8354 * force a rebalance
8356 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8357 set_se_shares(tg->se[i], shares);
8361 * Enable load balance activity on this group, by inserting it back on
8362 * each cpu's rq->leaf_cfs_rq_list.
8364 spin_lock_irqsave(&task_group_lock, flags);
8365 for_each_possible_cpu(i)
8366 register_fair_sched_group(tg, i);
8367 list_add_rcu(&tg->siblings, &tg->parent->children);
8368 spin_unlock_irqrestore(&task_group_lock, flags);
8369 done:
8370 mutex_unlock(&shares_mutex);
8371 return 0;
8374 unsigned long sched_group_shares(struct task_group *tg)
8376 return tg->shares;
8378 #endif
8380 #ifdef CONFIG_RT_GROUP_SCHED
8382 * Ensure that the real time constraints are schedulable.
8384 static DEFINE_MUTEX(rt_constraints_mutex);
8386 static unsigned long to_ratio(u64 period, u64 runtime)
8388 if (runtime == RUNTIME_INF)
8389 return 1ULL << 20;
8391 return div64_u64(runtime << 20, period);
8394 /* Must be called with tasklist_lock held */
8395 static inline int tg_has_rt_tasks(struct task_group *tg)
8397 struct task_struct *g, *p;
8399 do_each_thread(g, p) {
8400 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8401 return 1;
8402 } while_each_thread(g, p);
8404 return 0;
8407 struct rt_schedulable_data {
8408 struct task_group *tg;
8409 u64 rt_period;
8410 u64 rt_runtime;
8413 static int tg_schedulable(struct task_group *tg, void *data)
8415 struct rt_schedulable_data *d = data;
8416 struct task_group *child;
8417 unsigned long total, sum = 0;
8418 u64 period, runtime;
8420 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8421 runtime = tg->rt_bandwidth.rt_runtime;
8423 if (tg == d->tg) {
8424 period = d->rt_period;
8425 runtime = d->rt_runtime;
8429 * Cannot have more runtime than the period.
8431 if (runtime > period && runtime != RUNTIME_INF)
8432 return -EINVAL;
8435 * Ensure we don't starve existing RT tasks.
8437 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8438 return -EBUSY;
8440 total = to_ratio(period, runtime);
8443 * Nobody can have more than the global setting allows.
8445 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8446 return -EINVAL;
8449 * The sum of our children's runtime should not exceed our own.
8451 list_for_each_entry_rcu(child, &tg->children, siblings) {
8452 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8453 runtime = child->rt_bandwidth.rt_runtime;
8455 if (child == d->tg) {
8456 period = d->rt_period;
8457 runtime = d->rt_runtime;
8460 sum += to_ratio(period, runtime);
8463 if (sum > total)
8464 return -EINVAL;
8466 return 0;
8469 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8471 struct rt_schedulable_data data = {
8472 .tg = tg,
8473 .rt_period = period,
8474 .rt_runtime = runtime,
8477 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8480 static int tg_set_bandwidth(struct task_group *tg,
8481 u64 rt_period, u64 rt_runtime)
8483 int i, err = 0;
8485 mutex_lock(&rt_constraints_mutex);
8486 read_lock(&tasklist_lock);
8487 err = __rt_schedulable(tg, rt_period, rt_runtime);
8488 if (err)
8489 goto unlock;
8491 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8492 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8493 tg->rt_bandwidth.rt_runtime = rt_runtime;
8495 for_each_possible_cpu(i) {
8496 struct rt_rq *rt_rq = tg->rt_rq[i];
8498 raw_spin_lock(&rt_rq->rt_runtime_lock);
8499 rt_rq->rt_runtime = rt_runtime;
8500 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8502 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8503 unlock:
8504 read_unlock(&tasklist_lock);
8505 mutex_unlock(&rt_constraints_mutex);
8507 return err;
8510 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8512 u64 rt_runtime, rt_period;
8514 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8515 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8516 if (rt_runtime_us < 0)
8517 rt_runtime = RUNTIME_INF;
8519 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8522 long sched_group_rt_runtime(struct task_group *tg)
8524 u64 rt_runtime_us;
8526 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8527 return -1;
8529 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8530 do_div(rt_runtime_us, NSEC_PER_USEC);
8531 return rt_runtime_us;
8534 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8536 u64 rt_runtime, rt_period;
8538 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8539 rt_runtime = tg->rt_bandwidth.rt_runtime;
8541 if (rt_period == 0)
8542 return -EINVAL;
8544 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8547 long sched_group_rt_period(struct task_group *tg)
8549 u64 rt_period_us;
8551 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8552 do_div(rt_period_us, NSEC_PER_USEC);
8553 return rt_period_us;
8556 static int sched_rt_global_constraints(void)
8558 u64 runtime, period;
8559 int ret = 0;
8561 if (sysctl_sched_rt_period <= 0)
8562 return -EINVAL;
8564 runtime = global_rt_runtime();
8565 period = global_rt_period();
8568 * Sanity check on the sysctl variables.
8570 if (runtime > period && runtime != RUNTIME_INF)
8571 return -EINVAL;
8573 mutex_lock(&rt_constraints_mutex);
8574 read_lock(&tasklist_lock);
8575 ret = __rt_schedulable(NULL, 0, 0);
8576 read_unlock(&tasklist_lock);
8577 mutex_unlock(&rt_constraints_mutex);
8579 return ret;
8582 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8584 /* Don't accept realtime tasks when there is no way for them to run */
8585 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8586 return 0;
8588 return 1;
8591 #else /* !CONFIG_RT_GROUP_SCHED */
8592 static int sched_rt_global_constraints(void)
8594 unsigned long flags;
8595 int i;
8597 if (sysctl_sched_rt_period <= 0)
8598 return -EINVAL;
8601 * There's always some RT tasks in the root group
8602 * -- migration, kstopmachine etc..
8604 if (sysctl_sched_rt_runtime == 0)
8605 return -EBUSY;
8607 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8608 for_each_possible_cpu(i) {
8609 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8611 raw_spin_lock(&rt_rq->rt_runtime_lock);
8612 rt_rq->rt_runtime = global_rt_runtime();
8613 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8615 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8617 return 0;
8619 #endif /* CONFIG_RT_GROUP_SCHED */
8621 int sched_rt_handler(struct ctl_table *table, int write,
8622 void __user *buffer, size_t *lenp,
8623 loff_t *ppos)
8625 int ret;
8626 int old_period, old_runtime;
8627 static DEFINE_MUTEX(mutex);
8629 mutex_lock(&mutex);
8630 old_period = sysctl_sched_rt_period;
8631 old_runtime = sysctl_sched_rt_runtime;
8633 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8635 if (!ret && write) {
8636 ret = sched_rt_global_constraints();
8637 if (ret) {
8638 sysctl_sched_rt_period = old_period;
8639 sysctl_sched_rt_runtime = old_runtime;
8640 } else {
8641 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8642 def_rt_bandwidth.rt_period =
8643 ns_to_ktime(global_rt_period());
8646 mutex_unlock(&mutex);
8648 return ret;
8651 #ifdef CONFIG_CGROUP_SCHED
8653 /* return corresponding task_group object of a cgroup */
8654 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8656 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8657 struct task_group, css);
8660 static struct cgroup_subsys_state *
8661 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8663 struct task_group *tg, *parent;
8665 if (!cgrp->parent) {
8666 /* This is early initialization for the top cgroup */
8667 return &init_task_group.css;
8670 parent = cgroup_tg(cgrp->parent);
8671 tg = sched_create_group(parent);
8672 if (IS_ERR(tg))
8673 return ERR_PTR(-ENOMEM);
8675 return &tg->css;
8678 static void
8679 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8681 struct task_group *tg = cgroup_tg(cgrp);
8683 sched_destroy_group(tg);
8686 static int
8687 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8689 #ifdef CONFIG_RT_GROUP_SCHED
8690 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8691 return -EINVAL;
8692 #else
8693 /* We don't support RT-tasks being in separate groups */
8694 if (tsk->sched_class != &fair_sched_class)
8695 return -EINVAL;
8696 #endif
8697 return 0;
8700 static int
8701 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8702 struct task_struct *tsk, bool threadgroup)
8704 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
8705 if (retval)
8706 return retval;
8707 if (threadgroup) {
8708 struct task_struct *c;
8709 rcu_read_lock();
8710 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8711 retval = cpu_cgroup_can_attach_task(cgrp, c);
8712 if (retval) {
8713 rcu_read_unlock();
8714 return retval;
8717 rcu_read_unlock();
8719 return 0;
8722 static void
8723 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8724 struct cgroup *old_cont, struct task_struct *tsk,
8725 bool threadgroup)
8727 sched_move_task(tsk);
8728 if (threadgroup) {
8729 struct task_struct *c;
8730 rcu_read_lock();
8731 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8732 sched_move_task(c);
8734 rcu_read_unlock();
8738 #ifdef CONFIG_FAIR_GROUP_SCHED
8739 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8740 u64 shareval)
8742 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8745 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8747 struct task_group *tg = cgroup_tg(cgrp);
8749 return (u64) tg->shares;
8751 #endif /* CONFIG_FAIR_GROUP_SCHED */
8753 #ifdef CONFIG_RT_GROUP_SCHED
8754 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8755 s64 val)
8757 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8760 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8762 return sched_group_rt_runtime(cgroup_tg(cgrp));
8765 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8766 u64 rt_period_us)
8768 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8771 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8773 return sched_group_rt_period(cgroup_tg(cgrp));
8775 #endif /* CONFIG_RT_GROUP_SCHED */
8777 static struct cftype cpu_files[] = {
8778 #ifdef CONFIG_FAIR_GROUP_SCHED
8780 .name = "shares",
8781 .read_u64 = cpu_shares_read_u64,
8782 .write_u64 = cpu_shares_write_u64,
8784 #endif
8785 #ifdef CONFIG_RT_GROUP_SCHED
8787 .name = "rt_runtime_us",
8788 .read_s64 = cpu_rt_runtime_read,
8789 .write_s64 = cpu_rt_runtime_write,
8792 .name = "rt_period_us",
8793 .read_u64 = cpu_rt_period_read_uint,
8794 .write_u64 = cpu_rt_period_write_uint,
8796 #endif
8799 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8801 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8804 struct cgroup_subsys cpu_cgroup_subsys = {
8805 .name = "cpu",
8806 .create = cpu_cgroup_create,
8807 .destroy = cpu_cgroup_destroy,
8808 .can_attach = cpu_cgroup_can_attach,
8809 .attach = cpu_cgroup_attach,
8810 .populate = cpu_cgroup_populate,
8811 .subsys_id = cpu_cgroup_subsys_id,
8812 .early_init = 1,
8815 #endif /* CONFIG_CGROUP_SCHED */
8817 #ifdef CONFIG_CGROUP_CPUACCT
8820 * CPU accounting code for task groups.
8822 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8823 * (balbir@in.ibm.com).
8826 /* track cpu usage of a group of tasks and its child groups */
8827 struct cpuacct {
8828 struct cgroup_subsys_state css;
8829 /* cpuusage holds pointer to a u64-type object on every cpu */
8830 u64 __percpu *cpuusage;
8831 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
8832 struct cpuacct *parent;
8835 struct cgroup_subsys cpuacct_subsys;
8837 /* return cpu accounting group corresponding to this container */
8838 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8840 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8841 struct cpuacct, css);
8844 /* return cpu accounting group to which this task belongs */
8845 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8847 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8848 struct cpuacct, css);
8851 /* create a new cpu accounting group */
8852 static struct cgroup_subsys_state *cpuacct_create(
8853 struct cgroup_subsys *ss, struct cgroup *cgrp)
8855 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8856 int i;
8858 if (!ca)
8859 goto out;
8861 ca->cpuusage = alloc_percpu(u64);
8862 if (!ca->cpuusage)
8863 goto out_free_ca;
8865 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8866 if (percpu_counter_init(&ca->cpustat[i], 0))
8867 goto out_free_counters;
8869 if (cgrp->parent)
8870 ca->parent = cgroup_ca(cgrp->parent);
8872 return &ca->css;
8874 out_free_counters:
8875 while (--i >= 0)
8876 percpu_counter_destroy(&ca->cpustat[i]);
8877 free_percpu(ca->cpuusage);
8878 out_free_ca:
8879 kfree(ca);
8880 out:
8881 return ERR_PTR(-ENOMEM);
8884 /* destroy an existing cpu accounting group */
8885 static void
8886 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8888 struct cpuacct *ca = cgroup_ca(cgrp);
8889 int i;
8891 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8892 percpu_counter_destroy(&ca->cpustat[i]);
8893 free_percpu(ca->cpuusage);
8894 kfree(ca);
8897 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
8899 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8900 u64 data;
8902 #ifndef CONFIG_64BIT
8904 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
8906 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8907 data = *cpuusage;
8908 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8909 #else
8910 data = *cpuusage;
8911 #endif
8913 return data;
8916 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
8918 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8920 #ifndef CONFIG_64BIT
8922 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
8924 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8925 *cpuusage = val;
8926 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8927 #else
8928 *cpuusage = val;
8929 #endif
8932 /* return total cpu usage (in nanoseconds) of a group */
8933 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8935 struct cpuacct *ca = cgroup_ca(cgrp);
8936 u64 totalcpuusage = 0;
8937 int i;
8939 for_each_present_cpu(i)
8940 totalcpuusage += cpuacct_cpuusage_read(ca, i);
8942 return totalcpuusage;
8945 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8946 u64 reset)
8948 struct cpuacct *ca = cgroup_ca(cgrp);
8949 int err = 0;
8950 int i;
8952 if (reset) {
8953 err = -EINVAL;
8954 goto out;
8957 for_each_present_cpu(i)
8958 cpuacct_cpuusage_write(ca, i, 0);
8960 out:
8961 return err;
8964 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
8965 struct seq_file *m)
8967 struct cpuacct *ca = cgroup_ca(cgroup);
8968 u64 percpu;
8969 int i;
8971 for_each_present_cpu(i) {
8972 percpu = cpuacct_cpuusage_read(ca, i);
8973 seq_printf(m, "%llu ", (unsigned long long) percpu);
8975 seq_printf(m, "\n");
8976 return 0;
8979 static const char *cpuacct_stat_desc[] = {
8980 [CPUACCT_STAT_USER] = "user",
8981 [CPUACCT_STAT_SYSTEM] = "system",
8984 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
8985 struct cgroup_map_cb *cb)
8987 struct cpuacct *ca = cgroup_ca(cgrp);
8988 int i;
8990 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
8991 s64 val = percpu_counter_read(&ca->cpustat[i]);
8992 val = cputime64_to_clock_t(val);
8993 cb->fill(cb, cpuacct_stat_desc[i], val);
8995 return 0;
8998 static struct cftype files[] = {
9000 .name = "usage",
9001 .read_u64 = cpuusage_read,
9002 .write_u64 = cpuusage_write,
9005 .name = "usage_percpu",
9006 .read_seq_string = cpuacct_percpu_seq_read,
9009 .name = "stat",
9010 .read_map = cpuacct_stats_show,
9014 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9016 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9020 * charge this task's execution time to its accounting group.
9022 * called with rq->lock held.
9024 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9026 struct cpuacct *ca;
9027 int cpu;
9029 if (unlikely(!cpuacct_subsys.active))
9030 return;
9032 cpu = task_cpu(tsk);
9034 rcu_read_lock();
9036 ca = task_ca(tsk);
9038 for (; ca; ca = ca->parent) {
9039 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9040 *cpuusage += cputime;
9043 rcu_read_unlock();
9047 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9048 * in cputime_t units. As a result, cpuacct_update_stats calls
9049 * percpu_counter_add with values large enough to always overflow the
9050 * per cpu batch limit causing bad SMP scalability.
9052 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9053 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9054 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9056 #ifdef CONFIG_SMP
9057 #define CPUACCT_BATCH \
9058 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9059 #else
9060 #define CPUACCT_BATCH 0
9061 #endif
9064 * Charge the system/user time to the task's accounting group.
9066 static void cpuacct_update_stats(struct task_struct *tsk,
9067 enum cpuacct_stat_index idx, cputime_t val)
9069 struct cpuacct *ca;
9070 int batch = CPUACCT_BATCH;
9072 if (unlikely(!cpuacct_subsys.active))
9073 return;
9075 rcu_read_lock();
9076 ca = task_ca(tsk);
9078 do {
9079 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9080 ca = ca->parent;
9081 } while (ca);
9082 rcu_read_unlock();
9085 struct cgroup_subsys cpuacct_subsys = {
9086 .name = "cpuacct",
9087 .create = cpuacct_create,
9088 .destroy = cpuacct_destroy,
9089 .populate = cpuacct_populate,
9090 .subsys_id = cpuacct_subsys_id,
9092 #endif /* CONFIG_CGROUP_CPUACCT */
9094 #ifndef CONFIG_SMP
9096 int rcu_expedited_torture_stats(char *page)
9098 return 0;
9100 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
9102 void synchronize_sched_expedited(void)
9105 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9107 #else /* #ifndef CONFIG_SMP */
9109 static DEFINE_PER_CPU(struct migration_req, rcu_migration_req);
9110 static DEFINE_MUTEX(rcu_sched_expedited_mutex);
9112 #define RCU_EXPEDITED_STATE_POST -2
9113 #define RCU_EXPEDITED_STATE_IDLE -1
9115 static int rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
9117 int rcu_expedited_torture_stats(char *page)
9119 int cnt = 0;
9120 int cpu;
9122 cnt += sprintf(&page[cnt], "state: %d /", rcu_expedited_state);
9123 for_each_online_cpu(cpu) {
9124 cnt += sprintf(&page[cnt], " %d:%d",
9125 cpu, per_cpu(rcu_migration_req, cpu).dest_cpu);
9127 cnt += sprintf(&page[cnt], "\n");
9128 return cnt;
9130 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
9132 static long synchronize_sched_expedited_count;
9135 * Wait for an rcu-sched grace period to elapse, but use "big hammer"
9136 * approach to force grace period to end quickly. This consumes
9137 * significant time on all CPUs, and is thus not recommended for
9138 * any sort of common-case code.
9140 * Note that it is illegal to call this function while holding any
9141 * lock that is acquired by a CPU-hotplug notifier. Failing to
9142 * observe this restriction will result in deadlock.
9144 void synchronize_sched_expedited(void)
9146 int cpu;
9147 unsigned long flags;
9148 bool need_full_sync = 0;
9149 struct rq *rq;
9150 struct migration_req *req;
9151 long snap;
9152 int trycount = 0;
9154 smp_mb(); /* ensure prior mod happens before capturing snap. */
9155 snap = ACCESS_ONCE(synchronize_sched_expedited_count) + 1;
9156 get_online_cpus();
9157 while (!mutex_trylock(&rcu_sched_expedited_mutex)) {
9158 put_online_cpus();
9159 if (trycount++ < 10)
9160 udelay(trycount * num_online_cpus());
9161 else {
9162 synchronize_sched();
9163 return;
9165 if (ACCESS_ONCE(synchronize_sched_expedited_count) - snap > 0) {
9166 smp_mb(); /* ensure test happens before caller kfree */
9167 return;
9169 get_online_cpus();
9171 rcu_expedited_state = RCU_EXPEDITED_STATE_POST;
9172 for_each_online_cpu(cpu) {
9173 rq = cpu_rq(cpu);
9174 req = &per_cpu(rcu_migration_req, cpu);
9175 init_completion(&req->done);
9176 req->task = NULL;
9177 req->dest_cpu = RCU_MIGRATION_NEED_QS;
9178 raw_spin_lock_irqsave(&rq->lock, flags);
9179 list_add(&req->list, &rq->migration_queue);
9180 raw_spin_unlock_irqrestore(&rq->lock, flags);
9181 wake_up_process(rq->migration_thread);
9183 for_each_online_cpu(cpu) {
9184 rcu_expedited_state = cpu;
9185 req = &per_cpu(rcu_migration_req, cpu);
9186 rq = cpu_rq(cpu);
9187 wait_for_completion(&req->done);
9188 raw_spin_lock_irqsave(&rq->lock, flags);
9189 if (unlikely(req->dest_cpu == RCU_MIGRATION_MUST_SYNC))
9190 need_full_sync = 1;
9191 req->dest_cpu = RCU_MIGRATION_IDLE;
9192 raw_spin_unlock_irqrestore(&rq->lock, flags);
9194 rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
9195 synchronize_sched_expedited_count++;
9196 mutex_unlock(&rcu_sched_expedited_mutex);
9197 put_online_cpus();
9198 if (need_full_sync)
9199 synchronize_sched();
9201 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9203 #endif /* #else #ifndef CONFIG_SMP */