]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - kernel/sched.c
ftrace: fix wakeups
[mirror_ubuntu-jammy-kernel.git] / kernel / sched.c
1 /*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 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
27 */
28
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/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
73 #include <linux/ftrace.h>
74
75 #include <asm/tlb.h>
76 #include <asm/irq_regs.h>
77
78 /*
79 * Convert user-nice values [ -20 ... 0 ... 19 ]
80 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
81 * and back.
82 */
83 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
84 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
85 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
86
87 /*
88 * 'User priority' is the nice value converted to something we
89 * can work with better when scaling various scheduler parameters,
90 * it's a [ 0 ... 39 ] range.
91 */
92 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
93 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
94 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
95
96 /*
97 * Helpers for converting nanosecond timing to jiffy resolution
98 */
99 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
100
101 #define NICE_0_LOAD SCHED_LOAD_SCALE
102 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
103
104 /*
105 * These are the 'tuning knobs' of the scheduler:
106 *
107 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
108 * Timeslices get refilled after they expire.
109 */
110 #define DEF_TIMESLICE (100 * HZ / 1000)
111
112 /*
113 * single value that denotes runtime == period, ie unlimited time.
114 */
115 #define RUNTIME_INF ((u64)~0ULL)
116
117 #ifdef CONFIG_SMP
118 /*
119 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
120 * Since cpu_power is a 'constant', we can use a reciprocal divide.
121 */
122 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
123 {
124 return reciprocal_divide(load, sg->reciprocal_cpu_power);
125 }
126
127 /*
128 * Each time a sched group cpu_power is changed,
129 * we must compute its reciprocal value
130 */
131 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
132 {
133 sg->__cpu_power += val;
134 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
135 }
136 #endif
137
138 static inline int rt_policy(int policy)
139 {
140 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
141 return 1;
142 return 0;
143 }
144
145 static inline int task_has_rt_policy(struct task_struct *p)
146 {
147 return rt_policy(p->policy);
148 }
149
150 /*
151 * This is the priority-queue data structure of the RT scheduling class:
152 */
153 struct rt_prio_array {
154 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
155 struct list_head queue[MAX_RT_PRIO];
156 };
157
158 struct rt_bandwidth {
159 /* nests inside the rq lock: */
160 spinlock_t rt_runtime_lock;
161 ktime_t rt_period;
162 u64 rt_runtime;
163 struct hrtimer rt_period_timer;
164 };
165
166 static struct rt_bandwidth def_rt_bandwidth;
167
168 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
169
170 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
171 {
172 struct rt_bandwidth *rt_b =
173 container_of(timer, struct rt_bandwidth, rt_period_timer);
174 ktime_t now;
175 int overrun;
176 int idle = 0;
177
178 for (;;) {
179 now = hrtimer_cb_get_time(timer);
180 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
181
182 if (!overrun)
183 break;
184
185 idle = do_sched_rt_period_timer(rt_b, overrun);
186 }
187
188 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
189 }
190
191 static
192 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
193 {
194 rt_b->rt_period = ns_to_ktime(period);
195 rt_b->rt_runtime = runtime;
196
197 spin_lock_init(&rt_b->rt_runtime_lock);
198
199 hrtimer_init(&rt_b->rt_period_timer,
200 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
201 rt_b->rt_period_timer.function = sched_rt_period_timer;
202 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
203 }
204
205 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
206 {
207 ktime_t now;
208
209 if (rt_b->rt_runtime == RUNTIME_INF)
210 return;
211
212 if (hrtimer_active(&rt_b->rt_period_timer))
213 return;
214
215 spin_lock(&rt_b->rt_runtime_lock);
216 for (;;) {
217 if (hrtimer_active(&rt_b->rt_period_timer))
218 break;
219
220 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
221 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
222 hrtimer_start(&rt_b->rt_period_timer,
223 rt_b->rt_period_timer.expires,
224 HRTIMER_MODE_ABS);
225 }
226 spin_unlock(&rt_b->rt_runtime_lock);
227 }
228
229 #ifdef CONFIG_RT_GROUP_SCHED
230 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
231 {
232 hrtimer_cancel(&rt_b->rt_period_timer);
233 }
234 #endif
235
236 /*
237 * sched_domains_mutex serializes calls to arch_init_sched_domains,
238 * detach_destroy_domains and partition_sched_domains.
239 */
240 static DEFINE_MUTEX(sched_domains_mutex);
241
242 #ifdef CONFIG_GROUP_SCHED
243
244 #include <linux/cgroup.h>
245
246 struct cfs_rq;
247
248 static LIST_HEAD(task_groups);
249
250 /* task group related information */
251 struct task_group {
252 #ifdef CONFIG_CGROUP_SCHED
253 struct cgroup_subsys_state css;
254 #endif
255
256 #ifdef CONFIG_FAIR_GROUP_SCHED
257 /* schedulable entities of this group on each cpu */
258 struct sched_entity **se;
259 /* runqueue "owned" by this group on each cpu */
260 struct cfs_rq **cfs_rq;
261 unsigned long shares;
262 #endif
263
264 #ifdef CONFIG_RT_GROUP_SCHED
265 struct sched_rt_entity **rt_se;
266 struct rt_rq **rt_rq;
267
268 struct rt_bandwidth rt_bandwidth;
269 #endif
270
271 struct rcu_head rcu;
272 struct list_head list;
273
274 struct task_group *parent;
275 struct list_head siblings;
276 struct list_head children;
277 };
278
279 #ifdef CONFIG_USER_SCHED
280
281 /*
282 * Root task group.
283 * Every UID task group (including init_task_group aka UID-0) will
284 * be a child to this group.
285 */
286 struct task_group root_task_group;
287
288 #ifdef CONFIG_FAIR_GROUP_SCHED
289 /* Default task group's sched entity on each cpu */
290 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
291 /* Default task group's cfs_rq on each cpu */
292 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
293 #endif
294
295 #ifdef CONFIG_RT_GROUP_SCHED
296 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
297 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
298 #endif
299 #else
300 #define root_task_group init_task_group
301 #endif
302
303 /* task_group_lock serializes add/remove of task groups and also changes to
304 * a task group's cpu shares.
305 */
306 static DEFINE_SPINLOCK(task_group_lock);
307
308 #ifdef CONFIG_FAIR_GROUP_SCHED
309 #ifdef CONFIG_USER_SCHED
310 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
311 #else
312 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
313 #endif
314
315 /*
316 * A weight of 0, 1 or ULONG_MAX can cause arithmetics problems.
317 * (The default weight is 1024 - so there's no practical
318 * limitation from this.)
319 */
320 #define MIN_SHARES 2
321 #define MAX_SHARES (ULONG_MAX - 1)
322
323 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
324 #endif
325
326 /* Default task group.
327 * Every task in system belong to this group at bootup.
328 */
329 struct task_group init_task_group;
330
331 /* return group to which a task belongs */
332 static inline struct task_group *task_group(struct task_struct *p)
333 {
334 struct task_group *tg;
335
336 #ifdef CONFIG_USER_SCHED
337 tg = p->user->tg;
338 #elif defined(CONFIG_CGROUP_SCHED)
339 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
340 struct task_group, css);
341 #else
342 tg = &init_task_group;
343 #endif
344 return tg;
345 }
346
347 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
348 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
349 {
350 #ifdef CONFIG_FAIR_GROUP_SCHED
351 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
352 p->se.parent = task_group(p)->se[cpu];
353 #endif
354
355 #ifdef CONFIG_RT_GROUP_SCHED
356 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
357 p->rt.parent = task_group(p)->rt_se[cpu];
358 #endif
359 }
360
361 #else
362
363 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
364
365 #endif /* CONFIG_GROUP_SCHED */
366
367 /* CFS-related fields in a runqueue */
368 struct cfs_rq {
369 struct load_weight load;
370 unsigned long nr_running;
371
372 u64 exec_clock;
373 u64 min_vruntime;
374
375 struct rb_root tasks_timeline;
376 struct rb_node *rb_leftmost;
377
378 struct list_head tasks;
379 struct list_head *balance_iterator;
380
381 /*
382 * 'curr' points to currently running entity on this cfs_rq.
383 * It is set to NULL otherwise (i.e when none are currently running).
384 */
385 struct sched_entity *curr, *next;
386
387 unsigned long nr_spread_over;
388
389 #ifdef CONFIG_FAIR_GROUP_SCHED
390 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
391
392 /*
393 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
394 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
395 * (like users, containers etc.)
396 *
397 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
398 * list is used during load balance.
399 */
400 struct list_head leaf_cfs_rq_list;
401 struct task_group *tg; /* group that "owns" this runqueue */
402
403 #ifdef CONFIG_SMP
404 unsigned long task_weight;
405 unsigned long shares;
406 /*
407 * We need space to build a sched_domain wide view of the full task
408 * group tree, in order to avoid depending on dynamic memory allocation
409 * during the load balancing we place this in the per cpu task group
410 * hierarchy. This limits the load balancing to one instance per cpu,
411 * but more should not be needed anyway.
412 */
413 struct aggregate_struct {
414 /*
415 * load = weight(cpus) * f(tg)
416 *
417 * Where f(tg) is the recursive weight fraction assigned to
418 * this group.
419 */
420 unsigned long load;
421
422 /*
423 * part of the group weight distributed to this span.
424 */
425 unsigned long shares;
426
427 /*
428 * The sum of all runqueue weights within this span.
429 */
430 unsigned long rq_weight;
431
432 /*
433 * Weight contributed by tasks; this is the part we can
434 * influence by moving tasks around.
435 */
436 unsigned long task_weight;
437 } aggregate;
438 #endif
439 #endif
440 };
441
442 /* Real-Time classes' related field in a runqueue: */
443 struct rt_rq {
444 struct rt_prio_array active;
445 unsigned long rt_nr_running;
446 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
447 int highest_prio; /* highest queued rt task prio */
448 #endif
449 #ifdef CONFIG_SMP
450 unsigned long rt_nr_migratory;
451 int overloaded;
452 #endif
453 int rt_throttled;
454 u64 rt_time;
455 u64 rt_runtime;
456 /* Nests inside the rq lock: */
457 spinlock_t rt_runtime_lock;
458
459 #ifdef CONFIG_RT_GROUP_SCHED
460 unsigned long rt_nr_boosted;
461
462 struct rq *rq;
463 struct list_head leaf_rt_rq_list;
464 struct task_group *tg;
465 struct sched_rt_entity *rt_se;
466 #endif
467 };
468
469 #ifdef CONFIG_SMP
470
471 /*
472 * We add the notion of a root-domain which will be used to define per-domain
473 * variables. Each exclusive cpuset essentially defines an island domain by
474 * fully partitioning the member cpus from any other cpuset. Whenever a new
475 * exclusive cpuset is created, we also create and attach a new root-domain
476 * object.
477 *
478 */
479 struct root_domain {
480 atomic_t refcount;
481 cpumask_t span;
482 cpumask_t online;
483
484 /*
485 * The "RT overload" flag: it gets set if a CPU has more than
486 * one runnable RT task.
487 */
488 cpumask_t rto_mask;
489 atomic_t rto_count;
490 };
491
492 /*
493 * By default the system creates a single root-domain with all cpus as
494 * members (mimicking the global state we have today).
495 */
496 static struct root_domain def_root_domain;
497
498 #endif
499
500 /*
501 * This is the main, per-CPU runqueue data structure.
502 *
503 * Locking rule: those places that want to lock multiple runqueues
504 * (such as the load balancing or the thread migration code), lock
505 * acquire operations must be ordered by ascending &runqueue.
506 */
507 struct rq {
508 /* runqueue lock: */
509 spinlock_t lock;
510
511 /*
512 * nr_running and cpu_load should be in the same cacheline because
513 * remote CPUs use both these fields when doing load calculation.
514 */
515 unsigned long nr_running;
516 #define CPU_LOAD_IDX_MAX 5
517 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
518 unsigned char idle_at_tick;
519 #ifdef CONFIG_NO_HZ
520 unsigned long last_tick_seen;
521 unsigned char in_nohz_recently;
522 #endif
523 /* capture load from *all* tasks on this cpu: */
524 struct load_weight load;
525 unsigned long nr_load_updates;
526 u64 nr_switches;
527
528 struct cfs_rq cfs;
529 struct rt_rq rt;
530
531 #ifdef CONFIG_FAIR_GROUP_SCHED
532 /* list of leaf cfs_rq on this cpu: */
533 struct list_head leaf_cfs_rq_list;
534 #endif
535 #ifdef CONFIG_RT_GROUP_SCHED
536 struct list_head leaf_rt_rq_list;
537 #endif
538
539 /*
540 * This is part of a global counter where only the total sum
541 * over all CPUs matters. A task can increase this counter on
542 * one CPU and if it got migrated afterwards it may decrease
543 * it on another CPU. Always updated under the runqueue lock:
544 */
545 unsigned long nr_uninterruptible;
546
547 struct task_struct *curr, *idle;
548 unsigned long next_balance;
549 struct mm_struct *prev_mm;
550
551 u64 clock;
552
553 atomic_t nr_iowait;
554
555 #ifdef CONFIG_SMP
556 struct root_domain *rd;
557 struct sched_domain *sd;
558
559 /* For active balancing */
560 int active_balance;
561 int push_cpu;
562 /* cpu of this runqueue: */
563 int cpu;
564
565 struct task_struct *migration_thread;
566 struct list_head migration_queue;
567 #endif
568
569 #ifdef CONFIG_SCHED_HRTICK
570 unsigned long hrtick_flags;
571 ktime_t hrtick_expire;
572 struct hrtimer hrtick_timer;
573 #endif
574
575 #ifdef CONFIG_SCHEDSTATS
576 /* latency stats */
577 struct sched_info rq_sched_info;
578
579 /* sys_sched_yield() stats */
580 unsigned int yld_exp_empty;
581 unsigned int yld_act_empty;
582 unsigned int yld_both_empty;
583 unsigned int yld_count;
584
585 /* schedule() stats */
586 unsigned int sched_switch;
587 unsigned int sched_count;
588 unsigned int sched_goidle;
589
590 /* try_to_wake_up() stats */
591 unsigned int ttwu_count;
592 unsigned int ttwu_local;
593
594 /* BKL stats */
595 unsigned int bkl_count;
596 #endif
597 struct lock_class_key rq_lock_key;
598 };
599
600 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
601
602 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
603 {
604 rq->curr->sched_class->check_preempt_curr(rq, p);
605 }
606
607 static inline int cpu_of(struct rq *rq)
608 {
609 #ifdef CONFIG_SMP
610 return rq->cpu;
611 #else
612 return 0;
613 #endif
614 }
615
616 /*
617 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
618 * See detach_destroy_domains: synchronize_sched for details.
619 *
620 * The domain tree of any CPU may only be accessed from within
621 * preempt-disabled sections.
622 */
623 #define for_each_domain(cpu, __sd) \
624 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
625
626 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
627 #define this_rq() (&__get_cpu_var(runqueues))
628 #define task_rq(p) cpu_rq(task_cpu(p))
629 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
630
631 static inline void update_rq_clock(struct rq *rq)
632 {
633 rq->clock = sched_clock_cpu(cpu_of(rq));
634 }
635
636 /*
637 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
638 */
639 #ifdef CONFIG_SCHED_DEBUG
640 # define const_debug __read_mostly
641 #else
642 # define const_debug static const
643 #endif
644
645 /**
646 * runqueue_is_locked
647 *
648 * Returns true if the current cpu runqueue is locked.
649 * This interface allows printk to be called with the runqueue lock
650 * held and know whether or not it is OK to wake up the klogd.
651 */
652 int runqueue_is_locked(void)
653 {
654 int cpu = get_cpu();
655 struct rq *rq = cpu_rq(cpu);
656 int ret;
657
658 ret = spin_is_locked(&rq->lock);
659 put_cpu();
660 return ret;
661 }
662
663 /*
664 * Debugging: various feature bits
665 */
666
667 #define SCHED_FEAT(name, enabled) \
668 __SCHED_FEAT_##name ,
669
670 enum {
671 #include "sched_features.h"
672 };
673
674 #undef SCHED_FEAT
675
676 #define SCHED_FEAT(name, enabled) \
677 (1UL << __SCHED_FEAT_##name) * enabled |
678
679 const_debug unsigned int sysctl_sched_features =
680 #include "sched_features.h"
681 0;
682
683 #undef SCHED_FEAT
684
685 #ifdef CONFIG_SCHED_DEBUG
686 #define SCHED_FEAT(name, enabled) \
687 #name ,
688
689 static __read_mostly char *sched_feat_names[] = {
690 #include "sched_features.h"
691 NULL
692 };
693
694 #undef SCHED_FEAT
695
696 static int sched_feat_open(struct inode *inode, struct file *filp)
697 {
698 filp->private_data = inode->i_private;
699 return 0;
700 }
701
702 static ssize_t
703 sched_feat_read(struct file *filp, char __user *ubuf,
704 size_t cnt, loff_t *ppos)
705 {
706 char *buf;
707 int r = 0;
708 int len = 0;
709 int i;
710
711 for (i = 0; sched_feat_names[i]; i++) {
712 len += strlen(sched_feat_names[i]);
713 len += 4;
714 }
715
716 buf = kmalloc(len + 2, GFP_KERNEL);
717 if (!buf)
718 return -ENOMEM;
719
720 for (i = 0; sched_feat_names[i]; i++) {
721 if (sysctl_sched_features & (1UL << i))
722 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
723 else
724 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
725 }
726
727 r += sprintf(buf + r, "\n");
728 WARN_ON(r >= len + 2);
729
730 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
731
732 kfree(buf);
733
734 return r;
735 }
736
737 static ssize_t
738 sched_feat_write(struct file *filp, const char __user *ubuf,
739 size_t cnt, loff_t *ppos)
740 {
741 char buf[64];
742 char *cmp = buf;
743 int neg = 0;
744 int i;
745
746 if (cnt > 63)
747 cnt = 63;
748
749 if (copy_from_user(&buf, ubuf, cnt))
750 return -EFAULT;
751
752 buf[cnt] = 0;
753
754 if (strncmp(buf, "NO_", 3) == 0) {
755 neg = 1;
756 cmp += 3;
757 }
758
759 for (i = 0; sched_feat_names[i]; i++) {
760 int len = strlen(sched_feat_names[i]);
761
762 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
763 if (neg)
764 sysctl_sched_features &= ~(1UL << i);
765 else
766 sysctl_sched_features |= (1UL << i);
767 break;
768 }
769 }
770
771 if (!sched_feat_names[i])
772 return -EINVAL;
773
774 filp->f_pos += cnt;
775
776 return cnt;
777 }
778
779 static struct file_operations sched_feat_fops = {
780 .open = sched_feat_open,
781 .read = sched_feat_read,
782 .write = sched_feat_write,
783 };
784
785 static __init int sched_init_debug(void)
786 {
787 debugfs_create_file("sched_features", 0644, NULL, NULL,
788 &sched_feat_fops);
789
790 return 0;
791 }
792 late_initcall(sched_init_debug);
793
794 #endif
795
796 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
797
798 /*
799 * Number of tasks to iterate in a single balance run.
800 * Limited because this is done with IRQs disabled.
801 */
802 const_debug unsigned int sysctl_sched_nr_migrate = 32;
803
804 /*
805 * period over which we measure -rt task cpu usage in us.
806 * default: 1s
807 */
808 unsigned int sysctl_sched_rt_period = 1000000;
809
810 static __read_mostly int scheduler_running;
811
812 /*
813 * part of the period that we allow rt tasks to run in us.
814 * default: 0.95s
815 */
816 int sysctl_sched_rt_runtime = 950000;
817
818 static inline u64 global_rt_period(void)
819 {
820 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
821 }
822
823 static inline u64 global_rt_runtime(void)
824 {
825 if (sysctl_sched_rt_period < 0)
826 return RUNTIME_INF;
827
828 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
829 }
830
831 unsigned long long time_sync_thresh = 100000;
832
833 static DEFINE_PER_CPU(unsigned long long, time_offset);
834 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
835
836 /*
837 * Global lock which we take every now and then to synchronize
838 * the CPUs time. This method is not warp-safe, but it's good
839 * enough to synchronize slowly diverging time sources and thus
840 * it's good enough for tracing:
841 */
842 static DEFINE_SPINLOCK(time_sync_lock);
843 static unsigned long long prev_global_time;
844
845 static unsigned long long __sync_cpu_clock(unsigned long long time, int cpu)
846 {
847 /*
848 * We want this inlined, to not get tracer function calls
849 * in this critical section:
850 */
851 spin_acquire(&time_sync_lock.dep_map, 0, 0, _THIS_IP_);
852 __raw_spin_lock(&time_sync_lock.raw_lock);
853
854 if (time < prev_global_time) {
855 per_cpu(time_offset, cpu) += prev_global_time - time;
856 time = prev_global_time;
857 } else {
858 prev_global_time = time;
859 }
860
861 __raw_spin_unlock(&time_sync_lock.raw_lock);
862 spin_release(&time_sync_lock.dep_map, 1, _THIS_IP_);
863
864 return time;
865 }
866
867 static unsigned long long __cpu_clock(int cpu)
868 {
869 unsigned long long now;
870
871 /*
872 * Only call sched_clock() if the scheduler has already been
873 * initialized (some code might call cpu_clock() very early):
874 */
875 if (unlikely(!scheduler_running))
876 return 0;
877
878 now = sched_clock_cpu(cpu);
879
880 return now;
881 }
882
883 /*
884 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
885 * clock constructed from sched_clock():
886 */
887 unsigned long long cpu_clock(int cpu)
888 {
889 unsigned long long prev_cpu_time, time, delta_time;
890 unsigned long flags;
891
892 local_irq_save(flags);
893 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
894 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
895 delta_time = time-prev_cpu_time;
896
897 if (unlikely(delta_time > time_sync_thresh)) {
898 time = __sync_cpu_clock(time, cpu);
899 per_cpu(prev_cpu_time, cpu) = time;
900 }
901 local_irq_restore(flags);
902
903 return time;
904 }
905 EXPORT_SYMBOL_GPL(cpu_clock);
906
907 #ifndef prepare_arch_switch
908 # define prepare_arch_switch(next) do { } while (0)
909 #endif
910 #ifndef finish_arch_switch
911 # define finish_arch_switch(prev) do { } while (0)
912 #endif
913
914 static inline int task_current(struct rq *rq, struct task_struct *p)
915 {
916 return rq->curr == p;
917 }
918
919 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
920 static inline int task_running(struct rq *rq, struct task_struct *p)
921 {
922 return task_current(rq, p);
923 }
924
925 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
926 {
927 }
928
929 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
930 {
931 #ifdef CONFIG_DEBUG_SPINLOCK
932 /* this is a valid case when another task releases the spinlock */
933 rq->lock.owner = current;
934 #endif
935 /*
936 * If we are tracking spinlock dependencies then we have to
937 * fix up the runqueue lock - which gets 'carried over' from
938 * prev into current:
939 */
940 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
941
942 spin_unlock_irq(&rq->lock);
943 }
944
945 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
946 static inline int task_running(struct rq *rq, struct task_struct *p)
947 {
948 #ifdef CONFIG_SMP
949 return p->oncpu;
950 #else
951 return task_current(rq, p);
952 #endif
953 }
954
955 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
956 {
957 #ifdef CONFIG_SMP
958 /*
959 * We can optimise this out completely for !SMP, because the
960 * SMP rebalancing from interrupt is the only thing that cares
961 * here.
962 */
963 next->oncpu = 1;
964 #endif
965 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
966 spin_unlock_irq(&rq->lock);
967 #else
968 spin_unlock(&rq->lock);
969 #endif
970 }
971
972 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
973 {
974 #ifdef CONFIG_SMP
975 /*
976 * After ->oncpu is cleared, the task can be moved to a different CPU.
977 * We must ensure this doesn't happen until the switch is completely
978 * finished.
979 */
980 smp_wmb();
981 prev->oncpu = 0;
982 #endif
983 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
984 local_irq_enable();
985 #endif
986 }
987 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
988
989 /*
990 * __task_rq_lock - lock the runqueue a given task resides on.
991 * Must be called interrupts disabled.
992 */
993 static inline struct rq *__task_rq_lock(struct task_struct *p)
994 __acquires(rq->lock)
995 {
996 for (;;) {
997 struct rq *rq = task_rq(p);
998 spin_lock(&rq->lock);
999 if (likely(rq == task_rq(p)))
1000 return rq;
1001 spin_unlock(&rq->lock);
1002 }
1003 }
1004
1005 /*
1006 * task_rq_lock - lock the runqueue a given task resides on and disable
1007 * interrupts. Note the ordering: we can safely lookup the task_rq without
1008 * explicitly disabling preemption.
1009 */
1010 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1011 __acquires(rq->lock)
1012 {
1013 struct rq *rq;
1014
1015 for (;;) {
1016 local_irq_save(*flags);
1017 rq = task_rq(p);
1018 spin_lock(&rq->lock);
1019 if (likely(rq == task_rq(p)))
1020 return rq;
1021 spin_unlock_irqrestore(&rq->lock, *flags);
1022 }
1023 }
1024
1025 static void __task_rq_unlock(struct rq *rq)
1026 __releases(rq->lock)
1027 {
1028 spin_unlock(&rq->lock);
1029 }
1030
1031 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1032 __releases(rq->lock)
1033 {
1034 spin_unlock_irqrestore(&rq->lock, *flags);
1035 }
1036
1037 /*
1038 * this_rq_lock - lock this runqueue and disable interrupts.
1039 */
1040 static struct rq *this_rq_lock(void)
1041 __acquires(rq->lock)
1042 {
1043 struct rq *rq;
1044
1045 local_irq_disable();
1046 rq = this_rq();
1047 spin_lock(&rq->lock);
1048
1049 return rq;
1050 }
1051
1052 static void __resched_task(struct task_struct *p, int tif_bit);
1053
1054 static inline void resched_task(struct task_struct *p)
1055 {
1056 __resched_task(p, TIF_NEED_RESCHED);
1057 }
1058
1059 #ifdef CONFIG_SCHED_HRTICK
1060 /*
1061 * Use HR-timers to deliver accurate preemption points.
1062 *
1063 * Its all a bit involved since we cannot program an hrt while holding the
1064 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1065 * reschedule event.
1066 *
1067 * When we get rescheduled we reprogram the hrtick_timer outside of the
1068 * rq->lock.
1069 */
1070 static inline void resched_hrt(struct task_struct *p)
1071 {
1072 __resched_task(p, TIF_HRTICK_RESCHED);
1073 }
1074
1075 static inline void resched_rq(struct rq *rq)
1076 {
1077 unsigned long flags;
1078
1079 spin_lock_irqsave(&rq->lock, flags);
1080 resched_task(rq->curr);
1081 spin_unlock_irqrestore(&rq->lock, flags);
1082 }
1083
1084 enum {
1085 HRTICK_SET, /* re-programm hrtick_timer */
1086 HRTICK_RESET, /* not a new slice */
1087 HRTICK_BLOCK, /* stop hrtick operations */
1088 };
1089
1090 /*
1091 * Use hrtick when:
1092 * - enabled by features
1093 * - hrtimer is actually high res
1094 */
1095 static inline int hrtick_enabled(struct rq *rq)
1096 {
1097 if (!sched_feat(HRTICK))
1098 return 0;
1099 if (unlikely(test_bit(HRTICK_BLOCK, &rq->hrtick_flags)))
1100 return 0;
1101 return hrtimer_is_hres_active(&rq->hrtick_timer);
1102 }
1103
1104 /*
1105 * Called to set the hrtick timer state.
1106 *
1107 * called with rq->lock held and irqs disabled
1108 */
1109 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1110 {
1111 assert_spin_locked(&rq->lock);
1112
1113 /*
1114 * preempt at: now + delay
1115 */
1116 rq->hrtick_expire =
1117 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1118 /*
1119 * indicate we need to program the timer
1120 */
1121 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1122 if (reset)
1123 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1124
1125 /*
1126 * New slices are called from the schedule path and don't need a
1127 * forced reschedule.
1128 */
1129 if (reset)
1130 resched_hrt(rq->curr);
1131 }
1132
1133 static void hrtick_clear(struct rq *rq)
1134 {
1135 if (hrtimer_active(&rq->hrtick_timer))
1136 hrtimer_cancel(&rq->hrtick_timer);
1137 }
1138
1139 /*
1140 * Update the timer from the possible pending state.
1141 */
1142 static void hrtick_set(struct rq *rq)
1143 {
1144 ktime_t time;
1145 int set, reset;
1146 unsigned long flags;
1147
1148 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1149
1150 spin_lock_irqsave(&rq->lock, flags);
1151 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1152 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1153 time = rq->hrtick_expire;
1154 clear_thread_flag(TIF_HRTICK_RESCHED);
1155 spin_unlock_irqrestore(&rq->lock, flags);
1156
1157 if (set) {
1158 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1159 if (reset && !hrtimer_active(&rq->hrtick_timer))
1160 resched_rq(rq);
1161 } else
1162 hrtick_clear(rq);
1163 }
1164
1165 /*
1166 * High-resolution timer tick.
1167 * Runs from hardirq context with interrupts disabled.
1168 */
1169 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1170 {
1171 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1172
1173 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1174
1175 spin_lock(&rq->lock);
1176 update_rq_clock(rq);
1177 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1178 spin_unlock(&rq->lock);
1179
1180 return HRTIMER_NORESTART;
1181 }
1182
1183 static void hotplug_hrtick_disable(int cpu)
1184 {
1185 struct rq *rq = cpu_rq(cpu);
1186 unsigned long flags;
1187
1188 spin_lock_irqsave(&rq->lock, flags);
1189 rq->hrtick_flags = 0;
1190 __set_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1191 spin_unlock_irqrestore(&rq->lock, flags);
1192
1193 hrtick_clear(rq);
1194 }
1195
1196 static void hotplug_hrtick_enable(int cpu)
1197 {
1198 struct rq *rq = cpu_rq(cpu);
1199 unsigned long flags;
1200
1201 spin_lock_irqsave(&rq->lock, flags);
1202 __clear_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1203 spin_unlock_irqrestore(&rq->lock, flags);
1204 }
1205
1206 static int
1207 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1208 {
1209 int cpu = (int)(long)hcpu;
1210
1211 switch (action) {
1212 case CPU_UP_CANCELED:
1213 case CPU_UP_CANCELED_FROZEN:
1214 case CPU_DOWN_PREPARE:
1215 case CPU_DOWN_PREPARE_FROZEN:
1216 case CPU_DEAD:
1217 case CPU_DEAD_FROZEN:
1218 hotplug_hrtick_disable(cpu);
1219 return NOTIFY_OK;
1220
1221 case CPU_UP_PREPARE:
1222 case CPU_UP_PREPARE_FROZEN:
1223 case CPU_DOWN_FAILED:
1224 case CPU_DOWN_FAILED_FROZEN:
1225 case CPU_ONLINE:
1226 case CPU_ONLINE_FROZEN:
1227 hotplug_hrtick_enable(cpu);
1228 return NOTIFY_OK;
1229 }
1230
1231 return NOTIFY_DONE;
1232 }
1233
1234 static void init_hrtick(void)
1235 {
1236 hotcpu_notifier(hotplug_hrtick, 0);
1237 }
1238
1239 static void init_rq_hrtick(struct rq *rq)
1240 {
1241 rq->hrtick_flags = 0;
1242 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1243 rq->hrtick_timer.function = hrtick;
1244 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1245 }
1246
1247 void hrtick_resched(void)
1248 {
1249 struct rq *rq;
1250 unsigned long flags;
1251
1252 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1253 return;
1254
1255 local_irq_save(flags);
1256 rq = cpu_rq(smp_processor_id());
1257 hrtick_set(rq);
1258 local_irq_restore(flags);
1259 }
1260 #else
1261 static inline void hrtick_clear(struct rq *rq)
1262 {
1263 }
1264
1265 static inline void hrtick_set(struct rq *rq)
1266 {
1267 }
1268
1269 static inline void init_rq_hrtick(struct rq *rq)
1270 {
1271 }
1272
1273 void hrtick_resched(void)
1274 {
1275 }
1276
1277 static inline void init_hrtick(void)
1278 {
1279 }
1280 #endif
1281
1282 /*
1283 * resched_task - mark a task 'to be rescheduled now'.
1284 *
1285 * On UP this means the setting of the need_resched flag, on SMP it
1286 * might also involve a cross-CPU call to trigger the scheduler on
1287 * the target CPU.
1288 */
1289 #ifdef CONFIG_SMP
1290
1291 #ifndef tsk_is_polling
1292 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1293 #endif
1294
1295 static void __resched_task(struct task_struct *p, int tif_bit)
1296 {
1297 int cpu;
1298
1299 assert_spin_locked(&task_rq(p)->lock);
1300
1301 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1302 return;
1303
1304 set_tsk_thread_flag(p, tif_bit);
1305
1306 cpu = task_cpu(p);
1307 if (cpu == smp_processor_id())
1308 return;
1309
1310 /* NEED_RESCHED must be visible before we test polling */
1311 smp_mb();
1312 if (!tsk_is_polling(p))
1313 smp_send_reschedule(cpu);
1314 }
1315
1316 static void resched_cpu(int cpu)
1317 {
1318 struct rq *rq = cpu_rq(cpu);
1319 unsigned long flags;
1320
1321 if (!spin_trylock_irqsave(&rq->lock, flags))
1322 return;
1323 resched_task(cpu_curr(cpu));
1324 spin_unlock_irqrestore(&rq->lock, flags);
1325 }
1326
1327 #ifdef CONFIG_NO_HZ
1328 /*
1329 * When add_timer_on() enqueues a timer into the timer wheel of an
1330 * idle CPU then this timer might expire before the next timer event
1331 * which is scheduled to wake up that CPU. In case of a completely
1332 * idle system the next event might even be infinite time into the
1333 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1334 * leaves the inner idle loop so the newly added timer is taken into
1335 * account when the CPU goes back to idle and evaluates the timer
1336 * wheel for the next timer event.
1337 */
1338 void wake_up_idle_cpu(int cpu)
1339 {
1340 struct rq *rq = cpu_rq(cpu);
1341
1342 if (cpu == smp_processor_id())
1343 return;
1344
1345 /*
1346 * This is safe, as this function is called with the timer
1347 * wheel base lock of (cpu) held. When the CPU is on the way
1348 * to idle and has not yet set rq->curr to idle then it will
1349 * be serialized on the timer wheel base lock and take the new
1350 * timer into account automatically.
1351 */
1352 if (rq->curr != rq->idle)
1353 return;
1354
1355 /*
1356 * We can set TIF_RESCHED on the idle task of the other CPU
1357 * lockless. The worst case is that the other CPU runs the
1358 * idle task through an additional NOOP schedule()
1359 */
1360 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1361
1362 /* NEED_RESCHED must be visible before we test polling */
1363 smp_mb();
1364 if (!tsk_is_polling(rq->idle))
1365 smp_send_reschedule(cpu);
1366 }
1367 #endif
1368
1369 #else
1370 static void __resched_task(struct task_struct *p, int tif_bit)
1371 {
1372 assert_spin_locked(&task_rq(p)->lock);
1373 set_tsk_thread_flag(p, tif_bit);
1374 }
1375 #endif
1376
1377 #if BITS_PER_LONG == 32
1378 # define WMULT_CONST (~0UL)
1379 #else
1380 # define WMULT_CONST (1UL << 32)
1381 #endif
1382
1383 #define WMULT_SHIFT 32
1384
1385 /*
1386 * Shift right and round:
1387 */
1388 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1389
1390 /*
1391 * delta *= weight / lw
1392 */
1393 static unsigned long
1394 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1395 struct load_weight *lw)
1396 {
1397 u64 tmp;
1398
1399 if (!lw->inv_weight)
1400 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)/(lw->weight+1);
1401
1402 tmp = (u64)delta_exec * weight;
1403 /*
1404 * Check whether we'd overflow the 64-bit multiplication:
1405 */
1406 if (unlikely(tmp > WMULT_CONST))
1407 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1408 WMULT_SHIFT/2);
1409 else
1410 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1411
1412 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1413 }
1414
1415 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1416 {
1417 lw->weight += inc;
1418 lw->inv_weight = 0;
1419 }
1420
1421 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1422 {
1423 lw->weight -= dec;
1424 lw->inv_weight = 0;
1425 }
1426
1427 /*
1428 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1429 * of tasks with abnormal "nice" values across CPUs the contribution that
1430 * each task makes to its run queue's load is weighted according to its
1431 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1432 * scaled version of the new time slice allocation that they receive on time
1433 * slice expiry etc.
1434 */
1435
1436 #define WEIGHT_IDLEPRIO 2
1437 #define WMULT_IDLEPRIO (1 << 31)
1438
1439 /*
1440 * Nice levels are multiplicative, with a gentle 10% change for every
1441 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1442 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1443 * that remained on nice 0.
1444 *
1445 * The "10% effect" is relative and cumulative: from _any_ nice level,
1446 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1447 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1448 * If a task goes up by ~10% and another task goes down by ~10% then
1449 * the relative distance between them is ~25%.)
1450 */
1451 static const int prio_to_weight[40] = {
1452 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1453 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1454 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1455 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1456 /* 0 */ 1024, 820, 655, 526, 423,
1457 /* 5 */ 335, 272, 215, 172, 137,
1458 /* 10 */ 110, 87, 70, 56, 45,
1459 /* 15 */ 36, 29, 23, 18, 15,
1460 };
1461
1462 /*
1463 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1464 *
1465 * In cases where the weight does not change often, we can use the
1466 * precalculated inverse to speed up arithmetics by turning divisions
1467 * into multiplications:
1468 */
1469 static const u32 prio_to_wmult[40] = {
1470 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1471 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1472 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1473 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1474 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1475 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1476 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1477 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1478 };
1479
1480 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1481
1482 /*
1483 * runqueue iterator, to support SMP load-balancing between different
1484 * scheduling classes, without having to expose their internal data
1485 * structures to the load-balancing proper:
1486 */
1487 struct rq_iterator {
1488 void *arg;
1489 struct task_struct *(*start)(void *);
1490 struct task_struct *(*next)(void *);
1491 };
1492
1493 #ifdef CONFIG_SMP
1494 static unsigned long
1495 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1496 unsigned long max_load_move, struct sched_domain *sd,
1497 enum cpu_idle_type idle, int *all_pinned,
1498 int *this_best_prio, struct rq_iterator *iterator);
1499
1500 static int
1501 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1502 struct sched_domain *sd, enum cpu_idle_type idle,
1503 struct rq_iterator *iterator);
1504 #endif
1505
1506 #ifdef CONFIG_CGROUP_CPUACCT
1507 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1508 #else
1509 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1510 #endif
1511
1512 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1513 {
1514 update_load_add(&rq->load, load);
1515 }
1516
1517 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1518 {
1519 update_load_sub(&rq->load, load);
1520 }
1521
1522 #ifdef CONFIG_SMP
1523 static unsigned long source_load(int cpu, int type);
1524 static unsigned long target_load(int cpu, int type);
1525 static unsigned long cpu_avg_load_per_task(int cpu);
1526 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1527
1528 #ifdef CONFIG_FAIR_GROUP_SCHED
1529
1530 /*
1531 * Group load balancing.
1532 *
1533 * We calculate a few balance domain wide aggregate numbers; load and weight.
1534 * Given the pictures below, and assuming each item has equal weight:
1535 *
1536 * root 1 - thread
1537 * / | \ A - group
1538 * A 1 B
1539 * /|\ / \
1540 * C 2 D 3 4
1541 * | |
1542 * 5 6
1543 *
1544 * load:
1545 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1546 * which equals 1/9-th of the total load.
1547 *
1548 * shares:
1549 * The weight of this group on the selected cpus.
1550 *
1551 * rq_weight:
1552 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1553 * B would get 2.
1554 *
1555 * task_weight:
1556 * Part of the rq_weight contributed by tasks; all groups except B would
1557 * get 1, B gets 2.
1558 */
1559
1560 static inline struct aggregate_struct *
1561 aggregate(struct task_group *tg, struct sched_domain *sd)
1562 {
1563 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1564 }
1565
1566 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1567
1568 /*
1569 * Iterate the full tree, calling @down when first entering a node and @up when
1570 * leaving it for the final time.
1571 */
1572 static
1573 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1574 struct sched_domain *sd)
1575 {
1576 struct task_group *parent, *child;
1577
1578 rcu_read_lock();
1579 parent = &root_task_group;
1580 down:
1581 (*down)(parent, sd);
1582 list_for_each_entry_rcu(child, &parent->children, siblings) {
1583 parent = child;
1584 goto down;
1585
1586 up:
1587 continue;
1588 }
1589 (*up)(parent, sd);
1590
1591 child = parent;
1592 parent = parent->parent;
1593 if (parent)
1594 goto up;
1595 rcu_read_unlock();
1596 }
1597
1598 /*
1599 * Calculate the aggregate runqueue weight.
1600 */
1601 static
1602 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1603 {
1604 unsigned long rq_weight = 0;
1605 unsigned long task_weight = 0;
1606 int i;
1607
1608 for_each_cpu_mask(i, sd->span) {
1609 rq_weight += tg->cfs_rq[i]->load.weight;
1610 task_weight += tg->cfs_rq[i]->task_weight;
1611 }
1612
1613 aggregate(tg, sd)->rq_weight = rq_weight;
1614 aggregate(tg, sd)->task_weight = task_weight;
1615 }
1616
1617 /*
1618 * Compute the weight of this group on the given cpus.
1619 */
1620 static
1621 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1622 {
1623 unsigned long shares = 0;
1624 int i;
1625
1626 for_each_cpu_mask(i, sd->span)
1627 shares += tg->cfs_rq[i]->shares;
1628
1629 if ((!shares && aggregate(tg, sd)->rq_weight) || shares > tg->shares)
1630 shares = tg->shares;
1631
1632 aggregate(tg, sd)->shares = shares;
1633 }
1634
1635 /*
1636 * Compute the load fraction assigned to this group, relies on the aggregate
1637 * weight and this group's parent's load, i.e. top-down.
1638 */
1639 static
1640 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1641 {
1642 unsigned long load;
1643
1644 if (!tg->parent) {
1645 int i;
1646
1647 load = 0;
1648 for_each_cpu_mask(i, sd->span)
1649 load += cpu_rq(i)->load.weight;
1650
1651 } else {
1652 load = aggregate(tg->parent, sd)->load;
1653
1654 /*
1655 * shares is our weight in the parent's rq so
1656 * shares/parent->rq_weight gives our fraction of the load
1657 */
1658 load *= aggregate(tg, sd)->shares;
1659 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1660 }
1661
1662 aggregate(tg, sd)->load = load;
1663 }
1664
1665 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1666
1667 /*
1668 * Calculate and set the cpu's group shares.
1669 */
1670 static void
1671 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1672 int tcpu)
1673 {
1674 int boost = 0;
1675 unsigned long shares;
1676 unsigned long rq_weight;
1677
1678 if (!tg->se[tcpu])
1679 return;
1680
1681 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1682
1683 /*
1684 * If there are currently no tasks on the cpu pretend there is one of
1685 * average load so that when a new task gets to run here it will not
1686 * get delayed by group starvation.
1687 */
1688 if (!rq_weight) {
1689 boost = 1;
1690 rq_weight = NICE_0_LOAD;
1691 }
1692
1693 /*
1694 * \Sum shares * rq_weight
1695 * shares = -----------------------
1696 * \Sum rq_weight
1697 *
1698 */
1699 shares = aggregate(tg, sd)->shares * rq_weight;
1700 shares /= aggregate(tg, sd)->rq_weight + 1;
1701
1702 /*
1703 * record the actual number of shares, not the boosted amount.
1704 */
1705 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1706
1707 if (shares < MIN_SHARES)
1708 shares = MIN_SHARES;
1709 else if (shares > MAX_SHARES)
1710 shares = MAX_SHARES;
1711
1712 __set_se_shares(tg->se[tcpu], shares);
1713 }
1714
1715 /*
1716 * Re-adjust the weights on the cpu the task came from and on the cpu the
1717 * task went to.
1718 */
1719 static void
1720 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1721 int scpu, int dcpu)
1722 {
1723 unsigned long shares;
1724
1725 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1726
1727 __update_group_shares_cpu(tg, sd, scpu);
1728 __update_group_shares_cpu(tg, sd, dcpu);
1729
1730 /*
1731 * ensure we never loose shares due to rounding errors in the
1732 * above redistribution.
1733 */
1734 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1735 if (shares)
1736 tg->cfs_rq[dcpu]->shares += shares;
1737 }
1738
1739 /*
1740 * Because changing a group's shares changes the weight of the super-group
1741 * we need to walk up the tree and change all shares until we hit the root.
1742 */
1743 static void
1744 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1745 int scpu, int dcpu)
1746 {
1747 while (tg) {
1748 __move_group_shares(tg, sd, scpu, dcpu);
1749 tg = tg->parent;
1750 }
1751 }
1752
1753 static
1754 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1755 {
1756 unsigned long shares = aggregate(tg, sd)->shares;
1757 int i;
1758
1759 for_each_cpu_mask(i, sd->span) {
1760 struct rq *rq = cpu_rq(i);
1761 unsigned long flags;
1762
1763 spin_lock_irqsave(&rq->lock, flags);
1764 __update_group_shares_cpu(tg, sd, i);
1765 spin_unlock_irqrestore(&rq->lock, flags);
1766 }
1767
1768 aggregate_group_shares(tg, sd);
1769
1770 /*
1771 * ensure we never loose shares due to rounding errors in the
1772 * above redistribution.
1773 */
1774 shares -= aggregate(tg, sd)->shares;
1775 if (shares) {
1776 tg->cfs_rq[sd->first_cpu]->shares += shares;
1777 aggregate(tg, sd)->shares += shares;
1778 }
1779 }
1780
1781 /*
1782 * Calculate the accumulative weight and recursive load of each task group
1783 * while walking down the tree.
1784 */
1785 static
1786 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1787 {
1788 aggregate_group_weight(tg, sd);
1789 aggregate_group_shares(tg, sd);
1790 aggregate_group_load(tg, sd);
1791 }
1792
1793 /*
1794 * Rebalance the cpu shares while walking back up the tree.
1795 */
1796 static
1797 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1798 {
1799 aggregate_group_set_shares(tg, sd);
1800 }
1801
1802 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1803
1804 static void __init init_aggregate(void)
1805 {
1806 int i;
1807
1808 for_each_possible_cpu(i)
1809 spin_lock_init(&per_cpu(aggregate_lock, i));
1810 }
1811
1812 static int get_aggregate(struct sched_domain *sd)
1813 {
1814 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1815 return 0;
1816
1817 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1818 return 1;
1819 }
1820
1821 static void put_aggregate(struct sched_domain *sd)
1822 {
1823 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1824 }
1825
1826 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1827 {
1828 cfs_rq->shares = shares;
1829 }
1830
1831 #else
1832
1833 static inline void init_aggregate(void)
1834 {
1835 }
1836
1837 static inline int get_aggregate(struct sched_domain *sd)
1838 {
1839 return 0;
1840 }
1841
1842 static inline void put_aggregate(struct sched_domain *sd)
1843 {
1844 }
1845 #endif
1846
1847 #else /* CONFIG_SMP */
1848
1849 #ifdef CONFIG_FAIR_GROUP_SCHED
1850 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1851 {
1852 }
1853 #endif
1854
1855 #endif /* CONFIG_SMP */
1856
1857 #include "sched_stats.h"
1858 #include "sched_idletask.c"
1859 #include "sched_fair.c"
1860 #include "sched_rt.c"
1861 #ifdef CONFIG_SCHED_DEBUG
1862 # include "sched_debug.c"
1863 #endif
1864
1865 #define sched_class_highest (&rt_sched_class)
1866
1867 static void inc_nr_running(struct rq *rq)
1868 {
1869 rq->nr_running++;
1870 }
1871
1872 static void dec_nr_running(struct rq *rq)
1873 {
1874 rq->nr_running--;
1875 }
1876
1877 static void set_load_weight(struct task_struct *p)
1878 {
1879 if (task_has_rt_policy(p)) {
1880 p->se.load.weight = prio_to_weight[0] * 2;
1881 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1882 return;
1883 }
1884
1885 /*
1886 * SCHED_IDLE tasks get minimal weight:
1887 */
1888 if (p->policy == SCHED_IDLE) {
1889 p->se.load.weight = WEIGHT_IDLEPRIO;
1890 p->se.load.inv_weight = WMULT_IDLEPRIO;
1891 return;
1892 }
1893
1894 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1895 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1896 }
1897
1898 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1899 {
1900 sched_info_queued(p);
1901 p->sched_class->enqueue_task(rq, p, wakeup);
1902 p->se.on_rq = 1;
1903 }
1904
1905 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1906 {
1907 p->sched_class->dequeue_task(rq, p, sleep);
1908 p->se.on_rq = 0;
1909 }
1910
1911 /*
1912 * __normal_prio - return the priority that is based on the static prio
1913 */
1914 static inline int __normal_prio(struct task_struct *p)
1915 {
1916 return p->static_prio;
1917 }
1918
1919 /*
1920 * Calculate the expected normal priority: i.e. priority
1921 * without taking RT-inheritance into account. Might be
1922 * boosted by interactivity modifiers. Changes upon fork,
1923 * setprio syscalls, and whenever the interactivity
1924 * estimator recalculates.
1925 */
1926 static inline int normal_prio(struct task_struct *p)
1927 {
1928 int prio;
1929
1930 if (task_has_rt_policy(p))
1931 prio = MAX_RT_PRIO-1 - p->rt_priority;
1932 else
1933 prio = __normal_prio(p);
1934 return prio;
1935 }
1936
1937 /*
1938 * Calculate the current priority, i.e. the priority
1939 * taken into account by the scheduler. This value might
1940 * be boosted by RT tasks, or might be boosted by
1941 * interactivity modifiers. Will be RT if the task got
1942 * RT-boosted. If not then it returns p->normal_prio.
1943 */
1944 static int effective_prio(struct task_struct *p)
1945 {
1946 p->normal_prio = normal_prio(p);
1947 /*
1948 * If we are RT tasks or we were boosted to RT priority,
1949 * keep the priority unchanged. Otherwise, update priority
1950 * to the normal priority:
1951 */
1952 if (!rt_prio(p->prio))
1953 return p->normal_prio;
1954 return p->prio;
1955 }
1956
1957 /*
1958 * activate_task - move a task to the runqueue.
1959 */
1960 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1961 {
1962 if (task_contributes_to_load(p))
1963 rq->nr_uninterruptible--;
1964
1965 enqueue_task(rq, p, wakeup);
1966 inc_nr_running(rq);
1967 }
1968
1969 /*
1970 * deactivate_task - remove a task from the runqueue.
1971 */
1972 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1973 {
1974 if (task_contributes_to_load(p))
1975 rq->nr_uninterruptible++;
1976
1977 dequeue_task(rq, p, sleep);
1978 dec_nr_running(rq);
1979 }
1980
1981 /**
1982 * task_curr - is this task currently executing on a CPU?
1983 * @p: the task in question.
1984 */
1985 inline int task_curr(const struct task_struct *p)
1986 {
1987 return cpu_curr(task_cpu(p)) == p;
1988 }
1989
1990 /* Used instead of source_load when we know the type == 0 */
1991 unsigned long weighted_cpuload(const int cpu)
1992 {
1993 return cpu_rq(cpu)->load.weight;
1994 }
1995
1996 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1997 {
1998 set_task_rq(p, cpu);
1999 #ifdef CONFIG_SMP
2000 /*
2001 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2002 * successfuly executed on another CPU. We must ensure that updates of
2003 * per-task data have been completed by this moment.
2004 */
2005 smp_wmb();
2006 task_thread_info(p)->cpu = cpu;
2007 #endif
2008 }
2009
2010 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2011 const struct sched_class *prev_class,
2012 int oldprio, int running)
2013 {
2014 if (prev_class != p->sched_class) {
2015 if (prev_class->switched_from)
2016 prev_class->switched_from(rq, p, running);
2017 p->sched_class->switched_to(rq, p, running);
2018 } else
2019 p->sched_class->prio_changed(rq, p, oldprio, running);
2020 }
2021
2022 #ifdef CONFIG_SMP
2023
2024 /*
2025 * Is this task likely cache-hot:
2026 */
2027 static int
2028 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2029 {
2030 s64 delta;
2031
2032 /*
2033 * Buddy candidates are cache hot:
2034 */
2035 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2036 return 1;
2037
2038 if (p->sched_class != &fair_sched_class)
2039 return 0;
2040
2041 if (sysctl_sched_migration_cost == -1)
2042 return 1;
2043 if (sysctl_sched_migration_cost == 0)
2044 return 0;
2045
2046 delta = now - p->se.exec_start;
2047
2048 return delta < (s64)sysctl_sched_migration_cost;
2049 }
2050
2051
2052 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2053 {
2054 int old_cpu = task_cpu(p);
2055 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2056 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2057 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2058 u64 clock_offset;
2059
2060 clock_offset = old_rq->clock - new_rq->clock;
2061
2062 #ifdef CONFIG_SCHEDSTATS
2063 if (p->se.wait_start)
2064 p->se.wait_start -= clock_offset;
2065 if (p->se.sleep_start)
2066 p->se.sleep_start -= clock_offset;
2067 if (p->se.block_start)
2068 p->se.block_start -= clock_offset;
2069 if (old_cpu != new_cpu) {
2070 schedstat_inc(p, se.nr_migrations);
2071 if (task_hot(p, old_rq->clock, NULL))
2072 schedstat_inc(p, se.nr_forced2_migrations);
2073 }
2074 #endif
2075 p->se.vruntime -= old_cfsrq->min_vruntime -
2076 new_cfsrq->min_vruntime;
2077
2078 __set_task_cpu(p, new_cpu);
2079 }
2080
2081 struct migration_req {
2082 struct list_head list;
2083
2084 struct task_struct *task;
2085 int dest_cpu;
2086
2087 struct completion done;
2088 };
2089
2090 /*
2091 * The task's runqueue lock must be held.
2092 * Returns true if you have to wait for migration thread.
2093 */
2094 static int
2095 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2096 {
2097 struct rq *rq = task_rq(p);
2098
2099 /*
2100 * If the task is not on a runqueue (and not running), then
2101 * it is sufficient to simply update the task's cpu field.
2102 */
2103 if (!p->se.on_rq && !task_running(rq, p)) {
2104 set_task_cpu(p, dest_cpu);
2105 return 0;
2106 }
2107
2108 init_completion(&req->done);
2109 req->task = p;
2110 req->dest_cpu = dest_cpu;
2111 list_add(&req->list, &rq->migration_queue);
2112
2113 return 1;
2114 }
2115
2116 /*
2117 * wait_task_inactive - wait for a thread to unschedule.
2118 *
2119 * The caller must ensure that the task *will* unschedule sometime soon,
2120 * else this function might spin for a *long* time. This function can't
2121 * be called with interrupts off, or it may introduce deadlock with
2122 * smp_call_function() if an IPI is sent by the same process we are
2123 * waiting to become inactive.
2124 */
2125 void wait_task_inactive(struct task_struct *p)
2126 {
2127 unsigned long flags;
2128 int running, on_rq;
2129 struct rq *rq;
2130
2131 for (;;) {
2132 /*
2133 * We do the initial early heuristics without holding
2134 * any task-queue locks at all. We'll only try to get
2135 * the runqueue lock when things look like they will
2136 * work out!
2137 */
2138 rq = task_rq(p);
2139
2140 /*
2141 * If the task is actively running on another CPU
2142 * still, just relax and busy-wait without holding
2143 * any locks.
2144 *
2145 * NOTE! Since we don't hold any locks, it's not
2146 * even sure that "rq" stays as the right runqueue!
2147 * But we don't care, since "task_running()" will
2148 * return false if the runqueue has changed and p
2149 * is actually now running somewhere else!
2150 */
2151 while (task_running(rq, p))
2152 cpu_relax();
2153
2154 /*
2155 * Ok, time to look more closely! We need the rq
2156 * lock now, to be *sure*. If we're wrong, we'll
2157 * just go back and repeat.
2158 */
2159 rq = task_rq_lock(p, &flags);
2160 running = task_running(rq, p);
2161 on_rq = p->se.on_rq;
2162 task_rq_unlock(rq, &flags);
2163
2164 /*
2165 * Was it really running after all now that we
2166 * checked with the proper locks actually held?
2167 *
2168 * Oops. Go back and try again..
2169 */
2170 if (unlikely(running)) {
2171 cpu_relax();
2172 continue;
2173 }
2174
2175 /*
2176 * It's not enough that it's not actively running,
2177 * it must be off the runqueue _entirely_, and not
2178 * preempted!
2179 *
2180 * So if it wa still runnable (but just not actively
2181 * running right now), it's preempted, and we should
2182 * yield - it could be a while.
2183 */
2184 if (unlikely(on_rq)) {
2185 schedule_timeout_uninterruptible(1);
2186 continue;
2187 }
2188
2189 /*
2190 * Ahh, all good. It wasn't running, and it wasn't
2191 * runnable, which means that it will never become
2192 * running in the future either. We're all done!
2193 */
2194 break;
2195 }
2196 }
2197
2198 /***
2199 * kick_process - kick a running thread to enter/exit the kernel
2200 * @p: the to-be-kicked thread
2201 *
2202 * Cause a process which is running on another CPU to enter
2203 * kernel-mode, without any delay. (to get signals handled.)
2204 *
2205 * NOTE: this function doesnt have to take the runqueue lock,
2206 * because all it wants to ensure is that the remote task enters
2207 * the kernel. If the IPI races and the task has been migrated
2208 * to another CPU then no harm is done and the purpose has been
2209 * achieved as well.
2210 */
2211 void kick_process(struct task_struct *p)
2212 {
2213 int cpu;
2214
2215 preempt_disable();
2216 cpu = task_cpu(p);
2217 if ((cpu != smp_processor_id()) && task_curr(p))
2218 smp_send_reschedule(cpu);
2219 preempt_enable();
2220 }
2221
2222 /*
2223 * Return a low guess at the load of a migration-source cpu weighted
2224 * according to the scheduling class and "nice" value.
2225 *
2226 * We want to under-estimate the load of migration sources, to
2227 * balance conservatively.
2228 */
2229 static unsigned long source_load(int cpu, int type)
2230 {
2231 struct rq *rq = cpu_rq(cpu);
2232 unsigned long total = weighted_cpuload(cpu);
2233
2234 if (type == 0)
2235 return total;
2236
2237 return min(rq->cpu_load[type-1], total);
2238 }
2239
2240 /*
2241 * Return a high guess at the load of a migration-target cpu weighted
2242 * according to the scheduling class and "nice" value.
2243 */
2244 static unsigned long target_load(int cpu, int type)
2245 {
2246 struct rq *rq = cpu_rq(cpu);
2247 unsigned long total = weighted_cpuload(cpu);
2248
2249 if (type == 0)
2250 return total;
2251
2252 return max(rq->cpu_load[type-1], total);
2253 }
2254
2255 /*
2256 * Return the average load per task on the cpu's run queue
2257 */
2258 static unsigned long cpu_avg_load_per_task(int cpu)
2259 {
2260 struct rq *rq = cpu_rq(cpu);
2261 unsigned long total = weighted_cpuload(cpu);
2262 unsigned long n = rq->nr_running;
2263
2264 return n ? total / n : SCHED_LOAD_SCALE;
2265 }
2266
2267 /*
2268 * find_idlest_group finds and returns the least busy CPU group within the
2269 * domain.
2270 */
2271 static struct sched_group *
2272 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2273 {
2274 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2275 unsigned long min_load = ULONG_MAX, this_load = 0;
2276 int load_idx = sd->forkexec_idx;
2277 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2278
2279 do {
2280 unsigned long load, avg_load;
2281 int local_group;
2282 int i;
2283
2284 /* Skip over this group if it has no CPUs allowed */
2285 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2286 continue;
2287
2288 local_group = cpu_isset(this_cpu, group->cpumask);
2289
2290 /* Tally up the load of all CPUs in the group */
2291 avg_load = 0;
2292
2293 for_each_cpu_mask(i, group->cpumask) {
2294 /* Bias balancing toward cpus of our domain */
2295 if (local_group)
2296 load = source_load(i, load_idx);
2297 else
2298 load = target_load(i, load_idx);
2299
2300 avg_load += load;
2301 }
2302
2303 /* Adjust by relative CPU power of the group */
2304 avg_load = sg_div_cpu_power(group,
2305 avg_load * SCHED_LOAD_SCALE);
2306
2307 if (local_group) {
2308 this_load = avg_load;
2309 this = group;
2310 } else if (avg_load < min_load) {
2311 min_load = avg_load;
2312 idlest = group;
2313 }
2314 } while (group = group->next, group != sd->groups);
2315
2316 if (!idlest || 100*this_load < imbalance*min_load)
2317 return NULL;
2318 return idlest;
2319 }
2320
2321 /*
2322 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2323 */
2324 static int
2325 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2326 cpumask_t *tmp)
2327 {
2328 unsigned long load, min_load = ULONG_MAX;
2329 int idlest = -1;
2330 int i;
2331
2332 /* Traverse only the allowed CPUs */
2333 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2334
2335 for_each_cpu_mask(i, *tmp) {
2336 load = weighted_cpuload(i);
2337
2338 if (load < min_load || (load == min_load && i == this_cpu)) {
2339 min_load = load;
2340 idlest = i;
2341 }
2342 }
2343
2344 return idlest;
2345 }
2346
2347 /*
2348 * sched_balance_self: balance the current task (running on cpu) in domains
2349 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2350 * SD_BALANCE_EXEC.
2351 *
2352 * Balance, ie. select the least loaded group.
2353 *
2354 * Returns the target CPU number, or the same CPU if no balancing is needed.
2355 *
2356 * preempt must be disabled.
2357 */
2358 static int sched_balance_self(int cpu, int flag)
2359 {
2360 struct task_struct *t = current;
2361 struct sched_domain *tmp, *sd = NULL;
2362
2363 for_each_domain(cpu, tmp) {
2364 /*
2365 * If power savings logic is enabled for a domain, stop there.
2366 */
2367 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2368 break;
2369 if (tmp->flags & flag)
2370 sd = tmp;
2371 }
2372
2373 while (sd) {
2374 cpumask_t span, tmpmask;
2375 struct sched_group *group;
2376 int new_cpu, weight;
2377
2378 if (!(sd->flags & flag)) {
2379 sd = sd->child;
2380 continue;
2381 }
2382
2383 span = sd->span;
2384 group = find_idlest_group(sd, t, cpu);
2385 if (!group) {
2386 sd = sd->child;
2387 continue;
2388 }
2389
2390 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2391 if (new_cpu == -1 || new_cpu == cpu) {
2392 /* Now try balancing at a lower domain level of cpu */
2393 sd = sd->child;
2394 continue;
2395 }
2396
2397 /* Now try balancing at a lower domain level of new_cpu */
2398 cpu = new_cpu;
2399 sd = NULL;
2400 weight = cpus_weight(span);
2401 for_each_domain(cpu, tmp) {
2402 if (weight <= cpus_weight(tmp->span))
2403 break;
2404 if (tmp->flags & flag)
2405 sd = tmp;
2406 }
2407 /* while loop will break here if sd == NULL */
2408 }
2409
2410 return cpu;
2411 }
2412
2413 #endif /* CONFIG_SMP */
2414
2415 #ifdef CONFIG_CONTEXT_SWITCH_TRACER
2416
2417 void ftrace_all_fair_tasks(void *__rq, void *__tr, void *__data)
2418 {
2419 struct task_struct *p;
2420 struct sched_entity *se;
2421 struct rb_node *curr;
2422 struct rq *rq = __rq;
2423
2424 curr = first_fair(&rq->cfs);
2425 if (!curr)
2426 return;
2427
2428 if (rq->cfs.curr) {
2429 p = task_of(rq->cfs.curr);
2430 __trace_special(__tr, __data,
2431 p->pid, p->se.vruntime, p->se.sum_exec_runtime);
2432 }
2433 if (rq->cfs.next) {
2434 p = task_of(rq->cfs.next);
2435 __trace_special(__tr, __data,
2436 p->pid, p->se.vruntime, p->se.sum_exec_runtime);
2437 }
2438
2439 while (curr) {
2440 se = rb_entry(curr, struct sched_entity, run_node);
2441 if (!entity_is_task(se))
2442 continue;
2443
2444 p = task_of(se);
2445
2446 __trace_special(__tr, __data,
2447 p->pid, p->se.vruntime, p->se.sum_exec_runtime);
2448
2449 curr = rb_next(curr);
2450 }
2451 }
2452
2453 #endif
2454
2455 /***
2456 * try_to_wake_up - wake up a thread
2457 * @p: the to-be-woken-up thread
2458 * @state: the mask of task states that can be woken
2459 * @sync: do a synchronous wakeup?
2460 *
2461 * Put it on the run-queue if it's not already there. The "current"
2462 * thread is always on the run-queue (except when the actual
2463 * re-schedule is in progress), and as such you're allowed to do
2464 * the simpler "current->state = TASK_RUNNING" to mark yourself
2465 * runnable without the overhead of this.
2466 *
2467 * returns failure only if the task is already active.
2468 */
2469 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2470 {
2471 int cpu, orig_cpu, this_cpu, success = 0;
2472 unsigned long flags;
2473 long old_state;
2474 struct rq *rq;
2475
2476 if (!sched_feat(SYNC_WAKEUPS))
2477 sync = 0;
2478
2479 smp_wmb();
2480 rq = task_rq_lock(p, &flags);
2481 old_state = p->state;
2482 if (!(old_state & state))
2483 goto out;
2484
2485 if (p->se.on_rq)
2486 goto out_running;
2487
2488 cpu = task_cpu(p);
2489 orig_cpu = cpu;
2490 this_cpu = smp_processor_id();
2491
2492 #ifdef CONFIG_SMP
2493 if (unlikely(task_running(rq, p)))
2494 goto out_activate;
2495
2496 cpu = p->sched_class->select_task_rq(p, sync);
2497 if (cpu != orig_cpu) {
2498 set_task_cpu(p, cpu);
2499 task_rq_unlock(rq, &flags);
2500 /* might preempt at this point */
2501 rq = task_rq_lock(p, &flags);
2502 old_state = p->state;
2503 if (!(old_state & state))
2504 goto out;
2505 if (p->se.on_rq)
2506 goto out_running;
2507
2508 this_cpu = smp_processor_id();
2509 cpu = task_cpu(p);
2510 }
2511
2512 #ifdef CONFIG_SCHEDSTATS
2513 schedstat_inc(rq, ttwu_count);
2514 if (cpu == this_cpu)
2515 schedstat_inc(rq, ttwu_local);
2516 else {
2517 struct sched_domain *sd;
2518 for_each_domain(this_cpu, sd) {
2519 if (cpu_isset(cpu, sd->span)) {
2520 schedstat_inc(sd, ttwu_wake_remote);
2521 break;
2522 }
2523 }
2524 }
2525 #endif
2526
2527 out_activate:
2528 #endif /* CONFIG_SMP */
2529 ftrace_wake_up_task(rq, p, rq->curr);
2530 schedstat_inc(p, se.nr_wakeups);
2531 if (sync)
2532 schedstat_inc(p, se.nr_wakeups_sync);
2533 if (orig_cpu != cpu)
2534 schedstat_inc(p, se.nr_wakeups_migrate);
2535 if (cpu == this_cpu)
2536 schedstat_inc(p, se.nr_wakeups_local);
2537 else
2538 schedstat_inc(p, se.nr_wakeups_remote);
2539 update_rq_clock(rq);
2540 activate_task(rq, p, 1);
2541 success = 1;
2542
2543 out_running:
2544 check_preempt_curr(rq, p);
2545
2546 p->state = TASK_RUNNING;
2547 #ifdef CONFIG_SMP
2548 if (p->sched_class->task_wake_up)
2549 p->sched_class->task_wake_up(rq, p);
2550 #endif
2551 out:
2552 task_rq_unlock(rq, &flags);
2553
2554 return success;
2555 }
2556
2557 int wake_up_process(struct task_struct *p)
2558 {
2559 return try_to_wake_up(p, TASK_ALL, 0);
2560 }
2561 EXPORT_SYMBOL(wake_up_process);
2562
2563 int wake_up_state(struct task_struct *p, unsigned int state)
2564 {
2565 return try_to_wake_up(p, state, 0);
2566 }
2567
2568 /*
2569 * Perform scheduler related setup for a newly forked process p.
2570 * p is forked by current.
2571 *
2572 * __sched_fork() is basic setup used by init_idle() too:
2573 */
2574 static void __sched_fork(struct task_struct *p)
2575 {
2576 p->se.exec_start = 0;
2577 p->se.sum_exec_runtime = 0;
2578 p->se.prev_sum_exec_runtime = 0;
2579 p->se.last_wakeup = 0;
2580 p->se.avg_overlap = 0;
2581
2582 #ifdef CONFIG_SCHEDSTATS
2583 p->se.wait_start = 0;
2584 p->se.sum_sleep_runtime = 0;
2585 p->se.sleep_start = 0;
2586 p->se.block_start = 0;
2587 p->se.sleep_max = 0;
2588 p->se.block_max = 0;
2589 p->se.exec_max = 0;
2590 p->se.slice_max = 0;
2591 p->se.wait_max = 0;
2592 #endif
2593
2594 INIT_LIST_HEAD(&p->rt.run_list);
2595 p->se.on_rq = 0;
2596 INIT_LIST_HEAD(&p->se.group_node);
2597
2598 #ifdef CONFIG_PREEMPT_NOTIFIERS
2599 INIT_HLIST_HEAD(&p->preempt_notifiers);
2600 #endif
2601
2602 /*
2603 * We mark the process as running here, but have not actually
2604 * inserted it onto the runqueue yet. This guarantees that
2605 * nobody will actually run it, and a signal or other external
2606 * event cannot wake it up and insert it on the runqueue either.
2607 */
2608 p->state = TASK_RUNNING;
2609 }
2610
2611 /*
2612 * fork()/clone()-time setup:
2613 */
2614 void sched_fork(struct task_struct *p, int clone_flags)
2615 {
2616 int cpu = get_cpu();
2617
2618 __sched_fork(p);
2619
2620 #ifdef CONFIG_SMP
2621 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2622 #endif
2623 set_task_cpu(p, cpu);
2624
2625 /*
2626 * Make sure we do not leak PI boosting priority to the child:
2627 */
2628 p->prio = current->normal_prio;
2629 if (!rt_prio(p->prio))
2630 p->sched_class = &fair_sched_class;
2631
2632 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2633 if (likely(sched_info_on()))
2634 memset(&p->sched_info, 0, sizeof(p->sched_info));
2635 #endif
2636 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2637 p->oncpu = 0;
2638 #endif
2639 #ifdef CONFIG_PREEMPT
2640 /* Want to start with kernel preemption disabled. */
2641 task_thread_info(p)->preempt_count = 1;
2642 #endif
2643 put_cpu();
2644 }
2645
2646 /*
2647 * wake_up_new_task - wake up a newly created task for the first time.
2648 *
2649 * This function will do some initial scheduler statistics housekeeping
2650 * that must be done for every newly created context, then puts the task
2651 * on the runqueue and wakes it.
2652 */
2653 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2654 {
2655 unsigned long flags;
2656 struct rq *rq;
2657
2658 rq = task_rq_lock(p, &flags);
2659 BUG_ON(p->state != TASK_RUNNING);
2660 update_rq_clock(rq);
2661
2662 p->prio = effective_prio(p);
2663
2664 if (!p->sched_class->task_new || !current->se.on_rq) {
2665 activate_task(rq, p, 0);
2666 } else {
2667 /*
2668 * Let the scheduling class do new task startup
2669 * management (if any):
2670 */
2671 p->sched_class->task_new(rq, p);
2672 inc_nr_running(rq);
2673 }
2674 ftrace_wake_up_task(rq, p, rq->curr);
2675 check_preempt_curr(rq, p);
2676 #ifdef CONFIG_SMP
2677 if (p->sched_class->task_wake_up)
2678 p->sched_class->task_wake_up(rq, p);
2679 #endif
2680 task_rq_unlock(rq, &flags);
2681 }
2682
2683 #ifdef CONFIG_PREEMPT_NOTIFIERS
2684
2685 /**
2686 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2687 * @notifier: notifier struct to register
2688 */
2689 void preempt_notifier_register(struct preempt_notifier *notifier)
2690 {
2691 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2692 }
2693 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2694
2695 /**
2696 * preempt_notifier_unregister - no longer interested in preemption notifications
2697 * @notifier: notifier struct to unregister
2698 *
2699 * This is safe to call from within a preemption notifier.
2700 */
2701 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2702 {
2703 hlist_del(&notifier->link);
2704 }
2705 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2706
2707 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2708 {
2709 struct preempt_notifier *notifier;
2710 struct hlist_node *node;
2711
2712 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2713 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2714 }
2715
2716 static void
2717 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2718 struct task_struct *next)
2719 {
2720 struct preempt_notifier *notifier;
2721 struct hlist_node *node;
2722
2723 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2724 notifier->ops->sched_out(notifier, next);
2725 }
2726
2727 #else
2728
2729 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2730 {
2731 }
2732
2733 static void
2734 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2735 struct task_struct *next)
2736 {
2737 }
2738
2739 #endif
2740
2741 /**
2742 * prepare_task_switch - prepare to switch tasks
2743 * @rq: the runqueue preparing to switch
2744 * @prev: the current task that is being switched out
2745 * @next: the task we are going to switch to.
2746 *
2747 * This is called with the rq lock held and interrupts off. It must
2748 * be paired with a subsequent finish_task_switch after the context
2749 * switch.
2750 *
2751 * prepare_task_switch sets up locking and calls architecture specific
2752 * hooks.
2753 */
2754 static inline void
2755 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2756 struct task_struct *next)
2757 {
2758 fire_sched_out_preempt_notifiers(prev, next);
2759 prepare_lock_switch(rq, next);
2760 prepare_arch_switch(next);
2761 }
2762
2763 /**
2764 * finish_task_switch - clean up after a task-switch
2765 * @rq: runqueue associated with task-switch
2766 * @prev: the thread we just switched away from.
2767 *
2768 * finish_task_switch must be called after the context switch, paired
2769 * with a prepare_task_switch call before the context switch.
2770 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2771 * and do any other architecture-specific cleanup actions.
2772 *
2773 * Note that we may have delayed dropping an mm in context_switch(). If
2774 * so, we finish that here outside of the runqueue lock. (Doing it
2775 * with the lock held can cause deadlocks; see schedule() for
2776 * details.)
2777 */
2778 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2779 __releases(rq->lock)
2780 {
2781 struct mm_struct *mm = rq->prev_mm;
2782 long prev_state;
2783
2784 rq->prev_mm = NULL;
2785
2786 /*
2787 * A task struct has one reference for the use as "current".
2788 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2789 * schedule one last time. The schedule call will never return, and
2790 * the scheduled task must drop that reference.
2791 * The test for TASK_DEAD must occur while the runqueue locks are
2792 * still held, otherwise prev could be scheduled on another cpu, die
2793 * there before we look at prev->state, and then the reference would
2794 * be dropped twice.
2795 * Manfred Spraul <manfred@colorfullife.com>
2796 */
2797 prev_state = prev->state;
2798 finish_arch_switch(prev);
2799 finish_lock_switch(rq, prev);
2800 #ifdef CONFIG_SMP
2801 if (current->sched_class->post_schedule)
2802 current->sched_class->post_schedule(rq);
2803 #endif
2804
2805 fire_sched_in_preempt_notifiers(current);
2806 if (mm)
2807 mmdrop(mm);
2808 if (unlikely(prev_state == TASK_DEAD)) {
2809 /*
2810 * Remove function-return probe instances associated with this
2811 * task and put them back on the free list.
2812 */
2813 kprobe_flush_task(prev);
2814 put_task_struct(prev);
2815 }
2816 }
2817
2818 /**
2819 * schedule_tail - first thing a freshly forked thread must call.
2820 * @prev: the thread we just switched away from.
2821 */
2822 asmlinkage void schedule_tail(struct task_struct *prev)
2823 __releases(rq->lock)
2824 {
2825 struct rq *rq = this_rq();
2826
2827 finish_task_switch(rq, prev);
2828 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2829 /* In this case, finish_task_switch does not reenable preemption */
2830 preempt_enable();
2831 #endif
2832 if (current->set_child_tid)
2833 put_user(task_pid_vnr(current), current->set_child_tid);
2834 }
2835
2836 /*
2837 * context_switch - switch to the new MM and the new
2838 * thread's register state.
2839 */
2840 static inline void
2841 context_switch(struct rq *rq, struct task_struct *prev,
2842 struct task_struct *next)
2843 {
2844 struct mm_struct *mm, *oldmm;
2845
2846 prepare_task_switch(rq, prev, next);
2847 ftrace_ctx_switch(rq, prev, next);
2848 mm = next->mm;
2849 oldmm = prev->active_mm;
2850 /*
2851 * For paravirt, this is coupled with an exit in switch_to to
2852 * combine the page table reload and the switch backend into
2853 * one hypercall.
2854 */
2855 arch_enter_lazy_cpu_mode();
2856
2857 if (unlikely(!mm)) {
2858 next->active_mm = oldmm;
2859 atomic_inc(&oldmm->mm_count);
2860 enter_lazy_tlb(oldmm, next);
2861 } else
2862 switch_mm(oldmm, mm, next);
2863
2864 if (unlikely(!prev->mm)) {
2865 prev->active_mm = NULL;
2866 rq->prev_mm = oldmm;
2867 }
2868 /*
2869 * Since the runqueue lock will be released by the next
2870 * task (which is an invalid locking op but in the case
2871 * of the scheduler it's an obvious special-case), so we
2872 * do an early lockdep release here:
2873 */
2874 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2875 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2876 #endif
2877
2878 /* Here we just switch the register state and the stack. */
2879 switch_to(prev, next, prev);
2880
2881 barrier();
2882 /*
2883 * this_rq must be evaluated again because prev may have moved
2884 * CPUs since it called schedule(), thus the 'rq' on its stack
2885 * frame will be invalid.
2886 */
2887 finish_task_switch(this_rq(), prev);
2888 }
2889
2890 /*
2891 * nr_running, nr_uninterruptible and nr_context_switches:
2892 *
2893 * externally visible scheduler statistics: current number of runnable
2894 * threads, current number of uninterruptible-sleeping threads, total
2895 * number of context switches performed since bootup.
2896 */
2897 unsigned long nr_running(void)
2898 {
2899 unsigned long i, sum = 0;
2900
2901 for_each_online_cpu(i)
2902 sum += cpu_rq(i)->nr_running;
2903
2904 return sum;
2905 }
2906
2907 unsigned long nr_uninterruptible(void)
2908 {
2909 unsigned long i, sum = 0;
2910
2911 for_each_possible_cpu(i)
2912 sum += cpu_rq(i)->nr_uninterruptible;
2913
2914 /*
2915 * Since we read the counters lockless, it might be slightly
2916 * inaccurate. Do not allow it to go below zero though:
2917 */
2918 if (unlikely((long)sum < 0))
2919 sum = 0;
2920
2921 return sum;
2922 }
2923
2924 unsigned long long nr_context_switches(void)
2925 {
2926 int i;
2927 unsigned long long sum = 0;
2928
2929 for_each_possible_cpu(i)
2930 sum += cpu_rq(i)->nr_switches;
2931
2932 return sum;
2933 }
2934
2935 unsigned long nr_iowait(void)
2936 {
2937 unsigned long i, sum = 0;
2938
2939 for_each_possible_cpu(i)
2940 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2941
2942 return sum;
2943 }
2944
2945 unsigned long nr_active(void)
2946 {
2947 unsigned long i, running = 0, uninterruptible = 0;
2948
2949 for_each_online_cpu(i) {
2950 running += cpu_rq(i)->nr_running;
2951 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2952 }
2953
2954 if (unlikely((long)uninterruptible < 0))
2955 uninterruptible = 0;
2956
2957 return running + uninterruptible;
2958 }
2959
2960 /*
2961 * Update rq->cpu_load[] statistics. This function is usually called every
2962 * scheduler tick (TICK_NSEC).
2963 */
2964 static void update_cpu_load(struct rq *this_rq)
2965 {
2966 unsigned long this_load = this_rq->load.weight;
2967 int i, scale;
2968
2969 this_rq->nr_load_updates++;
2970
2971 /* Update our load: */
2972 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2973 unsigned long old_load, new_load;
2974
2975 /* scale is effectively 1 << i now, and >> i divides by scale */
2976
2977 old_load = this_rq->cpu_load[i];
2978 new_load = this_load;
2979 /*
2980 * Round up the averaging division if load is increasing. This
2981 * prevents us from getting stuck on 9 if the load is 10, for
2982 * example.
2983 */
2984 if (new_load > old_load)
2985 new_load += scale-1;
2986 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2987 }
2988 }
2989
2990 #ifdef CONFIG_SMP
2991
2992 /*
2993 * double_rq_lock - safely lock two runqueues
2994 *
2995 * Note this does not disable interrupts like task_rq_lock,
2996 * you need to do so manually before calling.
2997 */
2998 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2999 __acquires(rq1->lock)
3000 __acquires(rq2->lock)
3001 {
3002 BUG_ON(!irqs_disabled());
3003 if (rq1 == rq2) {
3004 spin_lock(&rq1->lock);
3005 __acquire(rq2->lock); /* Fake it out ;) */
3006 } else {
3007 if (rq1 < rq2) {
3008 spin_lock(&rq1->lock);
3009 spin_lock(&rq2->lock);
3010 } else {
3011 spin_lock(&rq2->lock);
3012 spin_lock(&rq1->lock);
3013 }
3014 }
3015 update_rq_clock(rq1);
3016 update_rq_clock(rq2);
3017 }
3018
3019 /*
3020 * double_rq_unlock - safely unlock two runqueues
3021 *
3022 * Note this does not restore interrupts like task_rq_unlock,
3023 * you need to do so manually after calling.
3024 */
3025 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3026 __releases(rq1->lock)
3027 __releases(rq2->lock)
3028 {
3029 spin_unlock(&rq1->lock);
3030 if (rq1 != rq2)
3031 spin_unlock(&rq2->lock);
3032 else
3033 __release(rq2->lock);
3034 }
3035
3036 /*
3037 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3038 */
3039 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3040 __releases(this_rq->lock)
3041 __acquires(busiest->lock)
3042 __acquires(this_rq->lock)
3043 {
3044 int ret = 0;
3045
3046 if (unlikely(!irqs_disabled())) {
3047 /* printk() doesn't work good under rq->lock */
3048 spin_unlock(&this_rq->lock);
3049 BUG_ON(1);
3050 }
3051 if (unlikely(!spin_trylock(&busiest->lock))) {
3052 if (busiest < this_rq) {
3053 spin_unlock(&this_rq->lock);
3054 spin_lock(&busiest->lock);
3055 spin_lock(&this_rq->lock);
3056 ret = 1;
3057 } else
3058 spin_lock(&busiest->lock);
3059 }
3060 return ret;
3061 }
3062
3063 /*
3064 * If dest_cpu is allowed for this process, migrate the task to it.
3065 * This is accomplished by forcing the cpu_allowed mask to only
3066 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3067 * the cpu_allowed mask is restored.
3068 */
3069 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3070 {
3071 struct migration_req req;
3072 unsigned long flags;
3073 struct rq *rq;
3074
3075 rq = task_rq_lock(p, &flags);
3076 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3077 || unlikely(cpu_is_offline(dest_cpu)))
3078 goto out;
3079
3080 /* force the process onto the specified CPU */
3081 if (migrate_task(p, dest_cpu, &req)) {
3082 /* Need to wait for migration thread (might exit: take ref). */
3083 struct task_struct *mt = rq->migration_thread;
3084
3085 get_task_struct(mt);
3086 task_rq_unlock(rq, &flags);
3087 wake_up_process(mt);
3088 put_task_struct(mt);
3089 wait_for_completion(&req.done);
3090
3091 return;
3092 }
3093 out:
3094 task_rq_unlock(rq, &flags);
3095 }
3096
3097 /*
3098 * sched_exec - execve() is a valuable balancing opportunity, because at
3099 * this point the task has the smallest effective memory and cache footprint.
3100 */
3101 void sched_exec(void)
3102 {
3103 int new_cpu, this_cpu = get_cpu();
3104 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3105 put_cpu();
3106 if (new_cpu != this_cpu)
3107 sched_migrate_task(current, new_cpu);
3108 }
3109
3110 /*
3111 * pull_task - move a task from a remote runqueue to the local runqueue.
3112 * Both runqueues must be locked.
3113 */
3114 static void pull_task(struct rq *src_rq, struct task_struct *p,
3115 struct rq *this_rq, int this_cpu)
3116 {
3117 deactivate_task(src_rq, p, 0);
3118 set_task_cpu(p, this_cpu);
3119 activate_task(this_rq, p, 0);
3120 /*
3121 * Note that idle threads have a prio of MAX_PRIO, for this test
3122 * to be always true for them.
3123 */
3124 check_preempt_curr(this_rq, p);
3125 }
3126
3127 /*
3128 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3129 */
3130 static
3131 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3132 struct sched_domain *sd, enum cpu_idle_type idle,
3133 int *all_pinned)
3134 {
3135 /*
3136 * We do not migrate tasks that are:
3137 * 1) running (obviously), or
3138 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3139 * 3) are cache-hot on their current CPU.
3140 */
3141 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3142 schedstat_inc(p, se.nr_failed_migrations_affine);
3143 return 0;
3144 }
3145 *all_pinned = 0;
3146
3147 if (task_running(rq, p)) {
3148 schedstat_inc(p, se.nr_failed_migrations_running);
3149 return 0;
3150 }
3151
3152 /*
3153 * Aggressive migration if:
3154 * 1) task is cache cold, or
3155 * 2) too many balance attempts have failed.
3156 */
3157
3158 if (!task_hot(p, rq->clock, sd) ||
3159 sd->nr_balance_failed > sd->cache_nice_tries) {
3160 #ifdef CONFIG_SCHEDSTATS
3161 if (task_hot(p, rq->clock, sd)) {
3162 schedstat_inc(sd, lb_hot_gained[idle]);
3163 schedstat_inc(p, se.nr_forced_migrations);
3164 }
3165 #endif
3166 return 1;
3167 }
3168
3169 if (task_hot(p, rq->clock, sd)) {
3170 schedstat_inc(p, se.nr_failed_migrations_hot);
3171 return 0;
3172 }
3173 return 1;
3174 }
3175
3176 static unsigned long
3177 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3178 unsigned long max_load_move, struct sched_domain *sd,
3179 enum cpu_idle_type idle, int *all_pinned,
3180 int *this_best_prio, struct rq_iterator *iterator)
3181 {
3182 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3183 struct task_struct *p;
3184 long rem_load_move = max_load_move;
3185
3186 if (max_load_move == 0)
3187 goto out;
3188
3189 pinned = 1;
3190
3191 /*
3192 * Start the load-balancing iterator:
3193 */
3194 p = iterator->start(iterator->arg);
3195 next:
3196 if (!p || loops++ > sysctl_sched_nr_migrate)
3197 goto out;
3198 /*
3199 * To help distribute high priority tasks across CPUs we don't
3200 * skip a task if it will be the highest priority task (i.e. smallest
3201 * prio value) on its new queue regardless of its load weight
3202 */
3203 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3204 SCHED_LOAD_SCALE_FUZZ;
3205 if ((skip_for_load && p->prio >= *this_best_prio) ||
3206 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3207 p = iterator->next(iterator->arg);
3208 goto next;
3209 }
3210
3211 pull_task(busiest, p, this_rq, this_cpu);
3212 pulled++;
3213 rem_load_move -= p->se.load.weight;
3214
3215 /*
3216 * We only want to steal up to the prescribed amount of weighted load.
3217 */
3218 if (rem_load_move > 0) {
3219 if (p->prio < *this_best_prio)
3220 *this_best_prio = p->prio;
3221 p = iterator->next(iterator->arg);
3222 goto next;
3223 }
3224 out:
3225 /*
3226 * Right now, this is one of only two places pull_task() is called,
3227 * so we can safely collect pull_task() stats here rather than
3228 * inside pull_task().
3229 */
3230 schedstat_add(sd, lb_gained[idle], pulled);
3231
3232 if (all_pinned)
3233 *all_pinned = pinned;
3234
3235 return max_load_move - rem_load_move;
3236 }
3237
3238 /*
3239 * move_tasks tries to move up to max_load_move weighted load from busiest to
3240 * this_rq, as part of a balancing operation within domain "sd".
3241 * Returns 1 if successful and 0 otherwise.
3242 *
3243 * Called with both runqueues locked.
3244 */
3245 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3246 unsigned long max_load_move,
3247 struct sched_domain *sd, enum cpu_idle_type idle,
3248 int *all_pinned)
3249 {
3250 const struct sched_class *class = sched_class_highest;
3251 unsigned long total_load_moved = 0;
3252 int this_best_prio = this_rq->curr->prio;
3253
3254 do {
3255 total_load_moved +=
3256 class->load_balance(this_rq, this_cpu, busiest,
3257 max_load_move - total_load_moved,
3258 sd, idle, all_pinned, &this_best_prio);
3259 class = class->next;
3260 } while (class && max_load_move > total_load_moved);
3261
3262 return total_load_moved > 0;
3263 }
3264
3265 static int
3266 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3267 struct sched_domain *sd, enum cpu_idle_type idle,
3268 struct rq_iterator *iterator)
3269 {
3270 struct task_struct *p = iterator->start(iterator->arg);
3271 int pinned = 0;
3272
3273 while (p) {
3274 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3275 pull_task(busiest, p, this_rq, this_cpu);
3276 /*
3277 * Right now, this is only the second place pull_task()
3278 * is called, so we can safely collect pull_task()
3279 * stats here rather than inside pull_task().
3280 */
3281 schedstat_inc(sd, lb_gained[idle]);
3282
3283 return 1;
3284 }
3285 p = iterator->next(iterator->arg);
3286 }
3287
3288 return 0;
3289 }
3290
3291 /*
3292 * move_one_task tries to move exactly one task from busiest to this_rq, as
3293 * part of active balancing operations within "domain".
3294 * Returns 1 if successful and 0 otherwise.
3295 *
3296 * Called with both runqueues locked.
3297 */
3298 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3299 struct sched_domain *sd, enum cpu_idle_type idle)
3300 {
3301 const struct sched_class *class;
3302
3303 for (class = sched_class_highest; class; class = class->next)
3304 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3305 return 1;
3306
3307 return 0;
3308 }
3309
3310 /*
3311 * find_busiest_group finds and returns the busiest CPU group within the
3312 * domain. It calculates and returns the amount of weighted load which
3313 * should be moved to restore balance via the imbalance parameter.
3314 */
3315 static struct sched_group *
3316 find_busiest_group(struct sched_domain *sd, int this_cpu,
3317 unsigned long *imbalance, enum cpu_idle_type idle,
3318 int *sd_idle, const cpumask_t *cpus, int *balance)
3319 {
3320 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3321 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3322 unsigned long max_pull;
3323 unsigned long busiest_load_per_task, busiest_nr_running;
3324 unsigned long this_load_per_task, this_nr_running;
3325 int load_idx, group_imb = 0;
3326 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3327 int power_savings_balance = 1;
3328 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3329 unsigned long min_nr_running = ULONG_MAX;
3330 struct sched_group *group_min = NULL, *group_leader = NULL;
3331 #endif
3332
3333 max_load = this_load = total_load = total_pwr = 0;
3334 busiest_load_per_task = busiest_nr_running = 0;
3335 this_load_per_task = this_nr_running = 0;
3336 if (idle == CPU_NOT_IDLE)
3337 load_idx = sd->busy_idx;
3338 else if (idle == CPU_NEWLY_IDLE)
3339 load_idx = sd->newidle_idx;
3340 else
3341 load_idx = sd->idle_idx;
3342
3343 do {
3344 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3345 int local_group;
3346 int i;
3347 int __group_imb = 0;
3348 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3349 unsigned long sum_nr_running, sum_weighted_load;
3350
3351 local_group = cpu_isset(this_cpu, group->cpumask);
3352
3353 if (local_group)
3354 balance_cpu = first_cpu(group->cpumask);
3355
3356 /* Tally up the load of all CPUs in the group */
3357 sum_weighted_load = sum_nr_running = avg_load = 0;
3358 max_cpu_load = 0;
3359 min_cpu_load = ~0UL;
3360
3361 for_each_cpu_mask(i, group->cpumask) {
3362 struct rq *rq;
3363
3364 if (!cpu_isset(i, *cpus))
3365 continue;
3366
3367 rq = cpu_rq(i);
3368
3369 if (*sd_idle && rq->nr_running)
3370 *sd_idle = 0;
3371
3372 /* Bias balancing toward cpus of our domain */
3373 if (local_group) {
3374 if (idle_cpu(i) && !first_idle_cpu) {
3375 first_idle_cpu = 1;
3376 balance_cpu = i;
3377 }
3378
3379 load = target_load(i, load_idx);
3380 } else {
3381 load = source_load(i, load_idx);
3382 if (load > max_cpu_load)
3383 max_cpu_load = load;
3384 if (min_cpu_load > load)
3385 min_cpu_load = load;
3386 }
3387
3388 avg_load += load;
3389 sum_nr_running += rq->nr_running;
3390 sum_weighted_load += weighted_cpuload(i);
3391 }
3392
3393 /*
3394 * First idle cpu or the first cpu(busiest) in this sched group
3395 * is eligible for doing load balancing at this and above
3396 * domains. In the newly idle case, we will allow all the cpu's
3397 * to do the newly idle load balance.
3398 */
3399 if (idle != CPU_NEWLY_IDLE && local_group &&
3400 balance_cpu != this_cpu && balance) {
3401 *balance = 0;
3402 goto ret;
3403 }
3404
3405 total_load += avg_load;
3406 total_pwr += group->__cpu_power;
3407
3408 /* Adjust by relative CPU power of the group */
3409 avg_load = sg_div_cpu_power(group,
3410 avg_load * SCHED_LOAD_SCALE);
3411
3412 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3413 __group_imb = 1;
3414
3415 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3416
3417 if (local_group) {
3418 this_load = avg_load;
3419 this = group;
3420 this_nr_running = sum_nr_running;
3421 this_load_per_task = sum_weighted_load;
3422 } else if (avg_load > max_load &&
3423 (sum_nr_running > group_capacity || __group_imb)) {
3424 max_load = avg_load;
3425 busiest = group;
3426 busiest_nr_running = sum_nr_running;
3427 busiest_load_per_task = sum_weighted_load;
3428 group_imb = __group_imb;
3429 }
3430
3431 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3432 /*
3433 * Busy processors will not participate in power savings
3434 * balance.
3435 */
3436 if (idle == CPU_NOT_IDLE ||
3437 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3438 goto group_next;
3439
3440 /*
3441 * If the local group is idle or completely loaded
3442 * no need to do power savings balance at this domain
3443 */
3444 if (local_group && (this_nr_running >= group_capacity ||
3445 !this_nr_running))
3446 power_savings_balance = 0;
3447
3448 /*
3449 * If a group is already running at full capacity or idle,
3450 * don't include that group in power savings calculations
3451 */
3452 if (!power_savings_balance || sum_nr_running >= group_capacity
3453 || !sum_nr_running)
3454 goto group_next;
3455
3456 /*
3457 * Calculate the group which has the least non-idle load.
3458 * This is the group from where we need to pick up the load
3459 * for saving power
3460 */
3461 if ((sum_nr_running < min_nr_running) ||
3462 (sum_nr_running == min_nr_running &&
3463 first_cpu(group->cpumask) <
3464 first_cpu(group_min->cpumask))) {
3465 group_min = group;
3466 min_nr_running = sum_nr_running;
3467 min_load_per_task = sum_weighted_load /
3468 sum_nr_running;
3469 }
3470
3471 /*
3472 * Calculate the group which is almost near its
3473 * capacity but still has some space to pick up some load
3474 * from other group and save more power
3475 */
3476 if (sum_nr_running <= group_capacity - 1) {
3477 if (sum_nr_running > leader_nr_running ||
3478 (sum_nr_running == leader_nr_running &&
3479 first_cpu(group->cpumask) >
3480 first_cpu(group_leader->cpumask))) {
3481 group_leader = group;
3482 leader_nr_running = sum_nr_running;
3483 }
3484 }
3485 group_next:
3486 #endif
3487 group = group->next;
3488 } while (group != sd->groups);
3489
3490 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3491 goto out_balanced;
3492
3493 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3494
3495 if (this_load >= avg_load ||
3496 100*max_load <= sd->imbalance_pct*this_load)
3497 goto out_balanced;
3498
3499 busiest_load_per_task /= busiest_nr_running;
3500 if (group_imb)
3501 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3502
3503 /*
3504 * We're trying to get all the cpus to the average_load, so we don't
3505 * want to push ourselves above the average load, nor do we wish to
3506 * reduce the max loaded cpu below the average load, as either of these
3507 * actions would just result in more rebalancing later, and ping-pong
3508 * tasks around. Thus we look for the minimum possible imbalance.
3509 * Negative imbalances (*we* are more loaded than anyone else) will
3510 * be counted as no imbalance for these purposes -- we can't fix that
3511 * by pulling tasks to us. Be careful of negative numbers as they'll
3512 * appear as very large values with unsigned longs.
3513 */
3514 if (max_load <= busiest_load_per_task)
3515 goto out_balanced;
3516
3517 /*
3518 * In the presence of smp nice balancing, certain scenarios can have
3519 * max load less than avg load(as we skip the groups at or below
3520 * its cpu_power, while calculating max_load..)
3521 */
3522 if (max_load < avg_load) {
3523 *imbalance = 0;
3524 goto small_imbalance;
3525 }
3526
3527 /* Don't want to pull so many tasks that a group would go idle */
3528 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3529
3530 /* How much load to actually move to equalise the imbalance */
3531 *imbalance = min(max_pull * busiest->__cpu_power,
3532 (avg_load - this_load) * this->__cpu_power)
3533 / SCHED_LOAD_SCALE;
3534
3535 /*
3536 * if *imbalance is less than the average load per runnable task
3537 * there is no gaurantee that any tasks will be moved so we'll have
3538 * a think about bumping its value to force at least one task to be
3539 * moved
3540 */
3541 if (*imbalance < busiest_load_per_task) {
3542 unsigned long tmp, pwr_now, pwr_move;
3543 unsigned int imbn;
3544
3545 small_imbalance:
3546 pwr_move = pwr_now = 0;
3547 imbn = 2;
3548 if (this_nr_running) {
3549 this_load_per_task /= this_nr_running;
3550 if (busiest_load_per_task > this_load_per_task)
3551 imbn = 1;
3552 } else
3553 this_load_per_task = SCHED_LOAD_SCALE;
3554
3555 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3556 busiest_load_per_task * imbn) {
3557 *imbalance = busiest_load_per_task;
3558 return busiest;
3559 }
3560
3561 /*
3562 * OK, we don't have enough imbalance to justify moving tasks,
3563 * however we may be able to increase total CPU power used by
3564 * moving them.
3565 */
3566
3567 pwr_now += busiest->__cpu_power *
3568 min(busiest_load_per_task, max_load);
3569 pwr_now += this->__cpu_power *
3570 min(this_load_per_task, this_load);
3571 pwr_now /= SCHED_LOAD_SCALE;
3572
3573 /* Amount of load we'd subtract */
3574 tmp = sg_div_cpu_power(busiest,
3575 busiest_load_per_task * SCHED_LOAD_SCALE);
3576 if (max_load > tmp)
3577 pwr_move += busiest->__cpu_power *
3578 min(busiest_load_per_task, max_load - tmp);
3579
3580 /* Amount of load we'd add */
3581 if (max_load * busiest->__cpu_power <
3582 busiest_load_per_task * SCHED_LOAD_SCALE)
3583 tmp = sg_div_cpu_power(this,
3584 max_load * busiest->__cpu_power);
3585 else
3586 tmp = sg_div_cpu_power(this,
3587 busiest_load_per_task * SCHED_LOAD_SCALE);
3588 pwr_move += this->__cpu_power *
3589 min(this_load_per_task, this_load + tmp);
3590 pwr_move /= SCHED_LOAD_SCALE;
3591
3592 /* Move if we gain throughput */
3593 if (pwr_move > pwr_now)
3594 *imbalance = busiest_load_per_task;
3595 }
3596
3597 return busiest;
3598
3599 out_balanced:
3600 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3601 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3602 goto ret;
3603
3604 if (this == group_leader && group_leader != group_min) {
3605 *imbalance = min_load_per_task;
3606 return group_min;
3607 }
3608 #endif
3609 ret:
3610 *imbalance = 0;
3611 return NULL;
3612 }
3613
3614 /*
3615 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3616 */
3617 static struct rq *
3618 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3619 unsigned long imbalance, const cpumask_t *cpus)
3620 {
3621 struct rq *busiest = NULL, *rq;
3622 unsigned long max_load = 0;
3623 int i;
3624
3625 for_each_cpu_mask(i, group->cpumask) {
3626 unsigned long wl;
3627
3628 if (!cpu_isset(i, *cpus))
3629 continue;
3630
3631 rq = cpu_rq(i);
3632 wl = weighted_cpuload(i);
3633
3634 if (rq->nr_running == 1 && wl > imbalance)
3635 continue;
3636
3637 if (wl > max_load) {
3638 max_load = wl;
3639 busiest = rq;
3640 }
3641 }
3642
3643 return busiest;
3644 }
3645
3646 /*
3647 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3648 * so long as it is large enough.
3649 */
3650 #define MAX_PINNED_INTERVAL 512
3651
3652 /*
3653 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3654 * tasks if there is an imbalance.
3655 */
3656 static int load_balance(int this_cpu, struct rq *this_rq,
3657 struct sched_domain *sd, enum cpu_idle_type idle,
3658 int *balance, cpumask_t *cpus)
3659 {
3660 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3661 struct sched_group *group;
3662 unsigned long imbalance;
3663 struct rq *busiest;
3664 unsigned long flags;
3665 int unlock_aggregate;
3666
3667 cpus_setall(*cpus);
3668
3669 unlock_aggregate = get_aggregate(sd);
3670
3671 /*
3672 * When power savings policy is enabled for the parent domain, idle
3673 * sibling can pick up load irrespective of busy siblings. In this case,
3674 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3675 * portraying it as CPU_NOT_IDLE.
3676 */
3677 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3678 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3679 sd_idle = 1;
3680
3681 schedstat_inc(sd, lb_count[idle]);
3682
3683 redo:
3684 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3685 cpus, balance);
3686
3687 if (*balance == 0)
3688 goto out_balanced;
3689
3690 if (!group) {
3691 schedstat_inc(sd, lb_nobusyg[idle]);
3692 goto out_balanced;
3693 }
3694
3695 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3696 if (!busiest) {
3697 schedstat_inc(sd, lb_nobusyq[idle]);
3698 goto out_balanced;
3699 }
3700
3701 BUG_ON(busiest == this_rq);
3702
3703 schedstat_add(sd, lb_imbalance[idle], imbalance);
3704
3705 ld_moved = 0;
3706 if (busiest->nr_running > 1) {
3707 /*
3708 * Attempt to move tasks. If find_busiest_group has found
3709 * an imbalance but busiest->nr_running <= 1, the group is
3710 * still unbalanced. ld_moved simply stays zero, so it is
3711 * correctly treated as an imbalance.
3712 */
3713 local_irq_save(flags);
3714 double_rq_lock(this_rq, busiest);
3715 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3716 imbalance, sd, idle, &all_pinned);
3717 double_rq_unlock(this_rq, busiest);
3718 local_irq_restore(flags);
3719
3720 /*
3721 * some other cpu did the load balance for us.
3722 */
3723 if (ld_moved && this_cpu != smp_processor_id())
3724 resched_cpu(this_cpu);
3725
3726 /* All tasks on this runqueue were pinned by CPU affinity */
3727 if (unlikely(all_pinned)) {
3728 cpu_clear(cpu_of(busiest), *cpus);
3729 if (!cpus_empty(*cpus))
3730 goto redo;
3731 goto out_balanced;
3732 }
3733 }
3734
3735 if (!ld_moved) {
3736 schedstat_inc(sd, lb_failed[idle]);
3737 sd->nr_balance_failed++;
3738
3739 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3740
3741 spin_lock_irqsave(&busiest->lock, flags);
3742
3743 /* don't kick the migration_thread, if the curr
3744 * task on busiest cpu can't be moved to this_cpu
3745 */
3746 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3747 spin_unlock_irqrestore(&busiest->lock, flags);
3748 all_pinned = 1;
3749 goto out_one_pinned;
3750 }
3751
3752 if (!busiest->active_balance) {
3753 busiest->active_balance = 1;
3754 busiest->push_cpu = this_cpu;
3755 active_balance = 1;
3756 }
3757 spin_unlock_irqrestore(&busiest->lock, flags);
3758 if (active_balance)
3759 wake_up_process(busiest->migration_thread);
3760
3761 /*
3762 * We've kicked active balancing, reset the failure
3763 * counter.
3764 */
3765 sd->nr_balance_failed = sd->cache_nice_tries+1;
3766 }
3767 } else
3768 sd->nr_balance_failed = 0;
3769
3770 if (likely(!active_balance)) {
3771 /* We were unbalanced, so reset the balancing interval */
3772 sd->balance_interval = sd->min_interval;
3773 } else {
3774 /*
3775 * If we've begun active balancing, start to back off. This
3776 * case may not be covered by the all_pinned logic if there
3777 * is only 1 task on the busy runqueue (because we don't call
3778 * move_tasks).
3779 */
3780 if (sd->balance_interval < sd->max_interval)
3781 sd->balance_interval *= 2;
3782 }
3783
3784 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3785 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3786 ld_moved = -1;
3787
3788 goto out;
3789
3790 out_balanced:
3791 schedstat_inc(sd, lb_balanced[idle]);
3792
3793 sd->nr_balance_failed = 0;
3794
3795 out_one_pinned:
3796 /* tune up the balancing interval */
3797 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3798 (sd->balance_interval < sd->max_interval))
3799 sd->balance_interval *= 2;
3800
3801 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3802 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3803 ld_moved = -1;
3804 else
3805 ld_moved = 0;
3806 out:
3807 if (unlock_aggregate)
3808 put_aggregate(sd);
3809 return ld_moved;
3810 }
3811
3812 /*
3813 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3814 * tasks if there is an imbalance.
3815 *
3816 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3817 * this_rq is locked.
3818 */
3819 static int
3820 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3821 cpumask_t *cpus)
3822 {
3823 struct sched_group *group;
3824 struct rq *busiest = NULL;
3825 unsigned long imbalance;
3826 int ld_moved = 0;
3827 int sd_idle = 0;
3828 int all_pinned = 0;
3829
3830 cpus_setall(*cpus);
3831
3832 /*
3833 * When power savings policy is enabled for the parent domain, idle
3834 * sibling can pick up load irrespective of busy siblings. In this case,
3835 * let the state of idle sibling percolate up as IDLE, instead of
3836 * portraying it as CPU_NOT_IDLE.
3837 */
3838 if (sd->flags & SD_SHARE_CPUPOWER &&
3839 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3840 sd_idle = 1;
3841
3842 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3843 redo:
3844 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3845 &sd_idle, cpus, NULL);
3846 if (!group) {
3847 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3848 goto out_balanced;
3849 }
3850
3851 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3852 if (!busiest) {
3853 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3854 goto out_balanced;
3855 }
3856
3857 BUG_ON(busiest == this_rq);
3858
3859 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3860
3861 ld_moved = 0;
3862 if (busiest->nr_running > 1) {
3863 /* Attempt to move tasks */
3864 double_lock_balance(this_rq, busiest);
3865 /* this_rq->clock is already updated */
3866 update_rq_clock(busiest);
3867 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3868 imbalance, sd, CPU_NEWLY_IDLE,
3869 &all_pinned);
3870 spin_unlock(&busiest->lock);
3871
3872 if (unlikely(all_pinned)) {
3873 cpu_clear(cpu_of(busiest), *cpus);
3874 if (!cpus_empty(*cpus))
3875 goto redo;
3876 }
3877 }
3878
3879 if (!ld_moved) {
3880 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3881 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3882 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3883 return -1;
3884 } else
3885 sd->nr_balance_failed = 0;
3886
3887 return ld_moved;
3888
3889 out_balanced:
3890 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3891 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3892 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3893 return -1;
3894 sd->nr_balance_failed = 0;
3895
3896 return 0;
3897 }
3898
3899 /*
3900 * idle_balance is called by schedule() if this_cpu is about to become
3901 * idle. Attempts to pull tasks from other CPUs.
3902 */
3903 static void idle_balance(int this_cpu, struct rq *this_rq)
3904 {
3905 struct sched_domain *sd;
3906 int pulled_task = -1;
3907 unsigned long next_balance = jiffies + HZ;
3908 cpumask_t tmpmask;
3909
3910 for_each_domain(this_cpu, sd) {
3911 unsigned long interval;
3912
3913 if (!(sd->flags & SD_LOAD_BALANCE))
3914 continue;
3915
3916 if (sd->flags & SD_BALANCE_NEWIDLE)
3917 /* If we've pulled tasks over stop searching: */
3918 pulled_task = load_balance_newidle(this_cpu, this_rq,
3919 sd, &tmpmask);
3920
3921 interval = msecs_to_jiffies(sd->balance_interval);
3922 if (time_after(next_balance, sd->last_balance + interval))
3923 next_balance = sd->last_balance + interval;
3924 if (pulled_task)
3925 break;
3926 }
3927 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3928 /*
3929 * We are going idle. next_balance may be set based on
3930 * a busy processor. So reset next_balance.
3931 */
3932 this_rq->next_balance = next_balance;
3933 }
3934 }
3935
3936 /*
3937 * active_load_balance is run by migration threads. It pushes running tasks
3938 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3939 * running on each physical CPU where possible, and avoids physical /
3940 * logical imbalances.
3941 *
3942 * Called with busiest_rq locked.
3943 */
3944 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3945 {
3946 int target_cpu = busiest_rq->push_cpu;
3947 struct sched_domain *sd;
3948 struct rq *target_rq;
3949
3950 /* Is there any task to move? */
3951 if (busiest_rq->nr_running <= 1)
3952 return;
3953
3954 target_rq = cpu_rq(target_cpu);
3955
3956 /*
3957 * This condition is "impossible", if it occurs
3958 * we need to fix it. Originally reported by
3959 * Bjorn Helgaas on a 128-cpu setup.
3960 */
3961 BUG_ON(busiest_rq == target_rq);
3962
3963 /* move a task from busiest_rq to target_rq */
3964 double_lock_balance(busiest_rq, target_rq);
3965 update_rq_clock(busiest_rq);
3966 update_rq_clock(target_rq);
3967
3968 /* Search for an sd spanning us and the target CPU. */
3969 for_each_domain(target_cpu, sd) {
3970 if ((sd->flags & SD_LOAD_BALANCE) &&
3971 cpu_isset(busiest_cpu, sd->span))
3972 break;
3973 }
3974
3975 if (likely(sd)) {
3976 schedstat_inc(sd, alb_count);
3977
3978 if (move_one_task(target_rq, target_cpu, busiest_rq,
3979 sd, CPU_IDLE))
3980 schedstat_inc(sd, alb_pushed);
3981 else
3982 schedstat_inc(sd, alb_failed);
3983 }
3984 spin_unlock(&target_rq->lock);
3985 }
3986
3987 #ifdef CONFIG_NO_HZ
3988 static struct {
3989 atomic_t load_balancer;
3990 cpumask_t cpu_mask;
3991 } nohz ____cacheline_aligned = {
3992 .load_balancer = ATOMIC_INIT(-1),
3993 .cpu_mask = CPU_MASK_NONE,
3994 };
3995
3996 /*
3997 * This routine will try to nominate the ilb (idle load balancing)
3998 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3999 * load balancing on behalf of all those cpus. If all the cpus in the system
4000 * go into this tickless mode, then there will be no ilb owner (as there is
4001 * no need for one) and all the cpus will sleep till the next wakeup event
4002 * arrives...
4003 *
4004 * For the ilb owner, tick is not stopped. And this tick will be used
4005 * for idle load balancing. ilb owner will still be part of
4006 * nohz.cpu_mask..
4007 *
4008 * While stopping the tick, this cpu will become the ilb owner if there
4009 * is no other owner. And will be the owner till that cpu becomes busy
4010 * or if all cpus in the system stop their ticks at which point
4011 * there is no need for ilb owner.
4012 *
4013 * When the ilb owner becomes busy, it nominates another owner, during the
4014 * next busy scheduler_tick()
4015 */
4016 int select_nohz_load_balancer(int stop_tick)
4017 {
4018 int cpu = smp_processor_id();
4019
4020 if (stop_tick) {
4021 cpu_set(cpu, nohz.cpu_mask);
4022 cpu_rq(cpu)->in_nohz_recently = 1;
4023
4024 /*
4025 * If we are going offline and still the leader, give up!
4026 */
4027 if (cpu_is_offline(cpu) &&
4028 atomic_read(&nohz.load_balancer) == cpu) {
4029 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4030 BUG();
4031 return 0;
4032 }
4033
4034 /* time for ilb owner also to sleep */
4035 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4036 if (atomic_read(&nohz.load_balancer) == cpu)
4037 atomic_set(&nohz.load_balancer, -1);
4038 return 0;
4039 }
4040
4041 if (atomic_read(&nohz.load_balancer) == -1) {
4042 /* make me the ilb owner */
4043 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4044 return 1;
4045 } else if (atomic_read(&nohz.load_balancer) == cpu)
4046 return 1;
4047 } else {
4048 if (!cpu_isset(cpu, nohz.cpu_mask))
4049 return 0;
4050
4051 cpu_clear(cpu, nohz.cpu_mask);
4052
4053 if (atomic_read(&nohz.load_balancer) == cpu)
4054 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4055 BUG();
4056 }
4057 return 0;
4058 }
4059 #endif
4060
4061 static DEFINE_SPINLOCK(balancing);
4062
4063 /*
4064 * It checks each scheduling domain to see if it is due to be balanced,
4065 * and initiates a balancing operation if so.
4066 *
4067 * Balancing parameters are set up in arch_init_sched_domains.
4068 */
4069 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4070 {
4071 int balance = 1;
4072 struct rq *rq = cpu_rq(cpu);
4073 unsigned long interval;
4074 struct sched_domain *sd;
4075 /* Earliest time when we have to do rebalance again */
4076 unsigned long next_balance = jiffies + 60*HZ;
4077 int update_next_balance = 0;
4078 cpumask_t tmp;
4079
4080 for_each_domain(cpu, sd) {
4081 if (!(sd->flags & SD_LOAD_BALANCE))
4082 continue;
4083
4084 interval = sd->balance_interval;
4085 if (idle != CPU_IDLE)
4086 interval *= sd->busy_factor;
4087
4088 /* scale ms to jiffies */
4089 interval = msecs_to_jiffies(interval);
4090 if (unlikely(!interval))
4091 interval = 1;
4092 if (interval > HZ*NR_CPUS/10)
4093 interval = HZ*NR_CPUS/10;
4094
4095
4096 if (sd->flags & SD_SERIALIZE) {
4097 if (!spin_trylock(&balancing))
4098 goto out;
4099 }
4100
4101 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4102 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4103 /*
4104 * We've pulled tasks over so either we're no
4105 * longer idle, or one of our SMT siblings is
4106 * not idle.
4107 */
4108 idle = CPU_NOT_IDLE;
4109 }
4110 sd->last_balance = jiffies;
4111 }
4112 if (sd->flags & SD_SERIALIZE)
4113 spin_unlock(&balancing);
4114 out:
4115 if (time_after(next_balance, sd->last_balance + interval)) {
4116 next_balance = sd->last_balance + interval;
4117 update_next_balance = 1;
4118 }
4119
4120 /*
4121 * Stop the load balance at this level. There is another
4122 * CPU in our sched group which is doing load balancing more
4123 * actively.
4124 */
4125 if (!balance)
4126 break;
4127 }
4128
4129 /*
4130 * next_balance will be updated only when there is a need.
4131 * When the cpu is attached to null domain for ex, it will not be
4132 * updated.
4133 */
4134 if (likely(update_next_balance))
4135 rq->next_balance = next_balance;
4136 }
4137
4138 /*
4139 * run_rebalance_domains is triggered when needed from the scheduler tick.
4140 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4141 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4142 */
4143 static void run_rebalance_domains(struct softirq_action *h)
4144 {
4145 int this_cpu = smp_processor_id();
4146 struct rq *this_rq = cpu_rq(this_cpu);
4147 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4148 CPU_IDLE : CPU_NOT_IDLE;
4149
4150 rebalance_domains(this_cpu, idle);
4151
4152 #ifdef CONFIG_NO_HZ
4153 /*
4154 * If this cpu is the owner for idle load balancing, then do the
4155 * balancing on behalf of the other idle cpus whose ticks are
4156 * stopped.
4157 */
4158 if (this_rq->idle_at_tick &&
4159 atomic_read(&nohz.load_balancer) == this_cpu) {
4160 cpumask_t cpus = nohz.cpu_mask;
4161 struct rq *rq;
4162 int balance_cpu;
4163
4164 cpu_clear(this_cpu, cpus);
4165 for_each_cpu_mask(balance_cpu, cpus) {
4166 /*
4167 * If this cpu gets work to do, stop the load balancing
4168 * work being done for other cpus. Next load
4169 * balancing owner will pick it up.
4170 */
4171 if (need_resched())
4172 break;
4173
4174 rebalance_domains(balance_cpu, CPU_IDLE);
4175
4176 rq = cpu_rq(balance_cpu);
4177 if (time_after(this_rq->next_balance, rq->next_balance))
4178 this_rq->next_balance = rq->next_balance;
4179 }
4180 }
4181 #endif
4182 }
4183
4184 /*
4185 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4186 *
4187 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4188 * idle load balancing owner or decide to stop the periodic load balancing,
4189 * if the whole system is idle.
4190 */
4191 static inline void trigger_load_balance(struct rq *rq, int cpu)
4192 {
4193 #ifdef CONFIG_NO_HZ
4194 /*
4195 * If we were in the nohz mode recently and busy at the current
4196 * scheduler tick, then check if we need to nominate new idle
4197 * load balancer.
4198 */
4199 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4200 rq->in_nohz_recently = 0;
4201
4202 if (atomic_read(&nohz.load_balancer) == cpu) {
4203 cpu_clear(cpu, nohz.cpu_mask);
4204 atomic_set(&nohz.load_balancer, -1);
4205 }
4206
4207 if (atomic_read(&nohz.load_balancer) == -1) {
4208 /*
4209 * simple selection for now: Nominate the
4210 * first cpu in the nohz list to be the next
4211 * ilb owner.
4212 *
4213 * TBD: Traverse the sched domains and nominate
4214 * the nearest cpu in the nohz.cpu_mask.
4215 */
4216 int ilb = first_cpu(nohz.cpu_mask);
4217
4218 if (ilb < nr_cpu_ids)
4219 resched_cpu(ilb);
4220 }
4221 }
4222
4223 /*
4224 * If this cpu is idle and doing idle load balancing for all the
4225 * cpus with ticks stopped, is it time for that to stop?
4226 */
4227 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4228 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4229 resched_cpu(cpu);
4230 return;
4231 }
4232
4233 /*
4234 * If this cpu is idle and the idle load balancing is done by
4235 * someone else, then no need raise the SCHED_SOFTIRQ
4236 */
4237 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4238 cpu_isset(cpu, nohz.cpu_mask))
4239 return;
4240 #endif
4241 if (time_after_eq(jiffies, rq->next_balance))
4242 raise_softirq(SCHED_SOFTIRQ);
4243 }
4244
4245 #else /* CONFIG_SMP */
4246
4247 /*
4248 * on UP we do not need to balance between CPUs:
4249 */
4250 static inline void idle_balance(int cpu, struct rq *rq)
4251 {
4252 }
4253
4254 #endif
4255
4256 DEFINE_PER_CPU(struct kernel_stat, kstat);
4257
4258 EXPORT_PER_CPU_SYMBOL(kstat);
4259
4260 /*
4261 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4262 * that have not yet been banked in case the task is currently running.
4263 */
4264 unsigned long long task_sched_runtime(struct task_struct *p)
4265 {
4266 unsigned long flags;
4267 u64 ns, delta_exec;
4268 struct rq *rq;
4269
4270 rq = task_rq_lock(p, &flags);
4271 ns = p->se.sum_exec_runtime;
4272 if (task_current(rq, p)) {
4273 update_rq_clock(rq);
4274 delta_exec = rq->clock - p->se.exec_start;
4275 if ((s64)delta_exec > 0)
4276 ns += delta_exec;
4277 }
4278 task_rq_unlock(rq, &flags);
4279
4280 return ns;
4281 }
4282
4283 /*
4284 * Account user cpu time to a process.
4285 * @p: the process that the cpu time gets accounted to
4286 * @cputime: the cpu time spent in user space since the last update
4287 */
4288 void account_user_time(struct task_struct *p, cputime_t cputime)
4289 {
4290 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4291 cputime64_t tmp;
4292
4293 p->utime = cputime_add(p->utime, cputime);
4294
4295 /* Add user time to cpustat. */
4296 tmp = cputime_to_cputime64(cputime);
4297 if (TASK_NICE(p) > 0)
4298 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4299 else
4300 cpustat->user = cputime64_add(cpustat->user, tmp);
4301 }
4302
4303 /*
4304 * Account guest cpu time to a process.
4305 * @p: the process that the cpu time gets accounted to
4306 * @cputime: the cpu time spent in virtual machine since the last update
4307 */
4308 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4309 {
4310 cputime64_t tmp;
4311 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4312
4313 tmp = cputime_to_cputime64(cputime);
4314
4315 p->utime = cputime_add(p->utime, cputime);
4316 p->gtime = cputime_add(p->gtime, cputime);
4317
4318 cpustat->user = cputime64_add(cpustat->user, tmp);
4319 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4320 }
4321
4322 /*
4323 * Account scaled user cpu time to a process.
4324 * @p: the process that the cpu time gets accounted to
4325 * @cputime: the cpu time spent in user space since the last update
4326 */
4327 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4328 {
4329 p->utimescaled = cputime_add(p->utimescaled, cputime);
4330 }
4331
4332 /*
4333 * Account system cpu time to a process.
4334 * @p: the process that the cpu time gets accounted to
4335 * @hardirq_offset: the offset to subtract from hardirq_count()
4336 * @cputime: the cpu time spent in kernel space since the last update
4337 */
4338 void account_system_time(struct task_struct *p, int hardirq_offset,
4339 cputime_t cputime)
4340 {
4341 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4342 struct rq *rq = this_rq();
4343 cputime64_t tmp;
4344
4345 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4346 account_guest_time(p, cputime);
4347 return;
4348 }
4349
4350 p->stime = cputime_add(p->stime, cputime);
4351
4352 /* Add system time to cpustat. */
4353 tmp = cputime_to_cputime64(cputime);
4354 if (hardirq_count() - hardirq_offset)
4355 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4356 else if (softirq_count())
4357 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4358 else if (p != rq->idle)
4359 cpustat->system = cputime64_add(cpustat->system, tmp);
4360 else if (atomic_read(&rq->nr_iowait) > 0)
4361 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4362 else
4363 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4364 /* Account for system time used */
4365 acct_update_integrals(p);
4366 }
4367
4368 /*
4369 * Account scaled system cpu time to a process.
4370 * @p: the process that the cpu time gets accounted to
4371 * @hardirq_offset: the offset to subtract from hardirq_count()
4372 * @cputime: the cpu time spent in kernel space since the last update
4373 */
4374 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4375 {
4376 p->stimescaled = cputime_add(p->stimescaled, cputime);
4377 }
4378
4379 /*
4380 * Account for involuntary wait time.
4381 * @p: the process from which the cpu time has been stolen
4382 * @steal: the cpu time spent in involuntary wait
4383 */
4384 void account_steal_time(struct task_struct *p, cputime_t steal)
4385 {
4386 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4387 cputime64_t tmp = cputime_to_cputime64(steal);
4388 struct rq *rq = this_rq();
4389
4390 if (p == rq->idle) {
4391 p->stime = cputime_add(p->stime, steal);
4392 if (atomic_read(&rq->nr_iowait) > 0)
4393 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4394 else
4395 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4396 } else
4397 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4398 }
4399
4400 /*
4401 * This function gets called by the timer code, with HZ frequency.
4402 * We call it with interrupts disabled.
4403 *
4404 * It also gets called by the fork code, when changing the parent's
4405 * timeslices.
4406 */
4407 void scheduler_tick(void)
4408 {
4409 int cpu = smp_processor_id();
4410 struct rq *rq = cpu_rq(cpu);
4411 struct task_struct *curr = rq->curr;
4412
4413 sched_clock_tick();
4414
4415 spin_lock(&rq->lock);
4416 update_rq_clock(rq);
4417 update_cpu_load(rq);
4418 curr->sched_class->task_tick(rq, curr, 0);
4419 spin_unlock(&rq->lock);
4420
4421 #ifdef CONFIG_SMP
4422 rq->idle_at_tick = idle_cpu(cpu);
4423 trigger_load_balance(rq, cpu);
4424 #endif
4425 }
4426
4427 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4428 defined(CONFIG_PREEMPT_TRACER))
4429
4430 static inline unsigned long get_parent_ip(unsigned long addr)
4431 {
4432 if (in_lock_functions(addr)) {
4433 addr = CALLER_ADDR2;
4434 if (in_lock_functions(addr))
4435 addr = CALLER_ADDR3;
4436 }
4437 return addr;
4438 }
4439
4440 void __kprobes add_preempt_count(int val)
4441 {
4442 #ifdef CONFIG_DEBUG_PREEMPT
4443 /*
4444 * Underflow?
4445 */
4446 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4447 return;
4448 #endif
4449 preempt_count() += val;
4450 #ifdef CONFIG_DEBUG_PREEMPT
4451 /*
4452 * Spinlock count overflowing soon?
4453 */
4454 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4455 PREEMPT_MASK - 10);
4456 #endif
4457 if (preempt_count() == val)
4458 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4459 }
4460 EXPORT_SYMBOL(add_preempt_count);
4461
4462 void __kprobes sub_preempt_count(int val)
4463 {
4464 #ifdef CONFIG_DEBUG_PREEMPT
4465 /*
4466 * Underflow?
4467 */
4468 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4469 return;
4470 /*
4471 * Is the spinlock portion underflowing?
4472 */
4473 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4474 !(preempt_count() & PREEMPT_MASK)))
4475 return;
4476 #endif
4477
4478 if (preempt_count() == val)
4479 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4480 preempt_count() -= val;
4481 }
4482 EXPORT_SYMBOL(sub_preempt_count);
4483
4484 #endif
4485
4486 /*
4487 * Print scheduling while atomic bug:
4488 */
4489 static noinline void __schedule_bug(struct task_struct *prev)
4490 {
4491 struct pt_regs *regs = get_irq_regs();
4492
4493 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4494 prev->comm, prev->pid, preempt_count());
4495
4496 debug_show_held_locks(prev);
4497 if (irqs_disabled())
4498 print_irqtrace_events(prev);
4499
4500 if (regs)
4501 show_regs(regs);
4502 else
4503 dump_stack();
4504 }
4505
4506 /*
4507 * Various schedule()-time debugging checks and statistics:
4508 */
4509 static inline void schedule_debug(struct task_struct *prev)
4510 {
4511 /*
4512 * Test if we are atomic. Since do_exit() needs to call into
4513 * schedule() atomically, we ignore that path for now.
4514 * Otherwise, whine if we are scheduling when we should not be.
4515 */
4516 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4517 __schedule_bug(prev);
4518
4519 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4520
4521 schedstat_inc(this_rq(), sched_count);
4522 #ifdef CONFIG_SCHEDSTATS
4523 if (unlikely(prev->lock_depth >= 0)) {
4524 schedstat_inc(this_rq(), bkl_count);
4525 schedstat_inc(prev, sched_info.bkl_count);
4526 }
4527 #endif
4528 }
4529
4530 /*
4531 * Pick up the highest-prio task:
4532 */
4533 static inline struct task_struct *
4534 pick_next_task(struct rq *rq, struct task_struct *prev)
4535 {
4536 const struct sched_class *class;
4537 struct task_struct *p;
4538
4539 /*
4540 * Optimization: we know that if all tasks are in
4541 * the fair class we can call that function directly:
4542 */
4543 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4544 p = fair_sched_class.pick_next_task(rq);
4545 if (likely(p))
4546 return p;
4547 }
4548
4549 class = sched_class_highest;
4550 for ( ; ; ) {
4551 p = class->pick_next_task(rq);
4552 if (p)
4553 return p;
4554 /*
4555 * Will never be NULL as the idle class always
4556 * returns a non-NULL p:
4557 */
4558 class = class->next;
4559 }
4560 }
4561
4562 /*
4563 * schedule() is the main scheduler function.
4564 */
4565 asmlinkage void __sched schedule(void)
4566 {
4567 struct task_struct *prev, *next;
4568 unsigned long *switch_count;
4569 struct rq *rq;
4570 int cpu;
4571
4572 need_resched:
4573 preempt_disable();
4574 cpu = smp_processor_id();
4575 rq = cpu_rq(cpu);
4576 rcu_qsctr_inc(cpu);
4577 prev = rq->curr;
4578 switch_count = &prev->nivcsw;
4579
4580 release_kernel_lock(prev);
4581 need_resched_nonpreemptible:
4582
4583 schedule_debug(prev);
4584
4585 hrtick_clear(rq);
4586
4587 /*
4588 * Do the rq-clock update outside the rq lock:
4589 */
4590 local_irq_disable();
4591 update_rq_clock(rq);
4592 spin_lock(&rq->lock);
4593 clear_tsk_need_resched(prev);
4594
4595 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4596 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4597 signal_pending(prev))) {
4598 prev->state = TASK_RUNNING;
4599 } else {
4600 deactivate_task(rq, prev, 1);
4601 }
4602 switch_count = &prev->nvcsw;
4603 }
4604
4605 #ifdef CONFIG_SMP
4606 if (prev->sched_class->pre_schedule)
4607 prev->sched_class->pre_schedule(rq, prev);
4608 #endif
4609
4610 if (unlikely(!rq->nr_running))
4611 idle_balance(cpu, rq);
4612
4613 prev->sched_class->put_prev_task(rq, prev);
4614 next = pick_next_task(rq, prev);
4615
4616 if (likely(prev != next)) {
4617 sched_info_switch(prev, next);
4618
4619 rq->nr_switches++;
4620 rq->curr = next;
4621 ++*switch_count;
4622
4623 context_switch(rq, prev, next); /* unlocks the rq */
4624 /*
4625 * the context switch might have flipped the stack from under
4626 * us, hence refresh the local variables.
4627 */
4628 cpu = smp_processor_id();
4629 rq = cpu_rq(cpu);
4630 } else
4631 spin_unlock_irq(&rq->lock);
4632
4633 hrtick_set(rq);
4634
4635 if (unlikely(reacquire_kernel_lock(current) < 0))
4636 goto need_resched_nonpreemptible;
4637
4638 preempt_enable_no_resched();
4639 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4640 goto need_resched;
4641 }
4642 EXPORT_SYMBOL(schedule);
4643
4644 #ifdef CONFIG_PREEMPT
4645 /*
4646 * this is the entry point to schedule() from in-kernel preemption
4647 * off of preempt_enable. Kernel preemptions off return from interrupt
4648 * occur there and call schedule directly.
4649 */
4650 asmlinkage void __sched preempt_schedule(void)
4651 {
4652 struct thread_info *ti = current_thread_info();
4653
4654 /*
4655 * If there is a non-zero preempt_count or interrupts are disabled,
4656 * we do not want to preempt the current task. Just return..
4657 */
4658 if (likely(ti->preempt_count || irqs_disabled()))
4659 return;
4660
4661 do {
4662 add_preempt_count(PREEMPT_ACTIVE);
4663 schedule();
4664 sub_preempt_count(PREEMPT_ACTIVE);
4665
4666 /*
4667 * Check again in case we missed a preemption opportunity
4668 * between schedule and now.
4669 */
4670 barrier();
4671 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4672 }
4673 EXPORT_SYMBOL(preempt_schedule);
4674
4675 /*
4676 * this is the entry point to schedule() from kernel preemption
4677 * off of irq context.
4678 * Note, that this is called and return with irqs disabled. This will
4679 * protect us against recursive calling from irq.
4680 */
4681 asmlinkage void __sched preempt_schedule_irq(void)
4682 {
4683 struct thread_info *ti = current_thread_info();
4684
4685 /* Catch callers which need to be fixed */
4686 BUG_ON(ti->preempt_count || !irqs_disabled());
4687
4688 do {
4689 add_preempt_count(PREEMPT_ACTIVE);
4690 local_irq_enable();
4691 schedule();
4692 local_irq_disable();
4693 sub_preempt_count(PREEMPT_ACTIVE);
4694
4695 /*
4696 * Check again in case we missed a preemption opportunity
4697 * between schedule and now.
4698 */
4699 barrier();
4700 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4701 }
4702
4703 #endif /* CONFIG_PREEMPT */
4704
4705 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4706 void *key)
4707 {
4708 return try_to_wake_up(curr->private, mode, sync);
4709 }
4710 EXPORT_SYMBOL(default_wake_function);
4711
4712 /*
4713 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4714 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4715 * number) then we wake all the non-exclusive tasks and one exclusive task.
4716 *
4717 * There are circumstances in which we can try to wake a task which has already
4718 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4719 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4720 */
4721 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4722 int nr_exclusive, int sync, void *key)
4723 {
4724 wait_queue_t *curr, *next;
4725
4726 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4727 unsigned flags = curr->flags;
4728
4729 if (curr->func(curr, mode, sync, key) &&
4730 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4731 break;
4732 }
4733 }
4734
4735 /**
4736 * __wake_up - wake up threads blocked on a waitqueue.
4737 * @q: the waitqueue
4738 * @mode: which threads
4739 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4740 * @key: is directly passed to the wakeup function
4741 */
4742 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4743 int nr_exclusive, void *key)
4744 {
4745 unsigned long flags;
4746
4747 spin_lock_irqsave(&q->lock, flags);
4748 __wake_up_common(q, mode, nr_exclusive, 0, key);
4749 spin_unlock_irqrestore(&q->lock, flags);
4750 }
4751 EXPORT_SYMBOL(__wake_up);
4752
4753 /*
4754 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4755 */
4756 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4757 {
4758 __wake_up_common(q, mode, 1, 0, NULL);
4759 }
4760
4761 /**
4762 * __wake_up_sync - wake up threads blocked on a waitqueue.
4763 * @q: the waitqueue
4764 * @mode: which threads
4765 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4766 *
4767 * The sync wakeup differs that the waker knows that it will schedule
4768 * away soon, so while the target thread will be woken up, it will not
4769 * be migrated to another CPU - ie. the two threads are 'synchronized'
4770 * with each other. This can prevent needless bouncing between CPUs.
4771 *
4772 * On UP it can prevent extra preemption.
4773 */
4774 void
4775 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4776 {
4777 unsigned long flags;
4778 int sync = 1;
4779
4780 if (unlikely(!q))
4781 return;
4782
4783 if (unlikely(!nr_exclusive))
4784 sync = 0;
4785
4786 spin_lock_irqsave(&q->lock, flags);
4787 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4788 spin_unlock_irqrestore(&q->lock, flags);
4789 }
4790 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4791
4792 void complete(struct completion *x)
4793 {
4794 unsigned long flags;
4795
4796 spin_lock_irqsave(&x->wait.lock, flags);
4797 x->done++;
4798 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4799 spin_unlock_irqrestore(&x->wait.lock, flags);
4800 }
4801 EXPORT_SYMBOL(complete);
4802
4803 void complete_all(struct completion *x)
4804 {
4805 unsigned long flags;
4806
4807 spin_lock_irqsave(&x->wait.lock, flags);
4808 x->done += UINT_MAX/2;
4809 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4810 spin_unlock_irqrestore(&x->wait.lock, flags);
4811 }
4812 EXPORT_SYMBOL(complete_all);
4813
4814 static inline long __sched
4815 do_wait_for_common(struct completion *x, long timeout, int state)
4816 {
4817 if (!x->done) {
4818 DECLARE_WAITQUEUE(wait, current);
4819
4820 wait.flags |= WQ_FLAG_EXCLUSIVE;
4821 __add_wait_queue_tail(&x->wait, &wait);
4822 do {
4823 if ((state == TASK_INTERRUPTIBLE &&
4824 signal_pending(current)) ||
4825 (state == TASK_KILLABLE &&
4826 fatal_signal_pending(current))) {
4827 __remove_wait_queue(&x->wait, &wait);
4828 return -ERESTARTSYS;
4829 }
4830 __set_current_state(state);
4831 spin_unlock_irq(&x->wait.lock);
4832 timeout = schedule_timeout(timeout);
4833 spin_lock_irq(&x->wait.lock);
4834 if (!timeout) {
4835 __remove_wait_queue(&x->wait, &wait);
4836 return timeout;
4837 }
4838 } while (!x->done);
4839 __remove_wait_queue(&x->wait, &wait);
4840 }
4841 x->done--;
4842 return timeout;
4843 }
4844
4845 static long __sched
4846 wait_for_common(struct completion *x, long timeout, int state)
4847 {
4848 might_sleep();
4849
4850 spin_lock_irq(&x->wait.lock);
4851 timeout = do_wait_for_common(x, timeout, state);
4852 spin_unlock_irq(&x->wait.lock);
4853 return timeout;
4854 }
4855
4856 void __sched wait_for_completion(struct completion *x)
4857 {
4858 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4859 }
4860 EXPORT_SYMBOL(wait_for_completion);
4861
4862 unsigned long __sched
4863 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4864 {
4865 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4866 }
4867 EXPORT_SYMBOL(wait_for_completion_timeout);
4868
4869 int __sched wait_for_completion_interruptible(struct completion *x)
4870 {
4871 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4872 if (t == -ERESTARTSYS)
4873 return t;
4874 return 0;
4875 }
4876 EXPORT_SYMBOL(wait_for_completion_interruptible);
4877
4878 unsigned long __sched
4879 wait_for_completion_interruptible_timeout(struct completion *x,
4880 unsigned long timeout)
4881 {
4882 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4883 }
4884 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4885
4886 int __sched wait_for_completion_killable(struct completion *x)
4887 {
4888 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4889 if (t == -ERESTARTSYS)
4890 return t;
4891 return 0;
4892 }
4893 EXPORT_SYMBOL(wait_for_completion_killable);
4894
4895 static long __sched
4896 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4897 {
4898 unsigned long flags;
4899 wait_queue_t wait;
4900
4901 init_waitqueue_entry(&wait, current);
4902
4903 __set_current_state(state);
4904
4905 spin_lock_irqsave(&q->lock, flags);
4906 __add_wait_queue(q, &wait);
4907 spin_unlock(&q->lock);
4908 timeout = schedule_timeout(timeout);
4909 spin_lock_irq(&q->lock);
4910 __remove_wait_queue(q, &wait);
4911 spin_unlock_irqrestore(&q->lock, flags);
4912
4913 return timeout;
4914 }
4915
4916 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4917 {
4918 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4919 }
4920 EXPORT_SYMBOL(interruptible_sleep_on);
4921
4922 long __sched
4923 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4924 {
4925 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4926 }
4927 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4928
4929 void __sched sleep_on(wait_queue_head_t *q)
4930 {
4931 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4932 }
4933 EXPORT_SYMBOL(sleep_on);
4934
4935 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4936 {
4937 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4938 }
4939 EXPORT_SYMBOL(sleep_on_timeout);
4940
4941 #ifdef CONFIG_RT_MUTEXES
4942
4943 /*
4944 * rt_mutex_setprio - set the current priority of a task
4945 * @p: task
4946 * @prio: prio value (kernel-internal form)
4947 *
4948 * This function changes the 'effective' priority of a task. It does
4949 * not touch ->normal_prio like __setscheduler().
4950 *
4951 * Used by the rt_mutex code to implement priority inheritance logic.
4952 */
4953 void rt_mutex_setprio(struct task_struct *p, int prio)
4954 {
4955 unsigned long flags;
4956 int oldprio, on_rq, running;
4957 struct rq *rq;
4958 const struct sched_class *prev_class = p->sched_class;
4959
4960 BUG_ON(prio < 0 || prio > MAX_PRIO);
4961
4962 rq = task_rq_lock(p, &flags);
4963 update_rq_clock(rq);
4964
4965 oldprio = p->prio;
4966 on_rq = p->se.on_rq;
4967 running = task_current(rq, p);
4968 if (on_rq)
4969 dequeue_task(rq, p, 0);
4970 if (running)
4971 p->sched_class->put_prev_task(rq, p);
4972
4973 if (rt_prio(prio))
4974 p->sched_class = &rt_sched_class;
4975 else
4976 p->sched_class = &fair_sched_class;
4977
4978 p->prio = prio;
4979
4980 if (running)
4981 p->sched_class->set_curr_task(rq);
4982 if (on_rq) {
4983 enqueue_task(rq, p, 0);
4984
4985 check_class_changed(rq, p, prev_class, oldprio, running);
4986 }
4987 task_rq_unlock(rq, &flags);
4988 }
4989
4990 #endif
4991
4992 void set_user_nice(struct task_struct *p, long nice)
4993 {
4994 int old_prio, delta, on_rq;
4995 unsigned long flags;
4996 struct rq *rq;
4997
4998 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4999 return;
5000 /*
5001 * We have to be careful, if called from sys_setpriority(),
5002 * the task might be in the middle of scheduling on another CPU.
5003 */
5004 rq = task_rq_lock(p, &flags);
5005 update_rq_clock(rq);
5006 /*
5007 * The RT priorities are set via sched_setscheduler(), but we still
5008 * allow the 'normal' nice value to be set - but as expected
5009 * it wont have any effect on scheduling until the task is
5010 * SCHED_FIFO/SCHED_RR:
5011 */
5012 if (task_has_rt_policy(p)) {
5013 p->static_prio = NICE_TO_PRIO(nice);
5014 goto out_unlock;
5015 }
5016 on_rq = p->se.on_rq;
5017 if (on_rq)
5018 dequeue_task(rq, p, 0);
5019
5020 p->static_prio = NICE_TO_PRIO(nice);
5021 set_load_weight(p);
5022 old_prio = p->prio;
5023 p->prio = effective_prio(p);
5024 delta = p->prio - old_prio;
5025
5026 if (on_rq) {
5027 enqueue_task(rq, p, 0);
5028 /*
5029 * If the task increased its priority or is running and
5030 * lowered its priority, then reschedule its CPU:
5031 */
5032 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5033 resched_task(rq->curr);
5034 }
5035 out_unlock:
5036 task_rq_unlock(rq, &flags);
5037 }
5038 EXPORT_SYMBOL(set_user_nice);
5039
5040 /*
5041 * can_nice - check if a task can reduce its nice value
5042 * @p: task
5043 * @nice: nice value
5044 */
5045 int can_nice(const struct task_struct *p, const int nice)
5046 {
5047 /* convert nice value [19,-20] to rlimit style value [1,40] */
5048 int nice_rlim = 20 - nice;
5049
5050 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5051 capable(CAP_SYS_NICE));
5052 }
5053
5054 #ifdef __ARCH_WANT_SYS_NICE
5055
5056 /*
5057 * sys_nice - change the priority of the current process.
5058 * @increment: priority increment
5059 *
5060 * sys_setpriority is a more generic, but much slower function that
5061 * does similar things.
5062 */
5063 asmlinkage long sys_nice(int increment)
5064 {
5065 long nice, retval;
5066
5067 /*
5068 * Setpriority might change our priority at the same moment.
5069 * We don't have to worry. Conceptually one call occurs first
5070 * and we have a single winner.
5071 */
5072 if (increment < -40)
5073 increment = -40;
5074 if (increment > 40)
5075 increment = 40;
5076
5077 nice = PRIO_TO_NICE(current->static_prio) + increment;
5078 if (nice < -20)
5079 nice = -20;
5080 if (nice > 19)
5081 nice = 19;
5082
5083 if (increment < 0 && !can_nice(current, nice))
5084 return -EPERM;
5085
5086 retval = security_task_setnice(current, nice);
5087 if (retval)
5088 return retval;
5089
5090 set_user_nice(current, nice);
5091 return 0;
5092 }
5093
5094 #endif
5095
5096 /**
5097 * task_prio - return the priority value of a given task.
5098 * @p: the task in question.
5099 *
5100 * This is the priority value as seen by users in /proc.
5101 * RT tasks are offset by -200. Normal tasks are centered
5102 * around 0, value goes from -16 to +15.
5103 */
5104 int task_prio(const struct task_struct *p)
5105 {
5106 return p->prio - MAX_RT_PRIO;
5107 }
5108
5109 /**
5110 * task_nice - return the nice value of a given task.
5111 * @p: the task in question.
5112 */
5113 int task_nice(const struct task_struct *p)
5114 {
5115 return TASK_NICE(p);
5116 }
5117 EXPORT_SYMBOL(task_nice);
5118
5119 /**
5120 * idle_cpu - is a given cpu idle currently?
5121 * @cpu: the processor in question.
5122 */
5123 int idle_cpu(int cpu)
5124 {
5125 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5126 }
5127
5128 /**
5129 * idle_task - return the idle task for a given cpu.
5130 * @cpu: the processor in question.
5131 */
5132 struct task_struct *idle_task(int cpu)
5133 {
5134 return cpu_rq(cpu)->idle;
5135 }
5136
5137 /**
5138 * find_process_by_pid - find a process with a matching PID value.
5139 * @pid: the pid in question.
5140 */
5141 static struct task_struct *find_process_by_pid(pid_t pid)
5142 {
5143 return pid ? find_task_by_vpid(pid) : current;
5144 }
5145
5146 /* Actually do priority change: must hold rq lock. */
5147 static void
5148 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5149 {
5150 BUG_ON(p->se.on_rq);
5151
5152 p->policy = policy;
5153 switch (p->policy) {
5154 case SCHED_NORMAL:
5155 case SCHED_BATCH:
5156 case SCHED_IDLE:
5157 p->sched_class = &fair_sched_class;
5158 break;
5159 case SCHED_FIFO:
5160 case SCHED_RR:
5161 p->sched_class = &rt_sched_class;
5162 break;
5163 }
5164
5165 p->rt_priority = prio;
5166 p->normal_prio = normal_prio(p);
5167 /* we are holding p->pi_lock already */
5168 p->prio = rt_mutex_getprio(p);
5169 set_load_weight(p);
5170 }
5171
5172 /**
5173 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5174 * @p: the task in question.
5175 * @policy: new policy.
5176 * @param: structure containing the new RT priority.
5177 *
5178 * NOTE that the task may be already dead.
5179 */
5180 int sched_setscheduler(struct task_struct *p, int policy,
5181 struct sched_param *param)
5182 {
5183 int retval, oldprio, oldpolicy = -1, on_rq, running;
5184 unsigned long flags;
5185 const struct sched_class *prev_class = p->sched_class;
5186 struct rq *rq;
5187
5188 /* may grab non-irq protected spin_locks */
5189 BUG_ON(in_interrupt());
5190 recheck:
5191 /* double check policy once rq lock held */
5192 if (policy < 0)
5193 policy = oldpolicy = p->policy;
5194 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5195 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5196 policy != SCHED_IDLE)
5197 return -EINVAL;
5198 /*
5199 * Valid priorities for SCHED_FIFO and SCHED_RR are
5200 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5201 * SCHED_BATCH and SCHED_IDLE is 0.
5202 */
5203 if (param->sched_priority < 0 ||
5204 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5205 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5206 return -EINVAL;
5207 if (rt_policy(policy) != (param->sched_priority != 0))
5208 return -EINVAL;
5209
5210 /*
5211 * Allow unprivileged RT tasks to decrease priority:
5212 */
5213 if (!capable(CAP_SYS_NICE)) {
5214 if (rt_policy(policy)) {
5215 unsigned long rlim_rtprio;
5216
5217 if (!lock_task_sighand(p, &flags))
5218 return -ESRCH;
5219 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5220 unlock_task_sighand(p, &flags);
5221
5222 /* can't set/change the rt policy */
5223 if (policy != p->policy && !rlim_rtprio)
5224 return -EPERM;
5225
5226 /* can't increase priority */
5227 if (param->sched_priority > p->rt_priority &&
5228 param->sched_priority > rlim_rtprio)
5229 return -EPERM;
5230 }
5231 /*
5232 * Like positive nice levels, dont allow tasks to
5233 * move out of SCHED_IDLE either:
5234 */
5235 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5236 return -EPERM;
5237
5238 /* can't change other user's priorities */
5239 if ((current->euid != p->euid) &&
5240 (current->euid != p->uid))
5241 return -EPERM;
5242 }
5243
5244 #ifdef CONFIG_RT_GROUP_SCHED
5245 /*
5246 * Do not allow realtime tasks into groups that have no runtime
5247 * assigned.
5248 */
5249 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5250 return -EPERM;
5251 #endif
5252
5253 retval = security_task_setscheduler(p, policy, param);
5254 if (retval)
5255 return retval;
5256 /*
5257 * make sure no PI-waiters arrive (or leave) while we are
5258 * changing the priority of the task:
5259 */
5260 spin_lock_irqsave(&p->pi_lock, flags);
5261 /*
5262 * To be able to change p->policy safely, the apropriate
5263 * runqueue lock must be held.
5264 */
5265 rq = __task_rq_lock(p);
5266 /* recheck policy now with rq lock held */
5267 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5268 policy = oldpolicy = -1;
5269 __task_rq_unlock(rq);
5270 spin_unlock_irqrestore(&p->pi_lock, flags);
5271 goto recheck;
5272 }
5273 update_rq_clock(rq);
5274 on_rq = p->se.on_rq;
5275 running = task_current(rq, p);
5276 if (on_rq)
5277 deactivate_task(rq, p, 0);
5278 if (running)
5279 p->sched_class->put_prev_task(rq, p);
5280
5281 oldprio = p->prio;
5282 __setscheduler(rq, p, policy, param->sched_priority);
5283
5284 if (running)
5285 p->sched_class->set_curr_task(rq);
5286 if (on_rq) {
5287 activate_task(rq, p, 0);
5288
5289 check_class_changed(rq, p, prev_class, oldprio, running);
5290 }
5291 __task_rq_unlock(rq);
5292 spin_unlock_irqrestore(&p->pi_lock, flags);
5293
5294 rt_mutex_adjust_pi(p);
5295
5296 return 0;
5297 }
5298 EXPORT_SYMBOL_GPL(sched_setscheduler);
5299
5300 static int
5301 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5302 {
5303 struct sched_param lparam;
5304 struct task_struct *p;
5305 int retval;
5306
5307 if (!param || pid < 0)
5308 return -EINVAL;
5309 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5310 return -EFAULT;
5311
5312 rcu_read_lock();
5313 retval = -ESRCH;
5314 p = find_process_by_pid(pid);
5315 if (p != NULL)
5316 retval = sched_setscheduler(p, policy, &lparam);
5317 rcu_read_unlock();
5318
5319 return retval;
5320 }
5321
5322 /**
5323 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5324 * @pid: the pid in question.
5325 * @policy: new policy.
5326 * @param: structure containing the new RT priority.
5327 */
5328 asmlinkage long
5329 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5330 {
5331 /* negative values for policy are not valid */
5332 if (policy < 0)
5333 return -EINVAL;
5334
5335 return do_sched_setscheduler(pid, policy, param);
5336 }
5337
5338 /**
5339 * sys_sched_setparam - set/change the RT priority of a thread
5340 * @pid: the pid in question.
5341 * @param: structure containing the new RT priority.
5342 */
5343 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5344 {
5345 return do_sched_setscheduler(pid, -1, param);
5346 }
5347
5348 /**
5349 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5350 * @pid: the pid in question.
5351 */
5352 asmlinkage long sys_sched_getscheduler(pid_t pid)
5353 {
5354 struct task_struct *p;
5355 int retval;
5356
5357 if (pid < 0)
5358 return -EINVAL;
5359
5360 retval = -ESRCH;
5361 read_lock(&tasklist_lock);
5362 p = find_process_by_pid(pid);
5363 if (p) {
5364 retval = security_task_getscheduler(p);
5365 if (!retval)
5366 retval = p->policy;
5367 }
5368 read_unlock(&tasklist_lock);
5369 return retval;
5370 }
5371
5372 /**
5373 * sys_sched_getscheduler - get the RT priority of a thread
5374 * @pid: the pid in question.
5375 * @param: structure containing the RT priority.
5376 */
5377 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5378 {
5379 struct sched_param lp;
5380 struct task_struct *p;
5381 int retval;
5382
5383 if (!param || pid < 0)
5384 return -EINVAL;
5385
5386 read_lock(&tasklist_lock);
5387 p = find_process_by_pid(pid);
5388 retval = -ESRCH;
5389 if (!p)
5390 goto out_unlock;
5391
5392 retval = security_task_getscheduler(p);
5393 if (retval)
5394 goto out_unlock;
5395
5396 lp.sched_priority = p->rt_priority;
5397 read_unlock(&tasklist_lock);
5398
5399 /*
5400 * This one might sleep, we cannot do it with a spinlock held ...
5401 */
5402 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5403
5404 return retval;
5405
5406 out_unlock:
5407 read_unlock(&tasklist_lock);
5408 return retval;
5409 }
5410
5411 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5412 {
5413 cpumask_t cpus_allowed;
5414 cpumask_t new_mask = *in_mask;
5415 struct task_struct *p;
5416 int retval;
5417
5418 get_online_cpus();
5419 read_lock(&tasklist_lock);
5420
5421 p = find_process_by_pid(pid);
5422 if (!p) {
5423 read_unlock(&tasklist_lock);
5424 put_online_cpus();
5425 return -ESRCH;
5426 }
5427
5428 /*
5429 * It is not safe to call set_cpus_allowed with the
5430 * tasklist_lock held. We will bump the task_struct's
5431 * usage count and then drop tasklist_lock.
5432 */
5433 get_task_struct(p);
5434 read_unlock(&tasklist_lock);
5435
5436 retval = -EPERM;
5437 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5438 !capable(CAP_SYS_NICE))
5439 goto out_unlock;
5440
5441 retval = security_task_setscheduler(p, 0, NULL);
5442 if (retval)
5443 goto out_unlock;
5444
5445 cpuset_cpus_allowed(p, &cpus_allowed);
5446 cpus_and(new_mask, new_mask, cpus_allowed);
5447 again:
5448 retval = set_cpus_allowed_ptr(p, &new_mask);
5449
5450 if (!retval) {
5451 cpuset_cpus_allowed(p, &cpus_allowed);
5452 if (!cpus_subset(new_mask, cpus_allowed)) {
5453 /*
5454 * We must have raced with a concurrent cpuset
5455 * update. Just reset the cpus_allowed to the
5456 * cpuset's cpus_allowed
5457 */
5458 new_mask = cpus_allowed;
5459 goto again;
5460 }
5461 }
5462 out_unlock:
5463 put_task_struct(p);
5464 put_online_cpus();
5465 return retval;
5466 }
5467
5468 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5469 cpumask_t *new_mask)
5470 {
5471 if (len < sizeof(cpumask_t)) {
5472 memset(new_mask, 0, sizeof(cpumask_t));
5473 } else if (len > sizeof(cpumask_t)) {
5474 len = sizeof(cpumask_t);
5475 }
5476 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5477 }
5478
5479 /**
5480 * sys_sched_setaffinity - set the cpu affinity of a process
5481 * @pid: pid of the process
5482 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5483 * @user_mask_ptr: user-space pointer to the new cpu mask
5484 */
5485 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5486 unsigned long __user *user_mask_ptr)
5487 {
5488 cpumask_t new_mask;
5489 int retval;
5490
5491 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5492 if (retval)
5493 return retval;
5494
5495 return sched_setaffinity(pid, &new_mask);
5496 }
5497
5498 /*
5499 * Represents all cpu's present in the system
5500 * In systems capable of hotplug, this map could dynamically grow
5501 * as new cpu's are detected in the system via any platform specific
5502 * method, such as ACPI for e.g.
5503 */
5504
5505 cpumask_t cpu_present_map __read_mostly;
5506 EXPORT_SYMBOL(cpu_present_map);
5507
5508 #ifndef CONFIG_SMP
5509 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5510 EXPORT_SYMBOL(cpu_online_map);
5511
5512 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5513 EXPORT_SYMBOL(cpu_possible_map);
5514 #endif
5515
5516 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5517 {
5518 struct task_struct *p;
5519 int retval;
5520
5521 get_online_cpus();
5522 read_lock(&tasklist_lock);
5523
5524 retval = -ESRCH;
5525 p = find_process_by_pid(pid);
5526 if (!p)
5527 goto out_unlock;
5528
5529 retval = security_task_getscheduler(p);
5530 if (retval)
5531 goto out_unlock;
5532
5533 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5534
5535 out_unlock:
5536 read_unlock(&tasklist_lock);
5537 put_online_cpus();
5538
5539 return retval;
5540 }
5541
5542 /**
5543 * sys_sched_getaffinity - get the cpu affinity of a process
5544 * @pid: pid of the process
5545 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5546 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5547 */
5548 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5549 unsigned long __user *user_mask_ptr)
5550 {
5551 int ret;
5552 cpumask_t mask;
5553
5554 if (len < sizeof(cpumask_t))
5555 return -EINVAL;
5556
5557 ret = sched_getaffinity(pid, &mask);
5558 if (ret < 0)
5559 return ret;
5560
5561 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5562 return -EFAULT;
5563
5564 return sizeof(cpumask_t);
5565 }
5566
5567 /**
5568 * sys_sched_yield - yield the current processor to other threads.
5569 *
5570 * This function yields the current CPU to other tasks. If there are no
5571 * other threads running on this CPU then this function will return.
5572 */
5573 asmlinkage long sys_sched_yield(void)
5574 {
5575 struct rq *rq = this_rq_lock();
5576
5577 schedstat_inc(rq, yld_count);
5578 current->sched_class->yield_task(rq);
5579
5580 /*
5581 * Since we are going to call schedule() anyway, there's
5582 * no need to preempt or enable interrupts:
5583 */
5584 __release(rq->lock);
5585 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5586 _raw_spin_unlock(&rq->lock);
5587 preempt_enable_no_resched();
5588
5589 schedule();
5590
5591 return 0;
5592 }
5593
5594 static void __cond_resched(void)
5595 {
5596 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5597 __might_sleep(__FILE__, __LINE__);
5598 #endif
5599 /*
5600 * The BKS might be reacquired before we have dropped
5601 * PREEMPT_ACTIVE, which could trigger a second
5602 * cond_resched() call.
5603 */
5604 do {
5605 add_preempt_count(PREEMPT_ACTIVE);
5606 schedule();
5607 sub_preempt_count(PREEMPT_ACTIVE);
5608 } while (need_resched());
5609 }
5610
5611 int __sched _cond_resched(void)
5612 {
5613 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5614 system_state == SYSTEM_RUNNING) {
5615 __cond_resched();
5616 return 1;
5617 }
5618 return 0;
5619 }
5620 EXPORT_SYMBOL(_cond_resched);
5621
5622 /*
5623 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5624 * call schedule, and on return reacquire the lock.
5625 *
5626 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5627 * operations here to prevent schedule() from being called twice (once via
5628 * spin_unlock(), once by hand).
5629 */
5630 int cond_resched_lock(spinlock_t *lock)
5631 {
5632 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5633 int ret = 0;
5634
5635 if (spin_needbreak(lock) || resched) {
5636 spin_unlock(lock);
5637 if (resched && need_resched())
5638 __cond_resched();
5639 else
5640 cpu_relax();
5641 ret = 1;
5642 spin_lock(lock);
5643 }
5644 return ret;
5645 }
5646 EXPORT_SYMBOL(cond_resched_lock);
5647
5648 int __sched cond_resched_softirq(void)
5649 {
5650 BUG_ON(!in_softirq());
5651
5652 if (need_resched() && system_state == SYSTEM_RUNNING) {
5653 local_bh_enable();
5654 __cond_resched();
5655 local_bh_disable();
5656 return 1;
5657 }
5658 return 0;
5659 }
5660 EXPORT_SYMBOL(cond_resched_softirq);
5661
5662 /**
5663 * yield - yield the current processor to other threads.
5664 *
5665 * This is a shortcut for kernel-space yielding - it marks the
5666 * thread runnable and calls sys_sched_yield().
5667 */
5668 void __sched yield(void)
5669 {
5670 set_current_state(TASK_RUNNING);
5671 sys_sched_yield();
5672 }
5673 EXPORT_SYMBOL(yield);
5674
5675 /*
5676 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5677 * that process accounting knows that this is a task in IO wait state.
5678 *
5679 * But don't do that if it is a deliberate, throttling IO wait (this task
5680 * has set its backing_dev_info: the queue against which it should throttle)
5681 */
5682 void __sched io_schedule(void)
5683 {
5684 struct rq *rq = &__raw_get_cpu_var(runqueues);
5685
5686 delayacct_blkio_start();
5687 atomic_inc(&rq->nr_iowait);
5688 schedule();
5689 atomic_dec(&rq->nr_iowait);
5690 delayacct_blkio_end();
5691 }
5692 EXPORT_SYMBOL(io_schedule);
5693
5694 long __sched io_schedule_timeout(long timeout)
5695 {
5696 struct rq *rq = &__raw_get_cpu_var(runqueues);
5697 long ret;
5698
5699 delayacct_blkio_start();
5700 atomic_inc(&rq->nr_iowait);
5701 ret = schedule_timeout(timeout);
5702 atomic_dec(&rq->nr_iowait);
5703 delayacct_blkio_end();
5704 return ret;
5705 }
5706
5707 /**
5708 * sys_sched_get_priority_max - return maximum RT priority.
5709 * @policy: scheduling class.
5710 *
5711 * this syscall returns the maximum rt_priority that can be used
5712 * by a given scheduling class.
5713 */
5714 asmlinkage long sys_sched_get_priority_max(int policy)
5715 {
5716 int ret = -EINVAL;
5717
5718 switch (policy) {
5719 case SCHED_FIFO:
5720 case SCHED_RR:
5721 ret = MAX_USER_RT_PRIO-1;
5722 break;
5723 case SCHED_NORMAL:
5724 case SCHED_BATCH:
5725 case SCHED_IDLE:
5726 ret = 0;
5727 break;
5728 }
5729 return ret;
5730 }
5731
5732 /**
5733 * sys_sched_get_priority_min - return minimum RT priority.
5734 * @policy: scheduling class.
5735 *
5736 * this syscall returns the minimum rt_priority that can be used
5737 * by a given scheduling class.
5738 */
5739 asmlinkage long sys_sched_get_priority_min(int policy)
5740 {
5741 int ret = -EINVAL;
5742
5743 switch (policy) {
5744 case SCHED_FIFO:
5745 case SCHED_RR:
5746 ret = 1;
5747 break;
5748 case SCHED_NORMAL:
5749 case SCHED_BATCH:
5750 case SCHED_IDLE:
5751 ret = 0;
5752 }
5753 return ret;
5754 }
5755
5756 /**
5757 * sys_sched_rr_get_interval - return the default timeslice of a process.
5758 * @pid: pid of the process.
5759 * @interval: userspace pointer to the timeslice value.
5760 *
5761 * this syscall writes the default timeslice value of a given process
5762 * into the user-space timespec buffer. A value of '0' means infinity.
5763 */
5764 asmlinkage
5765 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5766 {
5767 struct task_struct *p;
5768 unsigned int time_slice;
5769 int retval;
5770 struct timespec t;
5771
5772 if (pid < 0)
5773 return -EINVAL;
5774
5775 retval = -ESRCH;
5776 read_lock(&tasklist_lock);
5777 p = find_process_by_pid(pid);
5778 if (!p)
5779 goto out_unlock;
5780
5781 retval = security_task_getscheduler(p);
5782 if (retval)
5783 goto out_unlock;
5784
5785 /*
5786 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5787 * tasks that are on an otherwise idle runqueue:
5788 */
5789 time_slice = 0;
5790 if (p->policy == SCHED_RR) {
5791 time_slice = DEF_TIMESLICE;
5792 } else if (p->policy != SCHED_FIFO) {
5793 struct sched_entity *se = &p->se;
5794 unsigned long flags;
5795 struct rq *rq;
5796
5797 rq = task_rq_lock(p, &flags);
5798 if (rq->cfs.load.weight)
5799 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5800 task_rq_unlock(rq, &flags);
5801 }
5802 read_unlock(&tasklist_lock);
5803 jiffies_to_timespec(time_slice, &t);
5804 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5805 return retval;
5806
5807 out_unlock:
5808 read_unlock(&tasklist_lock);
5809 return retval;
5810 }
5811
5812 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5813
5814 void sched_show_task(struct task_struct *p)
5815 {
5816 unsigned long free = 0;
5817 unsigned state;
5818
5819 state = p->state ? __ffs(p->state) + 1 : 0;
5820 printk(KERN_INFO "%-13.13s %c", p->comm,
5821 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5822 #if BITS_PER_LONG == 32
5823 if (state == TASK_RUNNING)
5824 printk(KERN_CONT " running ");
5825 else
5826 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5827 #else
5828 if (state == TASK_RUNNING)
5829 printk(KERN_CONT " running task ");
5830 else
5831 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5832 #endif
5833 #ifdef CONFIG_DEBUG_STACK_USAGE
5834 {
5835 unsigned long *n = end_of_stack(p);
5836 while (!*n)
5837 n++;
5838 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5839 }
5840 #endif
5841 printk(KERN_CONT "%5lu %5d %6d\n", free,
5842 task_pid_nr(p), task_pid_nr(p->real_parent));
5843
5844 show_stack(p, NULL);
5845 }
5846
5847 void show_state_filter(unsigned long state_filter)
5848 {
5849 struct task_struct *g, *p;
5850
5851 #if BITS_PER_LONG == 32
5852 printk(KERN_INFO
5853 " task PC stack pid father\n");
5854 #else
5855 printk(KERN_INFO
5856 " task PC stack pid father\n");
5857 #endif
5858 read_lock(&tasklist_lock);
5859 do_each_thread(g, p) {
5860 /*
5861 * reset the NMI-timeout, listing all files on a slow
5862 * console might take alot of time:
5863 */
5864 touch_nmi_watchdog();
5865 if (!state_filter || (p->state & state_filter))
5866 sched_show_task(p);
5867 } while_each_thread(g, p);
5868
5869 touch_all_softlockup_watchdogs();
5870
5871 #ifdef CONFIG_SCHED_DEBUG
5872 sysrq_sched_debug_show();
5873 #endif
5874 read_unlock(&tasklist_lock);
5875 /*
5876 * Only show locks if all tasks are dumped:
5877 */
5878 if (state_filter == -1)
5879 debug_show_all_locks();
5880 }
5881
5882 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5883 {
5884 idle->sched_class = &idle_sched_class;
5885 }
5886
5887 /**
5888 * init_idle - set up an idle thread for a given CPU
5889 * @idle: task in question
5890 * @cpu: cpu the idle task belongs to
5891 *
5892 * NOTE: this function does not set the idle thread's NEED_RESCHED
5893 * flag, to make booting more robust.
5894 */
5895 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5896 {
5897 struct rq *rq = cpu_rq(cpu);
5898 unsigned long flags;
5899
5900 __sched_fork(idle);
5901 idle->se.exec_start = sched_clock();
5902
5903 idle->prio = idle->normal_prio = MAX_PRIO;
5904 idle->cpus_allowed = cpumask_of_cpu(cpu);
5905 __set_task_cpu(idle, cpu);
5906
5907 spin_lock_irqsave(&rq->lock, flags);
5908 rq->curr = rq->idle = idle;
5909 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5910 idle->oncpu = 1;
5911 #endif
5912 spin_unlock_irqrestore(&rq->lock, flags);
5913
5914 /* Set the preempt count _outside_ the spinlocks! */
5915 #if defined(CONFIG_PREEMPT)
5916 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5917 #else
5918 task_thread_info(idle)->preempt_count = 0;
5919 #endif
5920 /*
5921 * The idle tasks have their own, simple scheduling class:
5922 */
5923 idle->sched_class = &idle_sched_class;
5924 }
5925
5926 /*
5927 * In a system that switches off the HZ timer nohz_cpu_mask
5928 * indicates which cpus entered this state. This is used
5929 * in the rcu update to wait only for active cpus. For system
5930 * which do not switch off the HZ timer nohz_cpu_mask should
5931 * always be CPU_MASK_NONE.
5932 */
5933 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5934
5935 /*
5936 * Increase the granularity value when there are more CPUs,
5937 * because with more CPUs the 'effective latency' as visible
5938 * to users decreases. But the relationship is not linear,
5939 * so pick a second-best guess by going with the log2 of the
5940 * number of CPUs.
5941 *
5942 * This idea comes from the SD scheduler of Con Kolivas:
5943 */
5944 static inline void sched_init_granularity(void)
5945 {
5946 unsigned int factor = 1 + ilog2(num_online_cpus());
5947 const unsigned long limit = 200000000;
5948
5949 sysctl_sched_min_granularity *= factor;
5950 if (sysctl_sched_min_granularity > limit)
5951 sysctl_sched_min_granularity = limit;
5952
5953 sysctl_sched_latency *= factor;
5954 if (sysctl_sched_latency > limit)
5955 sysctl_sched_latency = limit;
5956
5957 sysctl_sched_wakeup_granularity *= factor;
5958 }
5959
5960 #ifdef CONFIG_SMP
5961 /*
5962 * This is how migration works:
5963 *
5964 * 1) we queue a struct migration_req structure in the source CPU's
5965 * runqueue and wake up that CPU's migration thread.
5966 * 2) we down() the locked semaphore => thread blocks.
5967 * 3) migration thread wakes up (implicitly it forces the migrated
5968 * thread off the CPU)
5969 * 4) it gets the migration request and checks whether the migrated
5970 * task is still in the wrong runqueue.
5971 * 5) if it's in the wrong runqueue then the migration thread removes
5972 * it and puts it into the right queue.
5973 * 6) migration thread up()s the semaphore.
5974 * 7) we wake up and the migration is done.
5975 */
5976
5977 /*
5978 * Change a given task's CPU affinity. Migrate the thread to a
5979 * proper CPU and schedule it away if the CPU it's executing on
5980 * is removed from the allowed bitmask.
5981 *
5982 * NOTE: the caller must have a valid reference to the task, the
5983 * task must not exit() & deallocate itself prematurely. The
5984 * call is not atomic; no spinlocks may be held.
5985 */
5986 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5987 {
5988 struct migration_req req;
5989 unsigned long flags;
5990 struct rq *rq;
5991 int ret = 0;
5992
5993 rq = task_rq_lock(p, &flags);
5994 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5995 ret = -EINVAL;
5996 goto out;
5997 }
5998
5999 if (p->sched_class->set_cpus_allowed)
6000 p->sched_class->set_cpus_allowed(p, new_mask);
6001 else {
6002 p->cpus_allowed = *new_mask;
6003 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
6004 }
6005
6006 /* Can the task run on the task's current CPU? If so, we're done */
6007 if (cpu_isset(task_cpu(p), *new_mask))
6008 goto out;
6009
6010 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
6011 /* Need help from migration thread: drop lock and wait. */
6012 task_rq_unlock(rq, &flags);
6013 wake_up_process(rq->migration_thread);
6014 wait_for_completion(&req.done);
6015 tlb_migrate_finish(p->mm);
6016 return 0;
6017 }
6018 out:
6019 task_rq_unlock(rq, &flags);
6020
6021 return ret;
6022 }
6023 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6024
6025 /*
6026 * Move (not current) task off this cpu, onto dest cpu. We're doing
6027 * this because either it can't run here any more (set_cpus_allowed()
6028 * away from this CPU, or CPU going down), or because we're
6029 * attempting to rebalance this task on exec (sched_exec).
6030 *
6031 * So we race with normal scheduler movements, but that's OK, as long
6032 * as the task is no longer on this CPU.
6033 *
6034 * Returns non-zero if task was successfully migrated.
6035 */
6036 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6037 {
6038 struct rq *rq_dest, *rq_src;
6039 int ret = 0, on_rq;
6040
6041 if (unlikely(cpu_is_offline(dest_cpu)))
6042 return ret;
6043
6044 rq_src = cpu_rq(src_cpu);
6045 rq_dest = cpu_rq(dest_cpu);
6046
6047 double_rq_lock(rq_src, rq_dest);
6048 /* Already moved. */
6049 if (task_cpu(p) != src_cpu)
6050 goto out;
6051 /* Affinity changed (again). */
6052 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6053 goto out;
6054
6055 on_rq = p->se.on_rq;
6056 if (on_rq)
6057 deactivate_task(rq_src, p, 0);
6058
6059 set_task_cpu(p, dest_cpu);
6060 if (on_rq) {
6061 activate_task(rq_dest, p, 0);
6062 check_preempt_curr(rq_dest, p);
6063 }
6064 ret = 1;
6065 out:
6066 double_rq_unlock(rq_src, rq_dest);
6067 return ret;
6068 }
6069
6070 /*
6071 * migration_thread - this is a highprio system thread that performs
6072 * thread migration by bumping thread off CPU then 'pushing' onto
6073 * another runqueue.
6074 */
6075 static int migration_thread(void *data)
6076 {
6077 int cpu = (long)data;
6078 struct rq *rq;
6079
6080 rq = cpu_rq(cpu);
6081 BUG_ON(rq->migration_thread != current);
6082
6083 set_current_state(TASK_INTERRUPTIBLE);
6084 while (!kthread_should_stop()) {
6085 struct migration_req *req;
6086 struct list_head *head;
6087
6088 spin_lock_irq(&rq->lock);
6089
6090 if (cpu_is_offline(cpu)) {
6091 spin_unlock_irq(&rq->lock);
6092 goto wait_to_die;
6093 }
6094
6095 if (rq->active_balance) {
6096 active_load_balance(rq, cpu);
6097 rq->active_balance = 0;
6098 }
6099
6100 head = &rq->migration_queue;
6101
6102 if (list_empty(head)) {
6103 spin_unlock_irq(&rq->lock);
6104 schedule();
6105 set_current_state(TASK_INTERRUPTIBLE);
6106 continue;
6107 }
6108 req = list_entry(head->next, struct migration_req, list);
6109 list_del_init(head->next);
6110
6111 spin_unlock(&rq->lock);
6112 __migrate_task(req->task, cpu, req->dest_cpu);
6113 local_irq_enable();
6114
6115 complete(&req->done);
6116 }
6117 __set_current_state(TASK_RUNNING);
6118 return 0;
6119
6120 wait_to_die:
6121 /* Wait for kthread_stop */
6122 set_current_state(TASK_INTERRUPTIBLE);
6123 while (!kthread_should_stop()) {
6124 schedule();
6125 set_current_state(TASK_INTERRUPTIBLE);
6126 }
6127 __set_current_state(TASK_RUNNING);
6128 return 0;
6129 }
6130
6131 #ifdef CONFIG_HOTPLUG_CPU
6132
6133 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6134 {
6135 int ret;
6136
6137 local_irq_disable();
6138 ret = __migrate_task(p, src_cpu, dest_cpu);
6139 local_irq_enable();
6140 return ret;
6141 }
6142
6143 /*
6144 * Figure out where task on dead CPU should go, use force if necessary.
6145 * NOTE: interrupts should be disabled by the caller
6146 */
6147 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6148 {
6149 unsigned long flags;
6150 cpumask_t mask;
6151 struct rq *rq;
6152 int dest_cpu;
6153
6154 do {
6155 /* On same node? */
6156 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6157 cpus_and(mask, mask, p->cpus_allowed);
6158 dest_cpu = any_online_cpu(mask);
6159
6160 /* On any allowed CPU? */
6161 if (dest_cpu >= nr_cpu_ids)
6162 dest_cpu = any_online_cpu(p->cpus_allowed);
6163
6164 /* No more Mr. Nice Guy. */
6165 if (dest_cpu >= nr_cpu_ids) {
6166 cpumask_t cpus_allowed;
6167
6168 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6169 /*
6170 * Try to stay on the same cpuset, where the
6171 * current cpuset may be a subset of all cpus.
6172 * The cpuset_cpus_allowed_locked() variant of
6173 * cpuset_cpus_allowed() will not block. It must be
6174 * called within calls to cpuset_lock/cpuset_unlock.
6175 */
6176 rq = task_rq_lock(p, &flags);
6177 p->cpus_allowed = cpus_allowed;
6178 dest_cpu = any_online_cpu(p->cpus_allowed);
6179 task_rq_unlock(rq, &flags);
6180
6181 /*
6182 * Don't tell them about moving exiting tasks or
6183 * kernel threads (both mm NULL), since they never
6184 * leave kernel.
6185 */
6186 if (p->mm && printk_ratelimit()) {
6187 printk(KERN_INFO "process %d (%s) no "
6188 "longer affine to cpu%d\n",
6189 task_pid_nr(p), p->comm, dead_cpu);
6190 }
6191 }
6192 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6193 }
6194
6195 /*
6196 * While a dead CPU has no uninterruptible tasks queued at this point,
6197 * it might still have a nonzero ->nr_uninterruptible counter, because
6198 * for performance reasons the counter is not stricly tracking tasks to
6199 * their home CPUs. So we just add the counter to another CPU's counter,
6200 * to keep the global sum constant after CPU-down:
6201 */
6202 static void migrate_nr_uninterruptible(struct rq *rq_src)
6203 {
6204 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6205 unsigned long flags;
6206
6207 local_irq_save(flags);
6208 double_rq_lock(rq_src, rq_dest);
6209 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6210 rq_src->nr_uninterruptible = 0;
6211 double_rq_unlock(rq_src, rq_dest);
6212 local_irq_restore(flags);
6213 }
6214
6215 /* Run through task list and migrate tasks from the dead cpu. */
6216 static void migrate_live_tasks(int src_cpu)
6217 {
6218 struct task_struct *p, *t;
6219
6220 read_lock(&tasklist_lock);
6221
6222 do_each_thread(t, p) {
6223 if (p == current)
6224 continue;
6225
6226 if (task_cpu(p) == src_cpu)
6227 move_task_off_dead_cpu(src_cpu, p);
6228 } while_each_thread(t, p);
6229
6230 read_unlock(&tasklist_lock);
6231 }
6232
6233 /*
6234 * Schedules idle task to be the next runnable task on current CPU.
6235 * It does so by boosting its priority to highest possible.
6236 * Used by CPU offline code.
6237 */
6238 void sched_idle_next(void)
6239 {
6240 int this_cpu = smp_processor_id();
6241 struct rq *rq = cpu_rq(this_cpu);
6242 struct task_struct *p = rq->idle;
6243 unsigned long flags;
6244
6245 /* cpu has to be offline */
6246 BUG_ON(cpu_online(this_cpu));
6247
6248 /*
6249 * Strictly not necessary since rest of the CPUs are stopped by now
6250 * and interrupts disabled on the current cpu.
6251 */
6252 spin_lock_irqsave(&rq->lock, flags);
6253
6254 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6255
6256 update_rq_clock(rq);
6257 activate_task(rq, p, 0);
6258
6259 spin_unlock_irqrestore(&rq->lock, flags);
6260 }
6261
6262 /*
6263 * Ensures that the idle task is using init_mm right before its cpu goes
6264 * offline.
6265 */
6266 void idle_task_exit(void)
6267 {
6268 struct mm_struct *mm = current->active_mm;
6269
6270 BUG_ON(cpu_online(smp_processor_id()));
6271
6272 if (mm != &init_mm)
6273 switch_mm(mm, &init_mm, current);
6274 mmdrop(mm);
6275 }
6276
6277 /* called under rq->lock with disabled interrupts */
6278 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6279 {
6280 struct rq *rq = cpu_rq(dead_cpu);
6281
6282 /* Must be exiting, otherwise would be on tasklist. */
6283 BUG_ON(!p->exit_state);
6284
6285 /* Cannot have done final schedule yet: would have vanished. */
6286 BUG_ON(p->state == TASK_DEAD);
6287
6288 get_task_struct(p);
6289
6290 /*
6291 * Drop lock around migration; if someone else moves it,
6292 * that's OK. No task can be added to this CPU, so iteration is
6293 * fine.
6294 */
6295 spin_unlock_irq(&rq->lock);
6296 move_task_off_dead_cpu(dead_cpu, p);
6297 spin_lock_irq(&rq->lock);
6298
6299 put_task_struct(p);
6300 }
6301
6302 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6303 static void migrate_dead_tasks(unsigned int dead_cpu)
6304 {
6305 struct rq *rq = cpu_rq(dead_cpu);
6306 struct task_struct *next;
6307
6308 for ( ; ; ) {
6309 if (!rq->nr_running)
6310 break;
6311 update_rq_clock(rq);
6312 next = pick_next_task(rq, rq->curr);
6313 if (!next)
6314 break;
6315 migrate_dead(dead_cpu, next);
6316
6317 }
6318 }
6319 #endif /* CONFIG_HOTPLUG_CPU */
6320
6321 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6322
6323 static struct ctl_table sd_ctl_dir[] = {
6324 {
6325 .procname = "sched_domain",
6326 .mode = 0555,
6327 },
6328 {0, },
6329 };
6330
6331 static struct ctl_table sd_ctl_root[] = {
6332 {
6333 .ctl_name = CTL_KERN,
6334 .procname = "kernel",
6335 .mode = 0555,
6336 .child = sd_ctl_dir,
6337 },
6338 {0, },
6339 };
6340
6341 static struct ctl_table *sd_alloc_ctl_entry(int n)
6342 {
6343 struct ctl_table *entry =
6344 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6345
6346 return entry;
6347 }
6348
6349 static void sd_free_ctl_entry(struct ctl_table **tablep)
6350 {
6351 struct ctl_table *entry;
6352
6353 /*
6354 * In the intermediate directories, both the child directory and
6355 * procname are dynamically allocated and could fail but the mode
6356 * will always be set. In the lowest directory the names are
6357 * static strings and all have proc handlers.
6358 */
6359 for (entry = *tablep; entry->mode; entry++) {
6360 if (entry->child)
6361 sd_free_ctl_entry(&entry->child);
6362 if (entry->proc_handler == NULL)
6363 kfree(entry->procname);
6364 }
6365
6366 kfree(*tablep);
6367 *tablep = NULL;
6368 }
6369
6370 static void
6371 set_table_entry(struct ctl_table *entry,
6372 const char *procname, void *data, int maxlen,
6373 mode_t mode, proc_handler *proc_handler)
6374 {
6375 entry->procname = procname;
6376 entry->data = data;
6377 entry->maxlen = maxlen;
6378 entry->mode = mode;
6379 entry->proc_handler = proc_handler;
6380 }
6381
6382 static struct ctl_table *
6383 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6384 {
6385 struct ctl_table *table = sd_alloc_ctl_entry(12);
6386
6387 if (table == NULL)
6388 return NULL;
6389
6390 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6391 sizeof(long), 0644, proc_doulongvec_minmax);
6392 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6393 sizeof(long), 0644, proc_doulongvec_minmax);
6394 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6395 sizeof(int), 0644, proc_dointvec_minmax);
6396 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6397 sizeof(int), 0644, proc_dointvec_minmax);
6398 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6399 sizeof(int), 0644, proc_dointvec_minmax);
6400 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6401 sizeof(int), 0644, proc_dointvec_minmax);
6402 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6403 sizeof(int), 0644, proc_dointvec_minmax);
6404 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6405 sizeof(int), 0644, proc_dointvec_minmax);
6406 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6407 sizeof(int), 0644, proc_dointvec_minmax);
6408 set_table_entry(&table[9], "cache_nice_tries",
6409 &sd->cache_nice_tries,
6410 sizeof(int), 0644, proc_dointvec_minmax);
6411 set_table_entry(&table[10], "flags", &sd->flags,
6412 sizeof(int), 0644, proc_dointvec_minmax);
6413 /* &table[11] is terminator */
6414
6415 return table;
6416 }
6417
6418 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6419 {
6420 struct ctl_table *entry, *table;
6421 struct sched_domain *sd;
6422 int domain_num = 0, i;
6423 char buf[32];
6424
6425 for_each_domain(cpu, sd)
6426 domain_num++;
6427 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6428 if (table == NULL)
6429 return NULL;
6430
6431 i = 0;
6432 for_each_domain(cpu, sd) {
6433 snprintf(buf, 32, "domain%d", i);
6434 entry->procname = kstrdup(buf, GFP_KERNEL);
6435 entry->mode = 0555;
6436 entry->child = sd_alloc_ctl_domain_table(sd);
6437 entry++;
6438 i++;
6439 }
6440 return table;
6441 }
6442
6443 static struct ctl_table_header *sd_sysctl_header;
6444 static void register_sched_domain_sysctl(void)
6445 {
6446 int i, cpu_num = num_online_cpus();
6447 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6448 char buf[32];
6449
6450 WARN_ON(sd_ctl_dir[0].child);
6451 sd_ctl_dir[0].child = entry;
6452
6453 if (entry == NULL)
6454 return;
6455
6456 for_each_online_cpu(i) {
6457 snprintf(buf, 32, "cpu%d", i);
6458 entry->procname = kstrdup(buf, GFP_KERNEL);
6459 entry->mode = 0555;
6460 entry->child = sd_alloc_ctl_cpu_table(i);
6461 entry++;
6462 }
6463
6464 WARN_ON(sd_sysctl_header);
6465 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6466 }
6467
6468 /* may be called multiple times per register */
6469 static void unregister_sched_domain_sysctl(void)
6470 {
6471 if (sd_sysctl_header)
6472 unregister_sysctl_table(sd_sysctl_header);
6473 sd_sysctl_header = NULL;
6474 if (sd_ctl_dir[0].child)
6475 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6476 }
6477 #else
6478 static void register_sched_domain_sysctl(void)
6479 {
6480 }
6481 static void unregister_sched_domain_sysctl(void)
6482 {
6483 }
6484 #endif
6485
6486 /*
6487 * migration_call - callback that gets triggered when a CPU is added.
6488 * Here we can start up the necessary migration thread for the new CPU.
6489 */
6490 static int __cpuinit
6491 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6492 {
6493 struct task_struct *p;
6494 int cpu = (long)hcpu;
6495 unsigned long flags;
6496 struct rq *rq;
6497
6498 switch (action) {
6499
6500 case CPU_UP_PREPARE:
6501 case CPU_UP_PREPARE_FROZEN:
6502 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6503 if (IS_ERR(p))
6504 return NOTIFY_BAD;
6505 kthread_bind(p, cpu);
6506 /* Must be high prio: stop_machine expects to yield to it. */
6507 rq = task_rq_lock(p, &flags);
6508 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6509 task_rq_unlock(rq, &flags);
6510 cpu_rq(cpu)->migration_thread = p;
6511 break;
6512
6513 case CPU_ONLINE:
6514 case CPU_ONLINE_FROZEN:
6515 /* Strictly unnecessary, as first user will wake it. */
6516 wake_up_process(cpu_rq(cpu)->migration_thread);
6517
6518 /* Update our root-domain */
6519 rq = cpu_rq(cpu);
6520 spin_lock_irqsave(&rq->lock, flags);
6521 if (rq->rd) {
6522 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6523 cpu_set(cpu, rq->rd->online);
6524 }
6525 spin_unlock_irqrestore(&rq->lock, flags);
6526 break;
6527
6528 #ifdef CONFIG_HOTPLUG_CPU
6529 case CPU_UP_CANCELED:
6530 case CPU_UP_CANCELED_FROZEN:
6531 if (!cpu_rq(cpu)->migration_thread)
6532 break;
6533 /* Unbind it from offline cpu so it can run. Fall thru. */
6534 kthread_bind(cpu_rq(cpu)->migration_thread,
6535 any_online_cpu(cpu_online_map));
6536 kthread_stop(cpu_rq(cpu)->migration_thread);
6537 cpu_rq(cpu)->migration_thread = NULL;
6538 break;
6539
6540 case CPU_DEAD:
6541 case CPU_DEAD_FROZEN:
6542 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6543 migrate_live_tasks(cpu);
6544 rq = cpu_rq(cpu);
6545 kthread_stop(rq->migration_thread);
6546 rq->migration_thread = NULL;
6547 /* Idle task back to normal (off runqueue, low prio) */
6548 spin_lock_irq(&rq->lock);
6549 update_rq_clock(rq);
6550 deactivate_task(rq, rq->idle, 0);
6551 rq->idle->static_prio = MAX_PRIO;
6552 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6553 rq->idle->sched_class = &idle_sched_class;
6554 migrate_dead_tasks(cpu);
6555 spin_unlock_irq(&rq->lock);
6556 cpuset_unlock();
6557 migrate_nr_uninterruptible(rq);
6558 BUG_ON(rq->nr_running != 0);
6559
6560 /*
6561 * No need to migrate the tasks: it was best-effort if
6562 * they didn't take sched_hotcpu_mutex. Just wake up
6563 * the requestors.
6564 */
6565 spin_lock_irq(&rq->lock);
6566 while (!list_empty(&rq->migration_queue)) {
6567 struct migration_req *req;
6568
6569 req = list_entry(rq->migration_queue.next,
6570 struct migration_req, list);
6571 list_del_init(&req->list);
6572 complete(&req->done);
6573 }
6574 spin_unlock_irq(&rq->lock);
6575 break;
6576
6577 case CPU_DYING:
6578 case CPU_DYING_FROZEN:
6579 /* Update our root-domain */
6580 rq = cpu_rq(cpu);
6581 spin_lock_irqsave(&rq->lock, flags);
6582 if (rq->rd) {
6583 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6584 cpu_clear(cpu, rq->rd->online);
6585 }
6586 spin_unlock_irqrestore(&rq->lock, flags);
6587 break;
6588 #endif
6589 }
6590 return NOTIFY_OK;
6591 }
6592
6593 /* Register at highest priority so that task migration (migrate_all_tasks)
6594 * happens before everything else.
6595 */
6596 static struct notifier_block __cpuinitdata migration_notifier = {
6597 .notifier_call = migration_call,
6598 .priority = 10
6599 };
6600
6601 void __init migration_init(void)
6602 {
6603 void *cpu = (void *)(long)smp_processor_id();
6604 int err;
6605
6606 /* Start one for the boot CPU: */
6607 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6608 BUG_ON(err == NOTIFY_BAD);
6609 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6610 register_cpu_notifier(&migration_notifier);
6611 }
6612 #endif
6613
6614 #ifdef CONFIG_SMP
6615
6616 #ifdef CONFIG_SCHED_DEBUG
6617
6618 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6619 cpumask_t *groupmask)
6620 {
6621 struct sched_group *group = sd->groups;
6622 char str[256];
6623
6624 cpulist_scnprintf(str, sizeof(str), sd->span);
6625 cpus_clear(*groupmask);
6626
6627 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6628
6629 if (!(sd->flags & SD_LOAD_BALANCE)) {
6630 printk("does not load-balance\n");
6631 if (sd->parent)
6632 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6633 " has parent");
6634 return -1;
6635 }
6636
6637 printk(KERN_CONT "span %s\n", str);
6638
6639 if (!cpu_isset(cpu, sd->span)) {
6640 printk(KERN_ERR "ERROR: domain->span does not contain "
6641 "CPU%d\n", cpu);
6642 }
6643 if (!cpu_isset(cpu, group->cpumask)) {
6644 printk(KERN_ERR "ERROR: domain->groups does not contain"
6645 " CPU%d\n", cpu);
6646 }
6647
6648 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6649 do {
6650 if (!group) {
6651 printk("\n");
6652 printk(KERN_ERR "ERROR: group is NULL\n");
6653 break;
6654 }
6655
6656 if (!group->__cpu_power) {
6657 printk(KERN_CONT "\n");
6658 printk(KERN_ERR "ERROR: domain->cpu_power not "
6659 "set\n");
6660 break;
6661 }
6662
6663 if (!cpus_weight(group->cpumask)) {
6664 printk(KERN_CONT "\n");
6665 printk(KERN_ERR "ERROR: empty group\n");
6666 break;
6667 }
6668
6669 if (cpus_intersects(*groupmask, group->cpumask)) {
6670 printk(KERN_CONT "\n");
6671 printk(KERN_ERR "ERROR: repeated CPUs\n");
6672 break;
6673 }
6674
6675 cpus_or(*groupmask, *groupmask, group->cpumask);
6676
6677 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6678 printk(KERN_CONT " %s", str);
6679
6680 group = group->next;
6681 } while (group != sd->groups);
6682 printk(KERN_CONT "\n");
6683
6684 if (!cpus_equal(sd->span, *groupmask))
6685 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6686
6687 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6688 printk(KERN_ERR "ERROR: parent span is not a superset "
6689 "of domain->span\n");
6690 return 0;
6691 }
6692
6693 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6694 {
6695 cpumask_t *groupmask;
6696 int level = 0;
6697
6698 if (!sd) {
6699 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6700 return;
6701 }
6702
6703 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6704
6705 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6706 if (!groupmask) {
6707 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6708 return;
6709 }
6710
6711 for (;;) {
6712 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6713 break;
6714 level++;
6715 sd = sd->parent;
6716 if (!sd)
6717 break;
6718 }
6719 kfree(groupmask);
6720 }
6721 #else
6722 # define sched_domain_debug(sd, cpu) do { } while (0)
6723 #endif
6724
6725 static int sd_degenerate(struct sched_domain *sd)
6726 {
6727 if (cpus_weight(sd->span) == 1)
6728 return 1;
6729
6730 /* Following flags need at least 2 groups */
6731 if (sd->flags & (SD_LOAD_BALANCE |
6732 SD_BALANCE_NEWIDLE |
6733 SD_BALANCE_FORK |
6734 SD_BALANCE_EXEC |
6735 SD_SHARE_CPUPOWER |
6736 SD_SHARE_PKG_RESOURCES)) {
6737 if (sd->groups != sd->groups->next)
6738 return 0;
6739 }
6740
6741 /* Following flags don't use groups */
6742 if (sd->flags & (SD_WAKE_IDLE |
6743 SD_WAKE_AFFINE |
6744 SD_WAKE_BALANCE))
6745 return 0;
6746
6747 return 1;
6748 }
6749
6750 static int
6751 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6752 {
6753 unsigned long cflags = sd->flags, pflags = parent->flags;
6754
6755 if (sd_degenerate(parent))
6756 return 1;
6757
6758 if (!cpus_equal(sd->span, parent->span))
6759 return 0;
6760
6761 /* Does parent contain flags not in child? */
6762 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6763 if (cflags & SD_WAKE_AFFINE)
6764 pflags &= ~SD_WAKE_BALANCE;
6765 /* Flags needing groups don't count if only 1 group in parent */
6766 if (parent->groups == parent->groups->next) {
6767 pflags &= ~(SD_LOAD_BALANCE |
6768 SD_BALANCE_NEWIDLE |
6769 SD_BALANCE_FORK |
6770 SD_BALANCE_EXEC |
6771 SD_SHARE_CPUPOWER |
6772 SD_SHARE_PKG_RESOURCES);
6773 }
6774 if (~cflags & pflags)
6775 return 0;
6776
6777 return 1;
6778 }
6779
6780 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6781 {
6782 unsigned long flags;
6783 const struct sched_class *class;
6784
6785 spin_lock_irqsave(&rq->lock, flags);
6786
6787 if (rq->rd) {
6788 struct root_domain *old_rd = rq->rd;
6789
6790 for (class = sched_class_highest; class; class = class->next) {
6791 if (class->leave_domain)
6792 class->leave_domain(rq);
6793 }
6794
6795 cpu_clear(rq->cpu, old_rd->span);
6796 cpu_clear(rq->cpu, old_rd->online);
6797
6798 if (atomic_dec_and_test(&old_rd->refcount))
6799 kfree(old_rd);
6800 }
6801
6802 atomic_inc(&rd->refcount);
6803 rq->rd = rd;
6804
6805 cpu_set(rq->cpu, rd->span);
6806 if (cpu_isset(rq->cpu, cpu_online_map))
6807 cpu_set(rq->cpu, rd->online);
6808
6809 for (class = sched_class_highest; class; class = class->next) {
6810 if (class->join_domain)
6811 class->join_domain(rq);
6812 }
6813
6814 spin_unlock_irqrestore(&rq->lock, flags);
6815 }
6816
6817 static void init_rootdomain(struct root_domain *rd)
6818 {
6819 memset(rd, 0, sizeof(*rd));
6820
6821 cpus_clear(rd->span);
6822 cpus_clear(rd->online);
6823 }
6824
6825 static void init_defrootdomain(void)
6826 {
6827 init_rootdomain(&def_root_domain);
6828 atomic_set(&def_root_domain.refcount, 1);
6829 }
6830
6831 static struct root_domain *alloc_rootdomain(void)
6832 {
6833 struct root_domain *rd;
6834
6835 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6836 if (!rd)
6837 return NULL;
6838
6839 init_rootdomain(rd);
6840
6841 return rd;
6842 }
6843
6844 /*
6845 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6846 * hold the hotplug lock.
6847 */
6848 static void
6849 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6850 {
6851 struct rq *rq = cpu_rq(cpu);
6852 struct sched_domain *tmp;
6853
6854 /* Remove the sched domains which do not contribute to scheduling. */
6855 for (tmp = sd; tmp; tmp = tmp->parent) {
6856 struct sched_domain *parent = tmp->parent;
6857 if (!parent)
6858 break;
6859 if (sd_parent_degenerate(tmp, parent)) {
6860 tmp->parent = parent->parent;
6861 if (parent->parent)
6862 parent->parent->child = tmp;
6863 }
6864 }
6865
6866 if (sd && sd_degenerate(sd)) {
6867 sd = sd->parent;
6868 if (sd)
6869 sd->child = NULL;
6870 }
6871
6872 sched_domain_debug(sd, cpu);
6873
6874 rq_attach_root(rq, rd);
6875 rcu_assign_pointer(rq->sd, sd);
6876 }
6877
6878 /* cpus with isolated domains */
6879 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6880
6881 /* Setup the mask of cpus configured for isolated domains */
6882 static int __init isolated_cpu_setup(char *str)
6883 {
6884 int ints[NR_CPUS], i;
6885
6886 str = get_options(str, ARRAY_SIZE(ints), ints);
6887 cpus_clear(cpu_isolated_map);
6888 for (i = 1; i <= ints[0]; i++)
6889 if (ints[i] < NR_CPUS)
6890 cpu_set(ints[i], cpu_isolated_map);
6891 return 1;
6892 }
6893
6894 __setup("isolcpus=", isolated_cpu_setup);
6895
6896 /*
6897 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6898 * to a function which identifies what group(along with sched group) a CPU
6899 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6900 * (due to the fact that we keep track of groups covered with a cpumask_t).
6901 *
6902 * init_sched_build_groups will build a circular linked list of the groups
6903 * covered by the given span, and will set each group's ->cpumask correctly,
6904 * and ->cpu_power to 0.
6905 */
6906 static void
6907 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6908 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6909 struct sched_group **sg,
6910 cpumask_t *tmpmask),
6911 cpumask_t *covered, cpumask_t *tmpmask)
6912 {
6913 struct sched_group *first = NULL, *last = NULL;
6914 int i;
6915
6916 cpus_clear(*covered);
6917
6918 for_each_cpu_mask(i, *span) {
6919 struct sched_group *sg;
6920 int group = group_fn(i, cpu_map, &sg, tmpmask);
6921 int j;
6922
6923 if (cpu_isset(i, *covered))
6924 continue;
6925
6926 cpus_clear(sg->cpumask);
6927 sg->__cpu_power = 0;
6928
6929 for_each_cpu_mask(j, *span) {
6930 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6931 continue;
6932
6933 cpu_set(j, *covered);
6934 cpu_set(j, sg->cpumask);
6935 }
6936 if (!first)
6937 first = sg;
6938 if (last)
6939 last->next = sg;
6940 last = sg;
6941 }
6942 last->next = first;
6943 }
6944
6945 #define SD_NODES_PER_DOMAIN 16
6946
6947 #ifdef CONFIG_NUMA
6948
6949 /**
6950 * find_next_best_node - find the next node to include in a sched_domain
6951 * @node: node whose sched_domain we're building
6952 * @used_nodes: nodes already in the sched_domain
6953 *
6954 * Find the next node to include in a given scheduling domain. Simply
6955 * finds the closest node not already in the @used_nodes map.
6956 *
6957 * Should use nodemask_t.
6958 */
6959 static int find_next_best_node(int node, nodemask_t *used_nodes)
6960 {
6961 int i, n, val, min_val, best_node = 0;
6962
6963 min_val = INT_MAX;
6964
6965 for (i = 0; i < MAX_NUMNODES; i++) {
6966 /* Start at @node */
6967 n = (node + i) % MAX_NUMNODES;
6968
6969 if (!nr_cpus_node(n))
6970 continue;
6971
6972 /* Skip already used nodes */
6973 if (node_isset(n, *used_nodes))
6974 continue;
6975
6976 /* Simple min distance search */
6977 val = node_distance(node, n);
6978
6979 if (val < min_val) {
6980 min_val = val;
6981 best_node = n;
6982 }
6983 }
6984
6985 node_set(best_node, *used_nodes);
6986 return best_node;
6987 }
6988
6989 /**
6990 * sched_domain_node_span - get a cpumask for a node's sched_domain
6991 * @node: node whose cpumask we're constructing
6992 * @span: resulting cpumask
6993 *
6994 * Given a node, construct a good cpumask for its sched_domain to span. It
6995 * should be one that prevents unnecessary balancing, but also spreads tasks
6996 * out optimally.
6997 */
6998 static void sched_domain_node_span(int node, cpumask_t *span)
6999 {
7000 nodemask_t used_nodes;
7001 node_to_cpumask_ptr(nodemask, node);
7002 int i;
7003
7004 cpus_clear(*span);
7005 nodes_clear(used_nodes);
7006
7007 cpus_or(*span, *span, *nodemask);
7008 node_set(node, used_nodes);
7009
7010 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7011 int next_node = find_next_best_node(node, &used_nodes);
7012
7013 node_to_cpumask_ptr_next(nodemask, next_node);
7014 cpus_or(*span, *span, *nodemask);
7015 }
7016 }
7017 #endif
7018
7019 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7020
7021 /*
7022 * SMT sched-domains:
7023 */
7024 #ifdef CONFIG_SCHED_SMT
7025 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7026 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7027
7028 static int
7029 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7030 cpumask_t *unused)
7031 {
7032 if (sg)
7033 *sg = &per_cpu(sched_group_cpus, cpu);
7034 return cpu;
7035 }
7036 #endif
7037
7038 /*
7039 * multi-core sched-domains:
7040 */
7041 #ifdef CONFIG_SCHED_MC
7042 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7043 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7044 #endif
7045
7046 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7047 static int
7048 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7049 cpumask_t *mask)
7050 {
7051 int group;
7052
7053 *mask = per_cpu(cpu_sibling_map, cpu);
7054 cpus_and(*mask, *mask, *cpu_map);
7055 group = first_cpu(*mask);
7056 if (sg)
7057 *sg = &per_cpu(sched_group_core, group);
7058 return group;
7059 }
7060 #elif defined(CONFIG_SCHED_MC)
7061 static int
7062 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7063 cpumask_t *unused)
7064 {
7065 if (sg)
7066 *sg = &per_cpu(sched_group_core, cpu);
7067 return cpu;
7068 }
7069 #endif
7070
7071 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7072 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7073
7074 static int
7075 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7076 cpumask_t *mask)
7077 {
7078 int group;
7079 #ifdef CONFIG_SCHED_MC
7080 *mask = cpu_coregroup_map(cpu);
7081 cpus_and(*mask, *mask, *cpu_map);
7082 group = first_cpu(*mask);
7083 #elif defined(CONFIG_SCHED_SMT)
7084 *mask = per_cpu(cpu_sibling_map, cpu);
7085 cpus_and(*mask, *mask, *cpu_map);
7086 group = first_cpu(*mask);
7087 #else
7088 group = cpu;
7089 #endif
7090 if (sg)
7091 *sg = &per_cpu(sched_group_phys, group);
7092 return group;
7093 }
7094
7095 #ifdef CONFIG_NUMA
7096 /*
7097 * The init_sched_build_groups can't handle what we want to do with node
7098 * groups, so roll our own. Now each node has its own list of groups which
7099 * gets dynamically allocated.
7100 */
7101 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7102 static struct sched_group ***sched_group_nodes_bycpu;
7103
7104 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7105 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7106
7107 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7108 struct sched_group **sg, cpumask_t *nodemask)
7109 {
7110 int group;
7111
7112 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7113 cpus_and(*nodemask, *nodemask, *cpu_map);
7114 group = first_cpu(*nodemask);
7115
7116 if (sg)
7117 *sg = &per_cpu(sched_group_allnodes, group);
7118 return group;
7119 }
7120
7121 static void init_numa_sched_groups_power(struct sched_group *group_head)
7122 {
7123 struct sched_group *sg = group_head;
7124 int j;
7125
7126 if (!sg)
7127 return;
7128 do {
7129 for_each_cpu_mask(j, sg->cpumask) {
7130 struct sched_domain *sd;
7131
7132 sd = &per_cpu(phys_domains, j);
7133 if (j != first_cpu(sd->groups->cpumask)) {
7134 /*
7135 * Only add "power" once for each
7136 * physical package.
7137 */
7138 continue;
7139 }
7140
7141 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7142 }
7143 sg = sg->next;
7144 } while (sg != group_head);
7145 }
7146 #endif
7147
7148 #ifdef CONFIG_NUMA
7149 /* Free memory allocated for various sched_group structures */
7150 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7151 {
7152 int cpu, i;
7153
7154 for_each_cpu_mask(cpu, *cpu_map) {
7155 struct sched_group **sched_group_nodes
7156 = sched_group_nodes_bycpu[cpu];
7157
7158 if (!sched_group_nodes)
7159 continue;
7160
7161 for (i = 0; i < MAX_NUMNODES; i++) {
7162 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7163
7164 *nodemask = node_to_cpumask(i);
7165 cpus_and(*nodemask, *nodemask, *cpu_map);
7166 if (cpus_empty(*nodemask))
7167 continue;
7168
7169 if (sg == NULL)
7170 continue;
7171 sg = sg->next;
7172 next_sg:
7173 oldsg = sg;
7174 sg = sg->next;
7175 kfree(oldsg);
7176 if (oldsg != sched_group_nodes[i])
7177 goto next_sg;
7178 }
7179 kfree(sched_group_nodes);
7180 sched_group_nodes_bycpu[cpu] = NULL;
7181 }
7182 }
7183 #else
7184 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7185 {
7186 }
7187 #endif
7188
7189 /*
7190 * Initialize sched groups cpu_power.
7191 *
7192 * cpu_power indicates the capacity of sched group, which is used while
7193 * distributing the load between different sched groups in a sched domain.
7194 * Typically cpu_power for all the groups in a sched domain will be same unless
7195 * there are asymmetries in the topology. If there are asymmetries, group
7196 * having more cpu_power will pickup more load compared to the group having
7197 * less cpu_power.
7198 *
7199 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7200 * the maximum number of tasks a group can handle in the presence of other idle
7201 * or lightly loaded groups in the same sched domain.
7202 */
7203 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7204 {
7205 struct sched_domain *child;
7206 struct sched_group *group;
7207
7208 WARN_ON(!sd || !sd->groups);
7209
7210 if (cpu != first_cpu(sd->groups->cpumask))
7211 return;
7212
7213 child = sd->child;
7214
7215 sd->groups->__cpu_power = 0;
7216
7217 /*
7218 * For perf policy, if the groups in child domain share resources
7219 * (for example cores sharing some portions of the cache hierarchy
7220 * or SMT), then set this domain groups cpu_power such that each group
7221 * can handle only one task, when there are other idle groups in the
7222 * same sched domain.
7223 */
7224 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7225 (child->flags &
7226 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7227 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7228 return;
7229 }
7230
7231 /*
7232 * add cpu_power of each child group to this groups cpu_power
7233 */
7234 group = child->groups;
7235 do {
7236 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7237 group = group->next;
7238 } while (group != child->groups);
7239 }
7240
7241 /*
7242 * Initializers for schedule domains
7243 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7244 */
7245
7246 #define SD_INIT(sd, type) sd_init_##type(sd)
7247 #define SD_INIT_FUNC(type) \
7248 static noinline void sd_init_##type(struct sched_domain *sd) \
7249 { \
7250 memset(sd, 0, sizeof(*sd)); \
7251 *sd = SD_##type##_INIT; \
7252 sd->level = SD_LV_##type; \
7253 }
7254
7255 SD_INIT_FUNC(CPU)
7256 #ifdef CONFIG_NUMA
7257 SD_INIT_FUNC(ALLNODES)
7258 SD_INIT_FUNC(NODE)
7259 #endif
7260 #ifdef CONFIG_SCHED_SMT
7261 SD_INIT_FUNC(SIBLING)
7262 #endif
7263 #ifdef CONFIG_SCHED_MC
7264 SD_INIT_FUNC(MC)
7265 #endif
7266
7267 /*
7268 * To minimize stack usage kmalloc room for cpumasks and share the
7269 * space as the usage in build_sched_domains() dictates. Used only
7270 * if the amount of space is significant.
7271 */
7272 struct allmasks {
7273 cpumask_t tmpmask; /* make this one first */
7274 union {
7275 cpumask_t nodemask;
7276 cpumask_t this_sibling_map;
7277 cpumask_t this_core_map;
7278 };
7279 cpumask_t send_covered;
7280
7281 #ifdef CONFIG_NUMA
7282 cpumask_t domainspan;
7283 cpumask_t covered;
7284 cpumask_t notcovered;
7285 #endif
7286 };
7287
7288 #if NR_CPUS > 128
7289 #define SCHED_CPUMASK_ALLOC 1
7290 #define SCHED_CPUMASK_FREE(v) kfree(v)
7291 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7292 #else
7293 #define SCHED_CPUMASK_ALLOC 0
7294 #define SCHED_CPUMASK_FREE(v)
7295 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7296 #endif
7297
7298 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7299 ((unsigned long)(a) + offsetof(struct allmasks, v))
7300
7301 static int default_relax_domain_level = -1;
7302
7303 static int __init setup_relax_domain_level(char *str)
7304 {
7305 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7306 return 1;
7307 }
7308 __setup("relax_domain_level=", setup_relax_domain_level);
7309
7310 static void set_domain_attribute(struct sched_domain *sd,
7311 struct sched_domain_attr *attr)
7312 {
7313 int request;
7314
7315 if (!attr || attr->relax_domain_level < 0) {
7316 if (default_relax_domain_level < 0)
7317 return;
7318 else
7319 request = default_relax_domain_level;
7320 } else
7321 request = attr->relax_domain_level;
7322 if (request < sd->level) {
7323 /* turn off idle balance on this domain */
7324 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7325 } else {
7326 /* turn on idle balance on this domain */
7327 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7328 }
7329 }
7330
7331 /*
7332 * Build sched domains for a given set of cpus and attach the sched domains
7333 * to the individual cpus
7334 */
7335 static int __build_sched_domains(const cpumask_t *cpu_map,
7336 struct sched_domain_attr *attr)
7337 {
7338 int i;
7339 struct root_domain *rd;
7340 SCHED_CPUMASK_DECLARE(allmasks);
7341 cpumask_t *tmpmask;
7342 #ifdef CONFIG_NUMA
7343 struct sched_group **sched_group_nodes = NULL;
7344 int sd_allnodes = 0;
7345
7346 /*
7347 * Allocate the per-node list of sched groups
7348 */
7349 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7350 GFP_KERNEL);
7351 if (!sched_group_nodes) {
7352 printk(KERN_WARNING "Can not alloc sched group node list\n");
7353 return -ENOMEM;
7354 }
7355 #endif
7356
7357 rd = alloc_rootdomain();
7358 if (!rd) {
7359 printk(KERN_WARNING "Cannot alloc root domain\n");
7360 #ifdef CONFIG_NUMA
7361 kfree(sched_group_nodes);
7362 #endif
7363 return -ENOMEM;
7364 }
7365
7366 #if SCHED_CPUMASK_ALLOC
7367 /* get space for all scratch cpumask variables */
7368 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7369 if (!allmasks) {
7370 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7371 kfree(rd);
7372 #ifdef CONFIG_NUMA
7373 kfree(sched_group_nodes);
7374 #endif
7375 return -ENOMEM;
7376 }
7377 #endif
7378 tmpmask = (cpumask_t *)allmasks;
7379
7380
7381 #ifdef CONFIG_NUMA
7382 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7383 #endif
7384
7385 /*
7386 * Set up domains for cpus specified by the cpu_map.
7387 */
7388 for_each_cpu_mask(i, *cpu_map) {
7389 struct sched_domain *sd = NULL, *p;
7390 SCHED_CPUMASK_VAR(nodemask, allmasks);
7391
7392 *nodemask = node_to_cpumask(cpu_to_node(i));
7393 cpus_and(*nodemask, *nodemask, *cpu_map);
7394
7395 #ifdef CONFIG_NUMA
7396 if (cpus_weight(*cpu_map) >
7397 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7398 sd = &per_cpu(allnodes_domains, i);
7399 SD_INIT(sd, ALLNODES);
7400 set_domain_attribute(sd, attr);
7401 sd->span = *cpu_map;
7402 sd->first_cpu = first_cpu(sd->span);
7403 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7404 p = sd;
7405 sd_allnodes = 1;
7406 } else
7407 p = NULL;
7408
7409 sd = &per_cpu(node_domains, i);
7410 SD_INIT(sd, NODE);
7411 set_domain_attribute(sd, attr);
7412 sched_domain_node_span(cpu_to_node(i), &sd->span);
7413 sd->first_cpu = first_cpu(sd->span);
7414 sd->parent = p;
7415 if (p)
7416 p->child = sd;
7417 cpus_and(sd->span, sd->span, *cpu_map);
7418 #endif
7419
7420 p = sd;
7421 sd = &per_cpu(phys_domains, i);
7422 SD_INIT(sd, CPU);
7423 set_domain_attribute(sd, attr);
7424 sd->span = *nodemask;
7425 sd->first_cpu = first_cpu(sd->span);
7426 sd->parent = p;
7427 if (p)
7428 p->child = sd;
7429 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7430
7431 #ifdef CONFIG_SCHED_MC
7432 p = sd;
7433 sd = &per_cpu(core_domains, i);
7434 SD_INIT(sd, MC);
7435 set_domain_attribute(sd, attr);
7436 sd->span = cpu_coregroup_map(i);
7437 sd->first_cpu = first_cpu(sd->span);
7438 cpus_and(sd->span, sd->span, *cpu_map);
7439 sd->parent = p;
7440 p->child = sd;
7441 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7442 #endif
7443
7444 #ifdef CONFIG_SCHED_SMT
7445 p = sd;
7446 sd = &per_cpu(cpu_domains, i);
7447 SD_INIT(sd, SIBLING);
7448 set_domain_attribute(sd, attr);
7449 sd->span = per_cpu(cpu_sibling_map, i);
7450 sd->first_cpu = first_cpu(sd->span);
7451 cpus_and(sd->span, sd->span, *cpu_map);
7452 sd->parent = p;
7453 p->child = sd;
7454 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7455 #endif
7456 }
7457
7458 #ifdef CONFIG_SCHED_SMT
7459 /* Set up CPU (sibling) groups */
7460 for_each_cpu_mask(i, *cpu_map) {
7461 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7462 SCHED_CPUMASK_VAR(send_covered, allmasks);
7463
7464 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7465 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7466 if (i != first_cpu(*this_sibling_map))
7467 continue;
7468
7469 init_sched_build_groups(this_sibling_map, cpu_map,
7470 &cpu_to_cpu_group,
7471 send_covered, tmpmask);
7472 }
7473 #endif
7474
7475 #ifdef CONFIG_SCHED_MC
7476 /* Set up multi-core groups */
7477 for_each_cpu_mask(i, *cpu_map) {
7478 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7479 SCHED_CPUMASK_VAR(send_covered, allmasks);
7480
7481 *this_core_map = cpu_coregroup_map(i);
7482 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7483 if (i != first_cpu(*this_core_map))
7484 continue;
7485
7486 init_sched_build_groups(this_core_map, cpu_map,
7487 &cpu_to_core_group,
7488 send_covered, tmpmask);
7489 }
7490 #endif
7491
7492 /* Set up physical groups */
7493 for (i = 0; i < MAX_NUMNODES; i++) {
7494 SCHED_CPUMASK_VAR(nodemask, allmasks);
7495 SCHED_CPUMASK_VAR(send_covered, allmasks);
7496
7497 *nodemask = node_to_cpumask(i);
7498 cpus_and(*nodemask, *nodemask, *cpu_map);
7499 if (cpus_empty(*nodemask))
7500 continue;
7501
7502 init_sched_build_groups(nodemask, cpu_map,
7503 &cpu_to_phys_group,
7504 send_covered, tmpmask);
7505 }
7506
7507 #ifdef CONFIG_NUMA
7508 /* Set up node groups */
7509 if (sd_allnodes) {
7510 SCHED_CPUMASK_VAR(send_covered, allmasks);
7511
7512 init_sched_build_groups(cpu_map, cpu_map,
7513 &cpu_to_allnodes_group,
7514 send_covered, tmpmask);
7515 }
7516
7517 for (i = 0; i < MAX_NUMNODES; i++) {
7518 /* Set up node groups */
7519 struct sched_group *sg, *prev;
7520 SCHED_CPUMASK_VAR(nodemask, allmasks);
7521 SCHED_CPUMASK_VAR(domainspan, allmasks);
7522 SCHED_CPUMASK_VAR(covered, allmasks);
7523 int j;
7524
7525 *nodemask = node_to_cpumask(i);
7526 cpus_clear(*covered);
7527
7528 cpus_and(*nodemask, *nodemask, *cpu_map);
7529 if (cpus_empty(*nodemask)) {
7530 sched_group_nodes[i] = NULL;
7531 continue;
7532 }
7533
7534 sched_domain_node_span(i, domainspan);
7535 cpus_and(*domainspan, *domainspan, *cpu_map);
7536
7537 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7538 if (!sg) {
7539 printk(KERN_WARNING "Can not alloc domain group for "
7540 "node %d\n", i);
7541 goto error;
7542 }
7543 sched_group_nodes[i] = sg;
7544 for_each_cpu_mask(j, *nodemask) {
7545 struct sched_domain *sd;
7546
7547 sd = &per_cpu(node_domains, j);
7548 sd->groups = sg;
7549 }
7550 sg->__cpu_power = 0;
7551 sg->cpumask = *nodemask;
7552 sg->next = sg;
7553 cpus_or(*covered, *covered, *nodemask);
7554 prev = sg;
7555
7556 for (j = 0; j < MAX_NUMNODES; j++) {
7557 SCHED_CPUMASK_VAR(notcovered, allmasks);
7558 int n = (i + j) % MAX_NUMNODES;
7559 node_to_cpumask_ptr(pnodemask, n);
7560
7561 cpus_complement(*notcovered, *covered);
7562 cpus_and(*tmpmask, *notcovered, *cpu_map);
7563 cpus_and(*tmpmask, *tmpmask, *domainspan);
7564 if (cpus_empty(*tmpmask))
7565 break;
7566
7567 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7568 if (cpus_empty(*tmpmask))
7569 continue;
7570
7571 sg = kmalloc_node(sizeof(struct sched_group),
7572 GFP_KERNEL, i);
7573 if (!sg) {
7574 printk(KERN_WARNING
7575 "Can not alloc domain group for node %d\n", j);
7576 goto error;
7577 }
7578 sg->__cpu_power = 0;
7579 sg->cpumask = *tmpmask;
7580 sg->next = prev->next;
7581 cpus_or(*covered, *covered, *tmpmask);
7582 prev->next = sg;
7583 prev = sg;
7584 }
7585 }
7586 #endif
7587
7588 /* Calculate CPU power for physical packages and nodes */
7589 #ifdef CONFIG_SCHED_SMT
7590 for_each_cpu_mask(i, *cpu_map) {
7591 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7592
7593 init_sched_groups_power(i, sd);
7594 }
7595 #endif
7596 #ifdef CONFIG_SCHED_MC
7597 for_each_cpu_mask(i, *cpu_map) {
7598 struct sched_domain *sd = &per_cpu(core_domains, i);
7599
7600 init_sched_groups_power(i, sd);
7601 }
7602 #endif
7603
7604 for_each_cpu_mask(i, *cpu_map) {
7605 struct sched_domain *sd = &per_cpu(phys_domains, i);
7606
7607 init_sched_groups_power(i, sd);
7608 }
7609
7610 #ifdef CONFIG_NUMA
7611 for (i = 0; i < MAX_NUMNODES; i++)
7612 init_numa_sched_groups_power(sched_group_nodes[i]);
7613
7614 if (sd_allnodes) {
7615 struct sched_group *sg;
7616
7617 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7618 tmpmask);
7619 init_numa_sched_groups_power(sg);
7620 }
7621 #endif
7622
7623 /* Attach the domains */
7624 for_each_cpu_mask(i, *cpu_map) {
7625 struct sched_domain *sd;
7626 #ifdef CONFIG_SCHED_SMT
7627 sd = &per_cpu(cpu_domains, i);
7628 #elif defined(CONFIG_SCHED_MC)
7629 sd = &per_cpu(core_domains, i);
7630 #else
7631 sd = &per_cpu(phys_domains, i);
7632 #endif
7633 cpu_attach_domain(sd, rd, i);
7634 }
7635
7636 SCHED_CPUMASK_FREE((void *)allmasks);
7637 return 0;
7638
7639 #ifdef CONFIG_NUMA
7640 error:
7641 free_sched_groups(cpu_map, tmpmask);
7642 SCHED_CPUMASK_FREE((void *)allmasks);
7643 return -ENOMEM;
7644 #endif
7645 }
7646
7647 static int build_sched_domains(const cpumask_t *cpu_map)
7648 {
7649 return __build_sched_domains(cpu_map, NULL);
7650 }
7651
7652 static cpumask_t *doms_cur; /* current sched domains */
7653 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7654 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7655 in 'doms_cur' */
7656
7657 /*
7658 * Special case: If a kmalloc of a doms_cur partition (array of
7659 * cpumask_t) fails, then fallback to a single sched domain,
7660 * as determined by the single cpumask_t fallback_doms.
7661 */
7662 static cpumask_t fallback_doms;
7663
7664 void __attribute__((weak)) arch_update_cpu_topology(void)
7665 {
7666 }
7667
7668 /*
7669 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7670 * For now this just excludes isolated cpus, but could be used to
7671 * exclude other special cases in the future.
7672 */
7673 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7674 {
7675 int err;
7676
7677 arch_update_cpu_topology();
7678 ndoms_cur = 1;
7679 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7680 if (!doms_cur)
7681 doms_cur = &fallback_doms;
7682 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7683 dattr_cur = NULL;
7684 err = build_sched_domains(doms_cur);
7685 register_sched_domain_sysctl();
7686
7687 return err;
7688 }
7689
7690 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7691 cpumask_t *tmpmask)
7692 {
7693 free_sched_groups(cpu_map, tmpmask);
7694 }
7695
7696 /*
7697 * Detach sched domains from a group of cpus specified in cpu_map
7698 * These cpus will now be attached to the NULL domain
7699 */
7700 static void detach_destroy_domains(const cpumask_t *cpu_map)
7701 {
7702 cpumask_t tmpmask;
7703 int i;
7704
7705 unregister_sched_domain_sysctl();
7706
7707 for_each_cpu_mask(i, *cpu_map)
7708 cpu_attach_domain(NULL, &def_root_domain, i);
7709 synchronize_sched();
7710 arch_destroy_sched_domains(cpu_map, &tmpmask);
7711 }
7712
7713 /* handle null as "default" */
7714 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7715 struct sched_domain_attr *new, int idx_new)
7716 {
7717 struct sched_domain_attr tmp;
7718
7719 /* fast path */
7720 if (!new && !cur)
7721 return 1;
7722
7723 tmp = SD_ATTR_INIT;
7724 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7725 new ? (new + idx_new) : &tmp,
7726 sizeof(struct sched_domain_attr));
7727 }
7728
7729 /*
7730 * Partition sched domains as specified by the 'ndoms_new'
7731 * cpumasks in the array doms_new[] of cpumasks. This compares
7732 * doms_new[] to the current sched domain partitioning, doms_cur[].
7733 * It destroys each deleted domain and builds each new domain.
7734 *
7735 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7736 * The masks don't intersect (don't overlap.) We should setup one
7737 * sched domain for each mask. CPUs not in any of the cpumasks will
7738 * not be load balanced. If the same cpumask appears both in the
7739 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7740 * it as it is.
7741 *
7742 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7743 * ownership of it and will kfree it when done with it. If the caller
7744 * failed the kmalloc call, then it can pass in doms_new == NULL,
7745 * and partition_sched_domains() will fallback to the single partition
7746 * 'fallback_doms'.
7747 *
7748 * Call with hotplug lock held
7749 */
7750 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7751 struct sched_domain_attr *dattr_new)
7752 {
7753 int i, j;
7754
7755 mutex_lock(&sched_domains_mutex);
7756
7757 /* always unregister in case we don't destroy any domains */
7758 unregister_sched_domain_sysctl();
7759
7760 if (doms_new == NULL) {
7761 ndoms_new = 1;
7762 doms_new = &fallback_doms;
7763 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7764 dattr_new = NULL;
7765 }
7766
7767 /* Destroy deleted domains */
7768 for (i = 0; i < ndoms_cur; i++) {
7769 for (j = 0; j < ndoms_new; j++) {
7770 if (cpus_equal(doms_cur[i], doms_new[j])
7771 && dattrs_equal(dattr_cur, i, dattr_new, j))
7772 goto match1;
7773 }
7774 /* no match - a current sched domain not in new doms_new[] */
7775 detach_destroy_domains(doms_cur + i);
7776 match1:
7777 ;
7778 }
7779
7780 /* Build new domains */
7781 for (i = 0; i < ndoms_new; i++) {
7782 for (j = 0; j < ndoms_cur; j++) {
7783 if (cpus_equal(doms_new[i], doms_cur[j])
7784 && dattrs_equal(dattr_new, i, dattr_cur, j))
7785 goto match2;
7786 }
7787 /* no match - add a new doms_new */
7788 __build_sched_domains(doms_new + i,
7789 dattr_new ? dattr_new + i : NULL);
7790 match2:
7791 ;
7792 }
7793
7794 /* Remember the new sched domains */
7795 if (doms_cur != &fallback_doms)
7796 kfree(doms_cur);
7797 kfree(dattr_cur); /* kfree(NULL) is safe */
7798 doms_cur = doms_new;
7799 dattr_cur = dattr_new;
7800 ndoms_cur = ndoms_new;
7801
7802 register_sched_domain_sysctl();
7803
7804 mutex_unlock(&sched_domains_mutex);
7805 }
7806
7807 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7808 int arch_reinit_sched_domains(void)
7809 {
7810 int err;
7811
7812 get_online_cpus();
7813 mutex_lock(&sched_domains_mutex);
7814 detach_destroy_domains(&cpu_online_map);
7815 err = arch_init_sched_domains(&cpu_online_map);
7816 mutex_unlock(&sched_domains_mutex);
7817 put_online_cpus();
7818
7819 return err;
7820 }
7821
7822 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7823 {
7824 int ret;
7825
7826 if (buf[0] != '0' && buf[0] != '1')
7827 return -EINVAL;
7828
7829 if (smt)
7830 sched_smt_power_savings = (buf[0] == '1');
7831 else
7832 sched_mc_power_savings = (buf[0] == '1');
7833
7834 ret = arch_reinit_sched_domains();
7835
7836 return ret ? ret : count;
7837 }
7838
7839 #ifdef CONFIG_SCHED_MC
7840 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7841 {
7842 return sprintf(page, "%u\n", sched_mc_power_savings);
7843 }
7844 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7845 const char *buf, size_t count)
7846 {
7847 return sched_power_savings_store(buf, count, 0);
7848 }
7849 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7850 sched_mc_power_savings_store);
7851 #endif
7852
7853 #ifdef CONFIG_SCHED_SMT
7854 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7855 {
7856 return sprintf(page, "%u\n", sched_smt_power_savings);
7857 }
7858 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7859 const char *buf, size_t count)
7860 {
7861 return sched_power_savings_store(buf, count, 1);
7862 }
7863 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7864 sched_smt_power_savings_store);
7865 #endif
7866
7867 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7868 {
7869 int err = 0;
7870
7871 #ifdef CONFIG_SCHED_SMT
7872 if (smt_capable())
7873 err = sysfs_create_file(&cls->kset.kobj,
7874 &attr_sched_smt_power_savings.attr);
7875 #endif
7876 #ifdef CONFIG_SCHED_MC
7877 if (!err && mc_capable())
7878 err = sysfs_create_file(&cls->kset.kobj,
7879 &attr_sched_mc_power_savings.attr);
7880 #endif
7881 return err;
7882 }
7883 #endif
7884
7885 /*
7886 * Force a reinitialization of the sched domains hierarchy. The domains
7887 * and groups cannot be updated in place without racing with the balancing
7888 * code, so we temporarily attach all running cpus to the NULL domain
7889 * which will prevent rebalancing while the sched domains are recalculated.
7890 */
7891 static int update_sched_domains(struct notifier_block *nfb,
7892 unsigned long action, void *hcpu)
7893 {
7894 switch (action) {
7895 case CPU_UP_PREPARE:
7896 case CPU_UP_PREPARE_FROZEN:
7897 case CPU_DOWN_PREPARE:
7898 case CPU_DOWN_PREPARE_FROZEN:
7899 detach_destroy_domains(&cpu_online_map);
7900 return NOTIFY_OK;
7901
7902 case CPU_UP_CANCELED:
7903 case CPU_UP_CANCELED_FROZEN:
7904 case CPU_DOWN_FAILED:
7905 case CPU_DOWN_FAILED_FROZEN:
7906 case CPU_ONLINE:
7907 case CPU_ONLINE_FROZEN:
7908 case CPU_DEAD:
7909 case CPU_DEAD_FROZEN:
7910 /*
7911 * Fall through and re-initialise the domains.
7912 */
7913 break;
7914 default:
7915 return NOTIFY_DONE;
7916 }
7917
7918 /* The hotplug lock is already held by cpu_up/cpu_down */
7919 arch_init_sched_domains(&cpu_online_map);
7920
7921 return NOTIFY_OK;
7922 }
7923
7924 void __init sched_init_smp(void)
7925 {
7926 cpumask_t non_isolated_cpus;
7927
7928 #if defined(CONFIG_NUMA)
7929 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7930 GFP_KERNEL);
7931 BUG_ON(sched_group_nodes_bycpu == NULL);
7932 #endif
7933 get_online_cpus();
7934 mutex_lock(&sched_domains_mutex);
7935 arch_init_sched_domains(&cpu_online_map);
7936 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7937 if (cpus_empty(non_isolated_cpus))
7938 cpu_set(smp_processor_id(), non_isolated_cpus);
7939 mutex_unlock(&sched_domains_mutex);
7940 put_online_cpus();
7941 /* XXX: Theoretical race here - CPU may be hotplugged now */
7942 hotcpu_notifier(update_sched_domains, 0);
7943 init_hrtick();
7944
7945 /* Move init over to a non-isolated CPU */
7946 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7947 BUG();
7948 sched_init_granularity();
7949 }
7950 #else
7951 void __init sched_init_smp(void)
7952 {
7953 sched_init_granularity();
7954 }
7955 #endif /* CONFIG_SMP */
7956
7957 int in_sched_functions(unsigned long addr)
7958 {
7959 return in_lock_functions(addr) ||
7960 (addr >= (unsigned long)__sched_text_start
7961 && addr < (unsigned long)__sched_text_end);
7962 }
7963
7964 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7965 {
7966 cfs_rq->tasks_timeline = RB_ROOT;
7967 INIT_LIST_HEAD(&cfs_rq->tasks);
7968 #ifdef CONFIG_FAIR_GROUP_SCHED
7969 cfs_rq->rq = rq;
7970 #endif
7971 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7972 }
7973
7974 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7975 {
7976 struct rt_prio_array *array;
7977 int i;
7978
7979 array = &rt_rq->active;
7980 for (i = 0; i < MAX_RT_PRIO; i++) {
7981 INIT_LIST_HEAD(array->queue + i);
7982 __clear_bit(i, array->bitmap);
7983 }
7984 /* delimiter for bitsearch: */
7985 __set_bit(MAX_RT_PRIO, array->bitmap);
7986
7987 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7988 rt_rq->highest_prio = MAX_RT_PRIO;
7989 #endif
7990 #ifdef CONFIG_SMP
7991 rt_rq->rt_nr_migratory = 0;
7992 rt_rq->overloaded = 0;
7993 #endif
7994
7995 rt_rq->rt_time = 0;
7996 rt_rq->rt_throttled = 0;
7997 rt_rq->rt_runtime = 0;
7998 spin_lock_init(&rt_rq->rt_runtime_lock);
7999
8000 #ifdef CONFIG_RT_GROUP_SCHED
8001 rt_rq->rt_nr_boosted = 0;
8002 rt_rq->rq = rq;
8003 #endif
8004 }
8005
8006 #ifdef CONFIG_FAIR_GROUP_SCHED
8007 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8008 struct sched_entity *se, int cpu, int add,
8009 struct sched_entity *parent)
8010 {
8011 struct rq *rq = cpu_rq(cpu);
8012 tg->cfs_rq[cpu] = cfs_rq;
8013 init_cfs_rq(cfs_rq, rq);
8014 cfs_rq->tg = tg;
8015 if (add)
8016 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8017
8018 tg->se[cpu] = se;
8019 /* se could be NULL for init_task_group */
8020 if (!se)
8021 return;
8022
8023 if (!parent)
8024 se->cfs_rq = &rq->cfs;
8025 else
8026 se->cfs_rq = parent->my_q;
8027
8028 se->my_q = cfs_rq;
8029 se->load.weight = tg->shares;
8030 se->load.inv_weight = 0;
8031 se->parent = parent;
8032 }
8033 #endif
8034
8035 #ifdef CONFIG_RT_GROUP_SCHED
8036 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8037 struct sched_rt_entity *rt_se, int cpu, int add,
8038 struct sched_rt_entity *parent)
8039 {
8040 struct rq *rq = cpu_rq(cpu);
8041
8042 tg->rt_rq[cpu] = rt_rq;
8043 init_rt_rq(rt_rq, rq);
8044 rt_rq->tg = tg;
8045 rt_rq->rt_se = rt_se;
8046 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8047 if (add)
8048 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8049
8050 tg->rt_se[cpu] = rt_se;
8051 if (!rt_se)
8052 return;
8053
8054 if (!parent)
8055 rt_se->rt_rq = &rq->rt;
8056 else
8057 rt_se->rt_rq = parent->my_q;
8058
8059 rt_se->rt_rq = &rq->rt;
8060 rt_se->my_q = rt_rq;
8061 rt_se->parent = parent;
8062 INIT_LIST_HEAD(&rt_se->run_list);
8063 }
8064 #endif
8065
8066 void __init sched_init(void)
8067 {
8068 int i, j;
8069 unsigned long alloc_size = 0, ptr;
8070
8071 #ifdef CONFIG_FAIR_GROUP_SCHED
8072 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8073 #endif
8074 #ifdef CONFIG_RT_GROUP_SCHED
8075 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8076 #endif
8077 #ifdef CONFIG_USER_SCHED
8078 alloc_size *= 2;
8079 #endif
8080 /*
8081 * As sched_init() is called before page_alloc is setup,
8082 * we use alloc_bootmem().
8083 */
8084 if (alloc_size) {
8085 ptr = (unsigned long)alloc_bootmem(alloc_size);
8086
8087 #ifdef CONFIG_FAIR_GROUP_SCHED
8088 init_task_group.se = (struct sched_entity **)ptr;
8089 ptr += nr_cpu_ids * sizeof(void **);
8090
8091 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8092 ptr += nr_cpu_ids * sizeof(void **);
8093
8094 #ifdef CONFIG_USER_SCHED
8095 root_task_group.se = (struct sched_entity **)ptr;
8096 ptr += nr_cpu_ids * sizeof(void **);
8097
8098 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8099 ptr += nr_cpu_ids * sizeof(void **);
8100 #endif
8101 #endif
8102 #ifdef CONFIG_RT_GROUP_SCHED
8103 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8104 ptr += nr_cpu_ids * sizeof(void **);
8105
8106 init_task_group.rt_rq = (struct rt_rq **)ptr;
8107 ptr += nr_cpu_ids * sizeof(void **);
8108
8109 #ifdef CONFIG_USER_SCHED
8110 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8111 ptr += nr_cpu_ids * sizeof(void **);
8112
8113 root_task_group.rt_rq = (struct rt_rq **)ptr;
8114 ptr += nr_cpu_ids * sizeof(void **);
8115 #endif
8116 #endif
8117 }
8118
8119 #ifdef CONFIG_SMP
8120 init_aggregate();
8121 init_defrootdomain();
8122 #endif
8123
8124 init_rt_bandwidth(&def_rt_bandwidth,
8125 global_rt_period(), global_rt_runtime());
8126
8127 #ifdef CONFIG_RT_GROUP_SCHED
8128 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8129 global_rt_period(), global_rt_runtime());
8130 #ifdef CONFIG_USER_SCHED
8131 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8132 global_rt_period(), RUNTIME_INF);
8133 #endif
8134 #endif
8135
8136 #ifdef CONFIG_GROUP_SCHED
8137 list_add(&init_task_group.list, &task_groups);
8138 INIT_LIST_HEAD(&init_task_group.children);
8139
8140 #ifdef CONFIG_USER_SCHED
8141 INIT_LIST_HEAD(&root_task_group.children);
8142 init_task_group.parent = &root_task_group;
8143 list_add(&init_task_group.siblings, &root_task_group.children);
8144 #endif
8145 #endif
8146
8147 for_each_possible_cpu(i) {
8148 struct rq *rq;
8149
8150 rq = cpu_rq(i);
8151 spin_lock_init(&rq->lock);
8152 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8153 rq->nr_running = 0;
8154 init_cfs_rq(&rq->cfs, rq);
8155 init_rt_rq(&rq->rt, rq);
8156 #ifdef CONFIG_FAIR_GROUP_SCHED
8157 init_task_group.shares = init_task_group_load;
8158 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8159 #ifdef CONFIG_CGROUP_SCHED
8160 /*
8161 * How much cpu bandwidth does init_task_group get?
8162 *
8163 * In case of task-groups formed thr' the cgroup filesystem, it
8164 * gets 100% of the cpu resources in the system. This overall
8165 * system cpu resource is divided among the tasks of
8166 * init_task_group and its child task-groups in a fair manner,
8167 * based on each entity's (task or task-group's) weight
8168 * (se->load.weight).
8169 *
8170 * In other words, if init_task_group has 10 tasks of weight
8171 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8172 * then A0's share of the cpu resource is:
8173 *
8174 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8175 *
8176 * We achieve this by letting init_task_group's tasks sit
8177 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8178 */
8179 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8180 #elif defined CONFIG_USER_SCHED
8181 root_task_group.shares = NICE_0_LOAD;
8182 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8183 /*
8184 * In case of task-groups formed thr' the user id of tasks,
8185 * init_task_group represents tasks belonging to root user.
8186 * Hence it forms a sibling of all subsequent groups formed.
8187 * In this case, init_task_group gets only a fraction of overall
8188 * system cpu resource, based on the weight assigned to root
8189 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8190 * by letting tasks of init_task_group sit in a separate cfs_rq
8191 * (init_cfs_rq) and having one entity represent this group of
8192 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8193 */
8194 init_tg_cfs_entry(&init_task_group,
8195 &per_cpu(init_cfs_rq, i),
8196 &per_cpu(init_sched_entity, i), i, 1,
8197 root_task_group.se[i]);
8198
8199 #endif
8200 #endif /* CONFIG_FAIR_GROUP_SCHED */
8201
8202 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8203 #ifdef CONFIG_RT_GROUP_SCHED
8204 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8205 #ifdef CONFIG_CGROUP_SCHED
8206 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8207 #elif defined CONFIG_USER_SCHED
8208 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8209 init_tg_rt_entry(&init_task_group,
8210 &per_cpu(init_rt_rq, i),
8211 &per_cpu(init_sched_rt_entity, i), i, 1,
8212 root_task_group.rt_se[i]);
8213 #endif
8214 #endif
8215
8216 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8217 rq->cpu_load[j] = 0;
8218 #ifdef CONFIG_SMP
8219 rq->sd = NULL;
8220 rq->rd = NULL;
8221 rq->active_balance = 0;
8222 rq->next_balance = jiffies;
8223 rq->push_cpu = 0;
8224 rq->cpu = i;
8225 rq->migration_thread = NULL;
8226 INIT_LIST_HEAD(&rq->migration_queue);
8227 rq_attach_root(rq, &def_root_domain);
8228 #endif
8229 init_rq_hrtick(rq);
8230 atomic_set(&rq->nr_iowait, 0);
8231 }
8232
8233 set_load_weight(&init_task);
8234
8235 #ifdef CONFIG_PREEMPT_NOTIFIERS
8236 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8237 #endif
8238
8239 #ifdef CONFIG_SMP
8240 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8241 #endif
8242
8243 #ifdef CONFIG_RT_MUTEXES
8244 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8245 #endif
8246
8247 /*
8248 * The boot idle thread does lazy MMU switching as well:
8249 */
8250 atomic_inc(&init_mm.mm_count);
8251 enter_lazy_tlb(&init_mm, current);
8252
8253 /*
8254 * Make us the idle thread. Technically, schedule() should not be
8255 * called from this thread, however somewhere below it might be,
8256 * but because we are the idle thread, we just pick up running again
8257 * when this runqueue becomes "idle".
8258 */
8259 init_idle(current, smp_processor_id());
8260 /*
8261 * During early bootup we pretend to be a normal task:
8262 */
8263 current->sched_class = &fair_sched_class;
8264
8265 scheduler_running = 1;
8266 }
8267
8268 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8269 void __might_sleep(char *file, int line)
8270 {
8271 #ifdef in_atomic
8272 static unsigned long prev_jiffy; /* ratelimiting */
8273
8274 if ((in_atomic() || irqs_disabled()) &&
8275 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8276 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8277 return;
8278 prev_jiffy = jiffies;
8279 printk(KERN_ERR "BUG: sleeping function called from invalid"
8280 " context at %s:%d\n", file, line);
8281 printk("in_atomic():%d, irqs_disabled():%d\n",
8282 in_atomic(), irqs_disabled());
8283 debug_show_held_locks(current);
8284 if (irqs_disabled())
8285 print_irqtrace_events(current);
8286 dump_stack();
8287 }
8288 #endif
8289 }
8290 EXPORT_SYMBOL(__might_sleep);
8291 #endif
8292
8293 #ifdef CONFIG_MAGIC_SYSRQ
8294 static void normalize_task(struct rq *rq, struct task_struct *p)
8295 {
8296 int on_rq;
8297
8298 update_rq_clock(rq);
8299 on_rq = p->se.on_rq;
8300 if (on_rq)
8301 deactivate_task(rq, p, 0);
8302 __setscheduler(rq, p, SCHED_NORMAL, 0);
8303 if (on_rq) {
8304 activate_task(rq, p, 0);
8305 resched_task(rq->curr);
8306 }
8307 }
8308
8309 void normalize_rt_tasks(void)
8310 {
8311 struct task_struct *g, *p;
8312 unsigned long flags;
8313 struct rq *rq;
8314
8315 read_lock_irqsave(&tasklist_lock, flags);
8316 do_each_thread(g, p) {
8317 /*
8318 * Only normalize user tasks:
8319 */
8320 if (!p->mm)
8321 continue;
8322
8323 p->se.exec_start = 0;
8324 #ifdef CONFIG_SCHEDSTATS
8325 p->se.wait_start = 0;
8326 p->se.sleep_start = 0;
8327 p->se.block_start = 0;
8328 #endif
8329
8330 if (!rt_task(p)) {
8331 /*
8332 * Renice negative nice level userspace
8333 * tasks back to 0:
8334 */
8335 if (TASK_NICE(p) < 0 && p->mm)
8336 set_user_nice(p, 0);
8337 continue;
8338 }
8339
8340 spin_lock(&p->pi_lock);
8341 rq = __task_rq_lock(p);
8342
8343 normalize_task(rq, p);
8344
8345 __task_rq_unlock(rq);
8346 spin_unlock(&p->pi_lock);
8347 } while_each_thread(g, p);
8348
8349 read_unlock_irqrestore(&tasklist_lock, flags);
8350 }
8351
8352 #endif /* CONFIG_MAGIC_SYSRQ */
8353
8354 #ifdef CONFIG_IA64
8355 /*
8356 * These functions are only useful for the IA64 MCA handling.
8357 *
8358 * They can only be called when the whole system has been
8359 * stopped - every CPU needs to be quiescent, and no scheduling
8360 * activity can take place. Using them for anything else would
8361 * be a serious bug, and as a result, they aren't even visible
8362 * under any other configuration.
8363 */
8364
8365 /**
8366 * curr_task - return the current task for a given cpu.
8367 * @cpu: the processor in question.
8368 *
8369 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8370 */
8371 struct task_struct *curr_task(int cpu)
8372 {
8373 return cpu_curr(cpu);
8374 }
8375
8376 /**
8377 * set_curr_task - set the current task for a given cpu.
8378 * @cpu: the processor in question.
8379 * @p: the task pointer to set.
8380 *
8381 * Description: This function must only be used when non-maskable interrupts
8382 * are serviced on a separate stack. It allows the architecture to switch the
8383 * notion of the current task on a cpu in a non-blocking manner. This function
8384 * must be called with all CPU's synchronized, and interrupts disabled, the
8385 * and caller must save the original value of the current task (see
8386 * curr_task() above) and restore that value before reenabling interrupts and
8387 * re-starting the system.
8388 *
8389 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8390 */
8391 void set_curr_task(int cpu, struct task_struct *p)
8392 {
8393 cpu_curr(cpu) = p;
8394 }
8395
8396 #endif
8397
8398 #ifdef CONFIG_FAIR_GROUP_SCHED
8399 static void free_fair_sched_group(struct task_group *tg)
8400 {
8401 int i;
8402
8403 for_each_possible_cpu(i) {
8404 if (tg->cfs_rq)
8405 kfree(tg->cfs_rq[i]);
8406 if (tg->se)
8407 kfree(tg->se[i]);
8408 }
8409
8410 kfree(tg->cfs_rq);
8411 kfree(tg->se);
8412 }
8413
8414 static
8415 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8416 {
8417 struct cfs_rq *cfs_rq;
8418 struct sched_entity *se, *parent_se;
8419 struct rq *rq;
8420 int i;
8421
8422 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8423 if (!tg->cfs_rq)
8424 goto err;
8425 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8426 if (!tg->se)
8427 goto err;
8428
8429 tg->shares = NICE_0_LOAD;
8430
8431 for_each_possible_cpu(i) {
8432 rq = cpu_rq(i);
8433
8434 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8435 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8436 if (!cfs_rq)
8437 goto err;
8438
8439 se = kmalloc_node(sizeof(struct sched_entity),
8440 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8441 if (!se)
8442 goto err;
8443
8444 parent_se = parent ? parent->se[i] : NULL;
8445 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8446 }
8447
8448 return 1;
8449
8450 err:
8451 return 0;
8452 }
8453
8454 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8455 {
8456 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8457 &cpu_rq(cpu)->leaf_cfs_rq_list);
8458 }
8459
8460 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8461 {
8462 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8463 }
8464 #else
8465 static inline void free_fair_sched_group(struct task_group *tg)
8466 {
8467 }
8468
8469 static inline
8470 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8471 {
8472 return 1;
8473 }
8474
8475 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8476 {
8477 }
8478
8479 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8480 {
8481 }
8482 #endif
8483
8484 #ifdef CONFIG_RT_GROUP_SCHED
8485 static void free_rt_sched_group(struct task_group *tg)
8486 {
8487 int i;
8488
8489 destroy_rt_bandwidth(&tg->rt_bandwidth);
8490
8491 for_each_possible_cpu(i) {
8492 if (tg->rt_rq)
8493 kfree(tg->rt_rq[i]);
8494 if (tg->rt_se)
8495 kfree(tg->rt_se[i]);
8496 }
8497
8498 kfree(tg->rt_rq);
8499 kfree(tg->rt_se);
8500 }
8501
8502 static
8503 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8504 {
8505 struct rt_rq *rt_rq;
8506 struct sched_rt_entity *rt_se, *parent_se;
8507 struct rq *rq;
8508 int i;
8509
8510 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8511 if (!tg->rt_rq)
8512 goto err;
8513 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8514 if (!tg->rt_se)
8515 goto err;
8516
8517 init_rt_bandwidth(&tg->rt_bandwidth,
8518 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8519
8520 for_each_possible_cpu(i) {
8521 rq = cpu_rq(i);
8522
8523 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8524 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8525 if (!rt_rq)
8526 goto err;
8527
8528 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8529 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8530 if (!rt_se)
8531 goto err;
8532
8533 parent_se = parent ? parent->rt_se[i] : NULL;
8534 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8535 }
8536
8537 return 1;
8538
8539 err:
8540 return 0;
8541 }
8542
8543 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8544 {
8545 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8546 &cpu_rq(cpu)->leaf_rt_rq_list);
8547 }
8548
8549 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8550 {
8551 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8552 }
8553 #else
8554 static inline void free_rt_sched_group(struct task_group *tg)
8555 {
8556 }
8557
8558 static inline
8559 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8560 {
8561 return 1;
8562 }
8563
8564 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8565 {
8566 }
8567
8568 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8569 {
8570 }
8571 #endif
8572
8573 #ifdef CONFIG_GROUP_SCHED
8574 static void free_sched_group(struct task_group *tg)
8575 {
8576 free_fair_sched_group(tg);
8577 free_rt_sched_group(tg);
8578 kfree(tg);
8579 }
8580
8581 /* allocate runqueue etc for a new task group */
8582 struct task_group *sched_create_group(struct task_group *parent)
8583 {
8584 struct task_group *tg;
8585 unsigned long flags;
8586 int i;
8587
8588 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8589 if (!tg)
8590 return ERR_PTR(-ENOMEM);
8591
8592 if (!alloc_fair_sched_group(tg, parent))
8593 goto err;
8594
8595 if (!alloc_rt_sched_group(tg, parent))
8596 goto err;
8597
8598 spin_lock_irqsave(&task_group_lock, flags);
8599 for_each_possible_cpu(i) {
8600 register_fair_sched_group(tg, i);
8601 register_rt_sched_group(tg, i);
8602 }
8603 list_add_rcu(&tg->list, &task_groups);
8604
8605 WARN_ON(!parent); /* root should already exist */
8606
8607 tg->parent = parent;
8608 list_add_rcu(&tg->siblings, &parent->children);
8609 INIT_LIST_HEAD(&tg->children);
8610 spin_unlock_irqrestore(&task_group_lock, flags);
8611
8612 return tg;
8613
8614 err:
8615 free_sched_group(tg);
8616 return ERR_PTR(-ENOMEM);
8617 }
8618
8619 /* rcu callback to free various structures associated with a task group */
8620 static void free_sched_group_rcu(struct rcu_head *rhp)
8621 {
8622 /* now it should be safe to free those cfs_rqs */
8623 free_sched_group(container_of(rhp, struct task_group, rcu));
8624 }
8625
8626 /* Destroy runqueue etc associated with a task group */
8627 void sched_destroy_group(struct task_group *tg)
8628 {
8629 unsigned long flags;
8630 int i;
8631
8632 spin_lock_irqsave(&task_group_lock, flags);
8633 for_each_possible_cpu(i) {
8634 unregister_fair_sched_group(tg, i);
8635 unregister_rt_sched_group(tg, i);
8636 }
8637 list_del_rcu(&tg->list);
8638 list_del_rcu(&tg->siblings);
8639 spin_unlock_irqrestore(&task_group_lock, flags);
8640
8641 /* wait for possible concurrent references to cfs_rqs complete */
8642 call_rcu(&tg->rcu, free_sched_group_rcu);
8643 }
8644
8645 /* change task's runqueue when it moves between groups.
8646 * The caller of this function should have put the task in its new group
8647 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8648 * reflect its new group.
8649 */
8650 void sched_move_task(struct task_struct *tsk)
8651 {
8652 int on_rq, running;
8653 unsigned long flags;
8654 struct rq *rq;
8655
8656 rq = task_rq_lock(tsk, &flags);
8657
8658 update_rq_clock(rq);
8659
8660 running = task_current(rq, tsk);
8661 on_rq = tsk->se.on_rq;
8662
8663 if (on_rq)
8664 dequeue_task(rq, tsk, 0);
8665 if (unlikely(running))
8666 tsk->sched_class->put_prev_task(rq, tsk);
8667
8668 set_task_rq(tsk, task_cpu(tsk));
8669
8670 #ifdef CONFIG_FAIR_GROUP_SCHED
8671 if (tsk->sched_class->moved_group)
8672 tsk->sched_class->moved_group(tsk);
8673 #endif
8674
8675 if (unlikely(running))
8676 tsk->sched_class->set_curr_task(rq);
8677 if (on_rq)
8678 enqueue_task(rq, tsk, 0);
8679
8680 task_rq_unlock(rq, &flags);
8681 }
8682 #endif
8683
8684 #ifdef CONFIG_FAIR_GROUP_SCHED
8685 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8686 {
8687 struct cfs_rq *cfs_rq = se->cfs_rq;
8688 int on_rq;
8689
8690 on_rq = se->on_rq;
8691 if (on_rq)
8692 dequeue_entity(cfs_rq, se, 0);
8693
8694 se->load.weight = shares;
8695 se->load.inv_weight = 0;
8696
8697 if (on_rq)
8698 enqueue_entity(cfs_rq, se, 0);
8699 }
8700
8701 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8702 {
8703 struct cfs_rq *cfs_rq = se->cfs_rq;
8704 struct rq *rq = cfs_rq->rq;
8705 unsigned long flags;
8706
8707 spin_lock_irqsave(&rq->lock, flags);
8708 __set_se_shares(se, shares);
8709 spin_unlock_irqrestore(&rq->lock, flags);
8710 }
8711
8712 static DEFINE_MUTEX(shares_mutex);
8713
8714 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8715 {
8716 int i;
8717 unsigned long flags;
8718
8719 /*
8720 * We can't change the weight of the root cgroup.
8721 */
8722 if (!tg->se[0])
8723 return -EINVAL;
8724
8725 if (shares < MIN_SHARES)
8726 shares = MIN_SHARES;
8727 else if (shares > MAX_SHARES)
8728 shares = MAX_SHARES;
8729
8730 mutex_lock(&shares_mutex);
8731 if (tg->shares == shares)
8732 goto done;
8733
8734 spin_lock_irqsave(&task_group_lock, flags);
8735 for_each_possible_cpu(i)
8736 unregister_fair_sched_group(tg, i);
8737 list_del_rcu(&tg->siblings);
8738 spin_unlock_irqrestore(&task_group_lock, flags);
8739
8740 /* wait for any ongoing reference to this group to finish */
8741 synchronize_sched();
8742
8743 /*
8744 * Now we are free to modify the group's share on each cpu
8745 * w/o tripping rebalance_share or load_balance_fair.
8746 */
8747 tg->shares = shares;
8748 for_each_possible_cpu(i) {
8749 /*
8750 * force a rebalance
8751 */
8752 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8753 set_se_shares(tg->se[i], shares);
8754 }
8755
8756 /*
8757 * Enable load balance activity on this group, by inserting it back on
8758 * each cpu's rq->leaf_cfs_rq_list.
8759 */
8760 spin_lock_irqsave(&task_group_lock, flags);
8761 for_each_possible_cpu(i)
8762 register_fair_sched_group(tg, i);
8763 list_add_rcu(&tg->siblings, &tg->parent->children);
8764 spin_unlock_irqrestore(&task_group_lock, flags);
8765 done:
8766 mutex_unlock(&shares_mutex);
8767 return 0;
8768 }
8769
8770 unsigned long sched_group_shares(struct task_group *tg)
8771 {
8772 return tg->shares;
8773 }
8774 #endif
8775
8776 #ifdef CONFIG_RT_GROUP_SCHED
8777 /*
8778 * Ensure that the real time constraints are schedulable.
8779 */
8780 static DEFINE_MUTEX(rt_constraints_mutex);
8781
8782 static unsigned long to_ratio(u64 period, u64 runtime)
8783 {
8784 if (runtime == RUNTIME_INF)
8785 return 1ULL << 16;
8786
8787 return div64_u64(runtime << 16, period);
8788 }
8789
8790 #ifdef CONFIG_CGROUP_SCHED
8791 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8792 {
8793 struct task_group *tgi, *parent = tg->parent;
8794 unsigned long total = 0;
8795
8796 if (!parent) {
8797 if (global_rt_period() < period)
8798 return 0;
8799
8800 return to_ratio(period, runtime) <
8801 to_ratio(global_rt_period(), global_rt_runtime());
8802 }
8803
8804 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8805 return 0;
8806
8807 rcu_read_lock();
8808 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8809 if (tgi == tg)
8810 continue;
8811
8812 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8813 tgi->rt_bandwidth.rt_runtime);
8814 }
8815 rcu_read_unlock();
8816
8817 return total + to_ratio(period, runtime) <
8818 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8819 parent->rt_bandwidth.rt_runtime);
8820 }
8821 #elif defined CONFIG_USER_SCHED
8822 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8823 {
8824 struct task_group *tgi;
8825 unsigned long total = 0;
8826 unsigned long global_ratio =
8827 to_ratio(global_rt_period(), global_rt_runtime());
8828
8829 rcu_read_lock();
8830 list_for_each_entry_rcu(tgi, &task_groups, list) {
8831 if (tgi == tg)
8832 continue;
8833
8834 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8835 tgi->rt_bandwidth.rt_runtime);
8836 }
8837 rcu_read_unlock();
8838
8839 return total + to_ratio(period, runtime) < global_ratio;
8840 }
8841 #endif
8842
8843 /* Must be called with tasklist_lock held */
8844 static inline int tg_has_rt_tasks(struct task_group *tg)
8845 {
8846 struct task_struct *g, *p;
8847 do_each_thread(g, p) {
8848 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8849 return 1;
8850 } while_each_thread(g, p);
8851 return 0;
8852 }
8853
8854 static int tg_set_bandwidth(struct task_group *tg,
8855 u64 rt_period, u64 rt_runtime)
8856 {
8857 int i, err = 0;
8858
8859 mutex_lock(&rt_constraints_mutex);
8860 read_lock(&tasklist_lock);
8861 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8862 err = -EBUSY;
8863 goto unlock;
8864 }
8865 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8866 err = -EINVAL;
8867 goto unlock;
8868 }
8869
8870 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8871 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8872 tg->rt_bandwidth.rt_runtime = rt_runtime;
8873
8874 for_each_possible_cpu(i) {
8875 struct rt_rq *rt_rq = tg->rt_rq[i];
8876
8877 spin_lock(&rt_rq->rt_runtime_lock);
8878 rt_rq->rt_runtime = rt_runtime;
8879 spin_unlock(&rt_rq->rt_runtime_lock);
8880 }
8881 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8882 unlock:
8883 read_unlock(&tasklist_lock);
8884 mutex_unlock(&rt_constraints_mutex);
8885
8886 return err;
8887 }
8888
8889 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8890 {
8891 u64 rt_runtime, rt_period;
8892
8893 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8894 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8895 if (rt_runtime_us < 0)
8896 rt_runtime = RUNTIME_INF;
8897
8898 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8899 }
8900
8901 long sched_group_rt_runtime(struct task_group *tg)
8902 {
8903 u64 rt_runtime_us;
8904
8905 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8906 return -1;
8907
8908 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8909 do_div(rt_runtime_us, NSEC_PER_USEC);
8910 return rt_runtime_us;
8911 }
8912
8913 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8914 {
8915 u64 rt_runtime, rt_period;
8916
8917 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8918 rt_runtime = tg->rt_bandwidth.rt_runtime;
8919
8920 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8921 }
8922
8923 long sched_group_rt_period(struct task_group *tg)
8924 {
8925 u64 rt_period_us;
8926
8927 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8928 do_div(rt_period_us, NSEC_PER_USEC);
8929 return rt_period_us;
8930 }
8931
8932 static int sched_rt_global_constraints(void)
8933 {
8934 int ret = 0;
8935
8936 mutex_lock(&rt_constraints_mutex);
8937 if (!__rt_schedulable(NULL, 1, 0))
8938 ret = -EINVAL;
8939 mutex_unlock(&rt_constraints_mutex);
8940
8941 return ret;
8942 }
8943 #else
8944 static int sched_rt_global_constraints(void)
8945 {
8946 unsigned long flags;
8947 int i;
8948
8949 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8950 for_each_possible_cpu(i) {
8951 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8952
8953 spin_lock(&rt_rq->rt_runtime_lock);
8954 rt_rq->rt_runtime = global_rt_runtime();
8955 spin_unlock(&rt_rq->rt_runtime_lock);
8956 }
8957 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8958
8959 return 0;
8960 }
8961 #endif
8962
8963 int sched_rt_handler(struct ctl_table *table, int write,
8964 struct file *filp, void __user *buffer, size_t *lenp,
8965 loff_t *ppos)
8966 {
8967 int ret;
8968 int old_period, old_runtime;
8969 static DEFINE_MUTEX(mutex);
8970
8971 mutex_lock(&mutex);
8972 old_period = sysctl_sched_rt_period;
8973 old_runtime = sysctl_sched_rt_runtime;
8974
8975 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8976
8977 if (!ret && write) {
8978 ret = sched_rt_global_constraints();
8979 if (ret) {
8980 sysctl_sched_rt_period = old_period;
8981 sysctl_sched_rt_runtime = old_runtime;
8982 } else {
8983 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8984 def_rt_bandwidth.rt_period =
8985 ns_to_ktime(global_rt_period());
8986 }
8987 }
8988 mutex_unlock(&mutex);
8989
8990 return ret;
8991 }
8992
8993 #ifdef CONFIG_CGROUP_SCHED
8994
8995 /* return corresponding task_group object of a cgroup */
8996 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8997 {
8998 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8999 struct task_group, css);
9000 }
9001
9002 static struct cgroup_subsys_state *
9003 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9004 {
9005 struct task_group *tg, *parent;
9006
9007 if (!cgrp->parent) {
9008 /* This is early initialization for the top cgroup */
9009 init_task_group.css.cgroup = cgrp;
9010 return &init_task_group.css;
9011 }
9012
9013 parent = cgroup_tg(cgrp->parent);
9014 tg = sched_create_group(parent);
9015 if (IS_ERR(tg))
9016 return ERR_PTR(-ENOMEM);
9017
9018 /* Bind the cgroup to task_group object we just created */
9019 tg->css.cgroup = cgrp;
9020
9021 return &tg->css;
9022 }
9023
9024 static void
9025 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9026 {
9027 struct task_group *tg = cgroup_tg(cgrp);
9028
9029 sched_destroy_group(tg);
9030 }
9031
9032 static int
9033 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9034 struct task_struct *tsk)
9035 {
9036 #ifdef CONFIG_RT_GROUP_SCHED
9037 /* Don't accept realtime tasks when there is no way for them to run */
9038 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9039 return -EINVAL;
9040 #else
9041 /* We don't support RT-tasks being in separate groups */
9042 if (tsk->sched_class != &fair_sched_class)
9043 return -EINVAL;
9044 #endif
9045
9046 return 0;
9047 }
9048
9049 static void
9050 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9051 struct cgroup *old_cont, struct task_struct *tsk)
9052 {
9053 sched_move_task(tsk);
9054 }
9055
9056 #ifdef CONFIG_FAIR_GROUP_SCHED
9057 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9058 u64 shareval)
9059 {
9060 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9061 }
9062
9063 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9064 {
9065 struct task_group *tg = cgroup_tg(cgrp);
9066
9067 return (u64) tg->shares;
9068 }
9069 #endif
9070
9071 #ifdef CONFIG_RT_GROUP_SCHED
9072 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9073 s64 val)
9074 {
9075 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9076 }
9077
9078 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9079 {
9080 return sched_group_rt_runtime(cgroup_tg(cgrp));
9081 }
9082
9083 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9084 u64 rt_period_us)
9085 {
9086 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9087 }
9088
9089 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9090 {
9091 return sched_group_rt_period(cgroup_tg(cgrp));
9092 }
9093 #endif
9094
9095 static struct cftype cpu_files[] = {
9096 #ifdef CONFIG_FAIR_GROUP_SCHED
9097 {
9098 .name = "shares",
9099 .read_u64 = cpu_shares_read_u64,
9100 .write_u64 = cpu_shares_write_u64,
9101 },
9102 #endif
9103 #ifdef CONFIG_RT_GROUP_SCHED
9104 {
9105 .name = "rt_runtime_us",
9106 .read_s64 = cpu_rt_runtime_read,
9107 .write_s64 = cpu_rt_runtime_write,
9108 },
9109 {
9110 .name = "rt_period_us",
9111 .read_u64 = cpu_rt_period_read_uint,
9112 .write_u64 = cpu_rt_period_write_uint,
9113 },
9114 #endif
9115 };
9116
9117 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9118 {
9119 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9120 }
9121
9122 struct cgroup_subsys cpu_cgroup_subsys = {
9123 .name = "cpu",
9124 .create = cpu_cgroup_create,
9125 .destroy = cpu_cgroup_destroy,
9126 .can_attach = cpu_cgroup_can_attach,
9127 .attach = cpu_cgroup_attach,
9128 .populate = cpu_cgroup_populate,
9129 .subsys_id = cpu_cgroup_subsys_id,
9130 .early_init = 1,
9131 };
9132
9133 #endif /* CONFIG_CGROUP_SCHED */
9134
9135 #ifdef CONFIG_CGROUP_CPUACCT
9136
9137 /*
9138 * CPU accounting code for task groups.
9139 *
9140 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9141 * (balbir@in.ibm.com).
9142 */
9143
9144 /* track cpu usage of a group of tasks */
9145 struct cpuacct {
9146 struct cgroup_subsys_state css;
9147 /* cpuusage holds pointer to a u64-type object on every cpu */
9148 u64 *cpuusage;
9149 };
9150
9151 struct cgroup_subsys cpuacct_subsys;
9152
9153 /* return cpu accounting group corresponding to this container */
9154 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9155 {
9156 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9157 struct cpuacct, css);
9158 }
9159
9160 /* return cpu accounting group to which this task belongs */
9161 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9162 {
9163 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9164 struct cpuacct, css);
9165 }
9166
9167 /* create a new cpu accounting group */
9168 static struct cgroup_subsys_state *cpuacct_create(
9169 struct cgroup_subsys *ss, struct cgroup *cgrp)
9170 {
9171 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9172
9173 if (!ca)
9174 return ERR_PTR(-ENOMEM);
9175
9176 ca->cpuusage = alloc_percpu(u64);
9177 if (!ca->cpuusage) {
9178 kfree(ca);
9179 return ERR_PTR(-ENOMEM);
9180 }
9181
9182 return &ca->css;
9183 }
9184
9185 /* destroy an existing cpu accounting group */
9186 static void
9187 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9188 {
9189 struct cpuacct *ca = cgroup_ca(cgrp);
9190
9191 free_percpu(ca->cpuusage);
9192 kfree(ca);
9193 }
9194
9195 /* return total cpu usage (in nanoseconds) of a group */
9196 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9197 {
9198 struct cpuacct *ca = cgroup_ca(cgrp);
9199 u64 totalcpuusage = 0;
9200 int i;
9201
9202 for_each_possible_cpu(i) {
9203 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9204
9205 /*
9206 * Take rq->lock to make 64-bit addition safe on 32-bit
9207 * platforms.
9208 */
9209 spin_lock_irq(&cpu_rq(i)->lock);
9210 totalcpuusage += *cpuusage;
9211 spin_unlock_irq(&cpu_rq(i)->lock);
9212 }
9213
9214 return totalcpuusage;
9215 }
9216
9217 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9218 u64 reset)
9219 {
9220 struct cpuacct *ca = cgroup_ca(cgrp);
9221 int err = 0;
9222 int i;
9223
9224 if (reset) {
9225 err = -EINVAL;
9226 goto out;
9227 }
9228
9229 for_each_possible_cpu(i) {
9230 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9231
9232 spin_lock_irq(&cpu_rq(i)->lock);
9233 *cpuusage = 0;
9234 spin_unlock_irq(&cpu_rq(i)->lock);
9235 }
9236 out:
9237 return err;
9238 }
9239
9240 static struct cftype files[] = {
9241 {
9242 .name = "usage",
9243 .read_u64 = cpuusage_read,
9244 .write_u64 = cpuusage_write,
9245 },
9246 };
9247
9248 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9249 {
9250 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9251 }
9252
9253 /*
9254 * charge this task's execution time to its accounting group.
9255 *
9256 * called with rq->lock held.
9257 */
9258 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9259 {
9260 struct cpuacct *ca;
9261
9262 if (!cpuacct_subsys.active)
9263 return;
9264
9265 ca = task_ca(tsk);
9266 if (ca) {
9267 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9268
9269 *cpuusage += cputime;
9270 }
9271 }
9272
9273 struct cgroup_subsys cpuacct_subsys = {
9274 .name = "cpuacct",
9275 .create = cpuacct_create,
9276 .destroy = cpuacct_destroy,
9277 .populate = cpuacct_populate,
9278 .subsys_id = cpuacct_subsys_id,
9279 };
9280 #endif /* CONFIG_CGROUP_CPUACCT */