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