Merge tag 'v3.10.107' into update
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / kernel / sched / core.c
CommitLineData
1da177e4 1/*
391e43da 2 * kernel/sched/core.c
1da177e4
LT
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
c31f2e8a
IM
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
b9131769
IM
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
1da177e4
LT
27 */
28
29#include <linux/mm.h>
30#include <linux/module.h>
31#include <linux/nmi.h>
32#include <linux/init.h>
dff06c15 33#include <linux/uaccess.h>
1da177e4 34#include <linux/highmem.h>
1da177e4
LT
35#include <asm/mmu_context.h>
36#include <linux/interrupt.h>
c59ede7b 37#include <linux/capability.h>
1da177e4
LT
38#include <linux/completion.h>
39#include <linux/kernel_stat.h>
9a11b49a 40#include <linux/debug_locks.h>
cdd6c482 41#include <linux/perf_event.h>
1da177e4
LT
42#include <linux/security.h>
43#include <linux/notifier.h>
44#include <linux/profile.h>
7dfb7103 45#include <linux/freezer.h>
198e2f18 46#include <linux/vmalloc.h>
1da177e4
LT
47#include <linux/blkdev.h>
48#include <linux/delay.h>
b488893a 49#include <linux/pid_namespace.h>
1da177e4
LT
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>
b5aadf7f 57#include <linux/proc_fs.h>
1da177e4 58#include <linux/seq_file.h>
e692ab53 59#include <linux/sysctl.h>
1da177e4
LT
60#include <linux/syscalls.h>
61#include <linux/times.h>
8f0ab514 62#include <linux/tsacct_kern.h>
c6fd91f0 63#include <linux/kprobes.h>
0ff92245 64#include <linux/delayacct.h>
dff06c15 65#include <linux/unistd.h>
f5ff8422 66#include <linux/pagemap.h>
8f4d37ec 67#include <linux/hrtimer.h>
30914a58 68#include <linux/tick.h>
f00b45c1
PZ
69#include <linux/debugfs.h>
70#include <linux/ctype.h>
6cd8a4bb 71#include <linux/ftrace.h>
5a0e3ad6 72#include <linux/slab.h>
f1c6f1a7 73#include <linux/init_task.h>
40401530 74#include <linux/binfmts.h>
91d1aa43 75#include <linux/context_tracking.h>
1da177e4 76
96f951ed 77#include <asm/switch_to.h>
5517d86b 78#include <asm/tlb.h>
838225b4 79#include <asm/irq_regs.h>
db7e527d 80#include <asm/mutex.h>
e6e6685a
GC
81#ifdef CONFIG_PARAVIRT
82#include <asm/paravirt.h>
83#endif
1da177e4 84
029632fb 85#include "sched.h"
ea138446 86#include "../workqueue_internal.h"
29d5e047 87#include "../smpboot.h"
6e0534f2 88
6fa3eb70
S
89#ifdef CONFIG_MT65XX_TRACER
90#include "mach/mt_mon.h"
91#include "linux/aee.h"
92#endif
93
94#include <linux/mt_sched_mon.h>
a8d154b0 95#define CREATE_TRACE_POINTS
ad8d75ff 96#include <trace/events/sched.h>
a8d154b0 97
6fa3eb70
S
98#include <mtlbprof/mtlbprof.h>
99#include <mtlbprof/mtlbprof_stat.h>
100
101#ifdef CONFIG_MT_PRIO_TRACER
102# include <linux/prio_tracer.h>
103#endif
104
029632fb 105void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
d0b27fa7 106{
58088ad0
PT
107 unsigned long delta;
108 ktime_t soft, hard, now;
d0b27fa7 109
58088ad0
PT
110 for (;;) {
111 if (hrtimer_active(period_timer))
112 break;
113
114 now = hrtimer_cb_get_time(period_timer);
115 hrtimer_forward(period_timer, now, period);
d0b27fa7 116
58088ad0
PT
117 soft = hrtimer_get_softexpires(period_timer);
118 hard = hrtimer_get_expires(period_timer);
119 delta = ktime_to_ns(ktime_sub(hard, soft));
120 __hrtimer_start_range_ns(period_timer, soft, delta,
121 HRTIMER_MODE_ABS_PINNED, 0);
122 }
123}
124
029632fb
PZ
125DEFINE_MUTEX(sched_domains_mutex);
126DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 127
fe44d621 128static void update_rq_clock_task(struct rq *rq, s64 delta);
305e6835 129
029632fb 130void update_rq_clock(struct rq *rq)
3e51f33f 131{
fe44d621 132 s64 delta;
305e6835 133
61eadef6 134 if (rq->skip_clock_update > 0)
f26f9aff 135 return;
aa483808 136
fe44d621
PZ
137 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
138 rq->clock += delta;
139 update_rq_clock_task(rq, delta);
3e51f33f
PZ
140}
141
bf5c91ba
IM
142/*
143 * Debugging: various feature bits
144 */
f00b45c1 145
f00b45c1
PZ
146#define SCHED_FEAT(name, enabled) \
147 (1UL << __SCHED_FEAT_##name) * enabled |
148
bf5c91ba 149const_debug unsigned int sysctl_sched_features =
391e43da 150#include "features.h"
f00b45c1
PZ
151 0;
152
153#undef SCHED_FEAT
154
155#ifdef CONFIG_SCHED_DEBUG
156#define SCHED_FEAT(name, enabled) \
157 #name ,
158
1292531f 159static const char * const sched_feat_names[] = {
391e43da 160#include "features.h"
f00b45c1
PZ
161};
162
163#undef SCHED_FEAT
164
34f3a814 165static int sched_feat_show(struct seq_file *m, void *v)
f00b45c1 166{
f00b45c1
PZ
167 int i;
168
f8b6d1cc 169 for (i = 0; i < __SCHED_FEAT_NR; i++) {
34f3a814
LZ
170 if (!(sysctl_sched_features & (1UL << i)))
171 seq_puts(m, "NO_");
172 seq_printf(m, "%s ", sched_feat_names[i]);
f00b45c1 173 }
34f3a814 174 seq_puts(m, "\n");
f00b45c1 175
34f3a814 176 return 0;
f00b45c1
PZ
177}
178
f8b6d1cc
PZ
179#ifdef HAVE_JUMP_LABEL
180
c5905afb
IM
181#define jump_label_key__true STATIC_KEY_INIT_TRUE
182#define jump_label_key__false STATIC_KEY_INIT_FALSE
f8b6d1cc
PZ
183
184#define SCHED_FEAT(name, enabled) \
185 jump_label_key__##enabled ,
186
c5905afb 187struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
f8b6d1cc
PZ
188#include "features.h"
189};
190
191#undef SCHED_FEAT
192
193static void sched_feat_disable(int i)
194{
12f1a0f9 195 static_key_disable(&sched_feat_keys[i]);
f8b6d1cc
PZ
196}
197
198static void sched_feat_enable(int i)
199{
12f1a0f9 200 static_key_enable(&sched_feat_keys[i]);
f8b6d1cc
PZ
201}
202#else
203static void sched_feat_disable(int i) { };
204static void sched_feat_enable(int i) { };
205#endif /* HAVE_JUMP_LABEL */
206
1a687c2e 207static int sched_feat_set(char *cmp)
f00b45c1 208{
f00b45c1 209 int i;
1a687c2e 210 int neg = 0;
f00b45c1 211
524429c3 212 if (strncmp(cmp, "NO_", 3) == 0) {
f00b45c1
PZ
213 neg = 1;
214 cmp += 3;
215 }
216
f8b6d1cc 217 for (i = 0; i < __SCHED_FEAT_NR; i++) {
7740191c 218 if (strcmp(cmp, sched_feat_names[i]) == 0) {
f8b6d1cc 219 if (neg) {
f00b45c1 220 sysctl_sched_features &= ~(1UL << i);
f8b6d1cc
PZ
221 sched_feat_disable(i);
222 } else {
f00b45c1 223 sysctl_sched_features |= (1UL << i);
f8b6d1cc
PZ
224 sched_feat_enable(i);
225 }
f00b45c1
PZ
226 break;
227 }
228 }
229
1a687c2e
MG
230 return i;
231}
232
233static ssize_t
234sched_feat_write(struct file *filp, const char __user *ubuf,
235 size_t cnt, loff_t *ppos)
236{
237 char buf[64];
238 char *cmp;
239 int i;
240
241 if (cnt > 63)
242 cnt = 63;
243
244 if (copy_from_user(&buf, ubuf, cnt))
245 return -EFAULT;
246
247 buf[cnt] = 0;
248 cmp = strstrip(buf);
249
250 i = sched_feat_set(cmp);
f8b6d1cc 251 if (i == __SCHED_FEAT_NR)
f00b45c1
PZ
252 return -EINVAL;
253
42994724 254 *ppos += cnt;
f00b45c1
PZ
255
256 return cnt;
257}
258
34f3a814
LZ
259static int sched_feat_open(struct inode *inode, struct file *filp)
260{
261 return single_open(filp, sched_feat_show, NULL);
262}
263
828c0950 264static const struct file_operations sched_feat_fops = {
34f3a814
LZ
265 .open = sched_feat_open,
266 .write = sched_feat_write,
267 .read = seq_read,
268 .llseek = seq_lseek,
269 .release = single_release,
f00b45c1
PZ
270};
271
272static __init int sched_init_debug(void)
273{
f00b45c1
PZ
274 debugfs_create_file("sched_features", 0644, NULL, NULL,
275 &sched_feat_fops);
276
277 return 0;
278}
279late_initcall(sched_init_debug);
f8b6d1cc 280#endif /* CONFIG_SCHED_DEBUG */
bf5c91ba 281
b82d9fdd
PZ
282/*
283 * Number of tasks to iterate in a single balance run.
284 * Limited because this is done with IRQs disabled.
285 */
286const_debug unsigned int sysctl_sched_nr_migrate = 32;
287
e9e9250b
PZ
288/*
289 * period over which we average the RT time consumption, measured
290 * in ms.
291 *
292 * default: 1s
293 */
294const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
295
fa85ae24 296/*
9f0c1e56 297 * period over which we measure -rt task cpu usage in us.
fa85ae24
PZ
298 * default: 1s
299 */
9f0c1e56 300unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 301
029632fb 302__read_mostly int scheduler_running;
6892b75e 303
9f0c1e56
PZ
304/*
305 * part of the period that we allow rt tasks to run in us.
306 * default: 0.95s
307 */
308int sysctl_sched_rt_runtime = 950000;
fa85ae24 309
fa85ae24 310
1da177e4 311
0970d299 312/*
0122ec5b 313 * __task_rq_lock - lock the rq @p resides on.
b29739f9 314 */
70b97a7f 315static inline struct rq *__task_rq_lock(struct task_struct *p)
b29739f9
IM
316 __acquires(rq->lock)
317{
0970d299
PZ
318 struct rq *rq;
319
0122ec5b
PZ
320 lockdep_assert_held(&p->pi_lock);
321
3a5c359a 322 for (;;) {
0970d299 323 rq = task_rq(p);
05fa785c 324 raw_spin_lock(&rq->lock);
65cc8e48 325 if (likely(rq == task_rq(p)))
3a5c359a 326 return rq;
05fa785c 327 raw_spin_unlock(&rq->lock);
b29739f9 328 }
b29739f9
IM
329}
330
1da177e4 331/*
0122ec5b 332 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
1da177e4 333 */
70b97a7f 334static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
0122ec5b 335 __acquires(p->pi_lock)
1da177e4
LT
336 __acquires(rq->lock)
337{
70b97a7f 338 struct rq *rq;
1da177e4 339
3a5c359a 340 for (;;) {
0122ec5b 341 raw_spin_lock_irqsave(&p->pi_lock, *flags);
3a5c359a 342 rq = task_rq(p);
05fa785c 343 raw_spin_lock(&rq->lock);
65cc8e48 344 if (likely(rq == task_rq(p)))
3a5c359a 345 return rq;
0122ec5b
PZ
346 raw_spin_unlock(&rq->lock);
347 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
1da177e4 348 }
1da177e4
LT
349}
350
a9957449 351static void __task_rq_unlock(struct rq *rq)
b29739f9
IM
352 __releases(rq->lock)
353{
05fa785c 354 raw_spin_unlock(&rq->lock);
b29739f9
IM
355}
356
0122ec5b
PZ
357static inline void
358task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
1da177e4 359 __releases(rq->lock)
0122ec5b 360 __releases(p->pi_lock)
1da177e4 361{
0122ec5b
PZ
362 raw_spin_unlock(&rq->lock);
363 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
1da177e4
LT
364}
365
1da177e4 366/*
cc2a73b5 367 * this_rq_lock - lock this runqueue and disable interrupts.
1da177e4 368 */
a9957449 369static struct rq *this_rq_lock(void)
1da177e4
LT
370 __acquires(rq->lock)
371{
70b97a7f 372 struct rq *rq;
1da177e4
LT
373
374 local_irq_disable();
375 rq = this_rq();
05fa785c 376 raw_spin_lock(&rq->lock);
1da177e4
LT
377
378 return rq;
379}
380
8f4d37ec
PZ
381#ifdef CONFIG_SCHED_HRTICK
382/*
383 * Use HR-timers to deliver accurate preemption points.
384 *
385 * Its all a bit involved since we cannot program an hrt while holding the
386 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
387 * reschedule event.
388 *
389 * When we get rescheduled we reprogram the hrtick_timer outside of the
390 * rq->lock.
391 */
8f4d37ec 392
8f4d37ec
PZ
393static void hrtick_clear(struct rq *rq)
394{
395 if (hrtimer_active(&rq->hrtick_timer))
396 hrtimer_cancel(&rq->hrtick_timer);
397}
398
8f4d37ec
PZ
399/*
400 * High-resolution timer tick.
401 * Runs from hardirq context with interrupts disabled.
402 */
403static enum hrtimer_restart hrtick(struct hrtimer *timer)
404{
405 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
406
407 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
408
05fa785c 409 raw_spin_lock(&rq->lock);
3e51f33f 410 update_rq_clock(rq);
8f4d37ec 411 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
05fa785c 412 raw_spin_unlock(&rq->lock);
8f4d37ec
PZ
413
414 return HRTIMER_NORESTART;
415}
416
95e904c7 417#ifdef CONFIG_SMP
31656519
PZ
418/*
419 * called from hardirq (IPI) context
420 */
421static void __hrtick_start(void *arg)
b328ca18 422{
31656519 423 struct rq *rq = arg;
b328ca18 424
05fa785c 425 raw_spin_lock(&rq->lock);
31656519
PZ
426 hrtimer_restart(&rq->hrtick_timer);
427 rq->hrtick_csd_pending = 0;
05fa785c 428 raw_spin_unlock(&rq->lock);
b328ca18
PZ
429}
430
31656519
PZ
431/*
432 * Called to set the hrtick timer state.
433 *
434 * called with rq->lock held and irqs disabled
435 */
029632fb 436void hrtick_start(struct rq *rq, u64 delay)
b328ca18 437{
31656519
PZ
438 struct hrtimer *timer = &rq->hrtick_timer;
439 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
b328ca18 440
cc584b21 441 hrtimer_set_expires(timer, time);
31656519
PZ
442
443 if (rq == this_rq()) {
444 hrtimer_restart(timer);
445 } else if (!rq->hrtick_csd_pending) {
6e275637 446 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
31656519
PZ
447 rq->hrtick_csd_pending = 1;
448 }
b328ca18
PZ
449}
450
451static int
452hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
453{
454 int cpu = (int)(long)hcpu;
455
456 switch (action) {
457 case CPU_UP_CANCELED:
458 case CPU_UP_CANCELED_FROZEN:
459 case CPU_DOWN_PREPARE:
460 case CPU_DOWN_PREPARE_FROZEN:
461 case CPU_DEAD:
462 case CPU_DEAD_FROZEN:
31656519 463 hrtick_clear(cpu_rq(cpu));
b328ca18
PZ
464 return NOTIFY_OK;
465 }
466
467 return NOTIFY_DONE;
468}
469
fa748203 470static __init void init_hrtick(void)
b328ca18
PZ
471{
472 hotcpu_notifier(hotplug_hrtick, 0);
473}
31656519
PZ
474#else
475/*
476 * Called to set the hrtick timer state.
477 *
478 * called with rq->lock held and irqs disabled
479 */
029632fb 480void hrtick_start(struct rq *rq, u64 delay)
31656519 481{
7f1e2ca9 482 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
5c333864 483 HRTIMER_MODE_REL_PINNED, 0);
31656519 484}
b328ca18 485
006c75f1 486static inline void init_hrtick(void)
8f4d37ec 487{
8f4d37ec 488}
31656519 489#endif /* CONFIG_SMP */
8f4d37ec 490
31656519 491static void init_rq_hrtick(struct rq *rq)
8f4d37ec 492{
31656519
PZ
493#ifdef CONFIG_SMP
494 rq->hrtick_csd_pending = 0;
8f4d37ec 495
31656519
PZ
496 rq->hrtick_csd.flags = 0;
497 rq->hrtick_csd.func = __hrtick_start;
498 rq->hrtick_csd.info = rq;
499#endif
8f4d37ec 500
31656519
PZ
501 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
502 rq->hrtick_timer.function = hrtick;
8f4d37ec 503}
006c75f1 504#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
505static inline void hrtick_clear(struct rq *rq)
506{
507}
508
8f4d37ec
PZ
509static inline void init_rq_hrtick(struct rq *rq)
510{
511}
512
b328ca18
PZ
513static inline void init_hrtick(void)
514{
515}
006c75f1 516#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 517
c24d20db
IM
518/*
519 * resched_task - mark a task 'to be rescheduled now'.
520 *
521 * On UP this means the setting of the need_resched flag, on SMP it
522 * might also involve a cross-CPU call to trigger the scheduler on
523 * the target CPU.
524 */
525#ifdef CONFIG_SMP
029632fb 526void resched_task(struct task_struct *p)
c24d20db
IM
527{
528 int cpu;
529
05fa785c 530 assert_raw_spin_locked(&task_rq(p)->lock);
c24d20db 531
5ed0cec0 532 if (test_tsk_need_resched(p))
c24d20db
IM
533 return;
534
5ed0cec0 535 set_tsk_need_resched(p);
c24d20db
IM
536
537 cpu = task_cpu(p);
538 if (cpu == smp_processor_id())
539 return;
540
541 /* NEED_RESCHED must be visible before we test polling */
542 smp_mb();
543 if (!tsk_is_polling(p))
544 smp_send_reschedule(cpu);
545}
546
029632fb 547void resched_cpu(int cpu)
c24d20db
IM
548{
549 struct rq *rq = cpu_rq(cpu);
550 unsigned long flags;
551
05fa785c 552 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
c24d20db
IM
553 return;
554 resched_task(cpu_curr(cpu));
05fa785c 555 raw_spin_unlock_irqrestore(&rq->lock, flags);
c24d20db 556}
06d8308c 557
3451d024 558#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2
VP
559/*
560 * In the semi idle case, use the nearest busy cpu for migrating timers
561 * from an idle cpu. This is good for power-savings.
562 *
563 * We don't do similar optimization for completely idle system, as
564 * selecting an idle cpu will add more delays to the timers than intended
565 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
566 */
567int get_nohz_timer_target(void)
568{
569 int cpu = smp_processor_id();
570 int i;
571 struct sched_domain *sd;
572
057f3fad 573 rcu_read_lock();
83cd4fe2 574 for_each_domain(cpu, sd) {
057f3fad
PZ
575 for_each_cpu(i, sched_domain_span(sd)) {
576 if (!idle_cpu(i)) {
577 cpu = i;
578 goto unlock;
579 }
580 }
83cd4fe2 581 }
057f3fad
PZ
582unlock:
583 rcu_read_unlock();
83cd4fe2
VP
584 return cpu;
585}
06d8308c
TG
586/*
587 * When add_timer_on() enqueues a timer into the timer wheel of an
588 * idle CPU then this timer might expire before the next timer event
589 * which is scheduled to wake up that CPU. In case of a completely
590 * idle system the next event might even be infinite time into the
591 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
592 * leaves the inner idle loop so the newly added timer is taken into
593 * account when the CPU goes back to idle and evaluates the timer
594 * wheel for the next timer event.
595 */
1c20091e 596static void wake_up_idle_cpu(int cpu)
06d8308c
TG
597{
598 struct rq *rq = cpu_rq(cpu);
599
600 if (cpu == smp_processor_id())
601 return;
602
603 /*
604 * This is safe, as this function is called with the timer
605 * wheel base lock of (cpu) held. When the CPU is on the way
606 * to idle and has not yet set rq->curr to idle then it will
607 * be serialized on the timer wheel base lock and take the new
608 * timer into account automatically.
609 */
610 if (rq->curr != rq->idle)
611 return;
45bf76df 612
45bf76df 613 /*
06d8308c
TG
614 * We can set TIF_RESCHED on the idle task of the other CPU
615 * lockless. The worst case is that the other CPU runs the
616 * idle task through an additional NOOP schedule()
45bf76df 617 */
5ed0cec0 618 set_tsk_need_resched(rq->idle);
45bf76df 619
06d8308c
TG
620 /* NEED_RESCHED must be visible before we test polling */
621 smp_mb();
622 if (!tsk_is_polling(rq->idle))
623 smp_send_reschedule(cpu);
45bf76df
IM
624}
625
c5bfece2 626static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 627{
c5bfece2 628 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
629 if (cpu != smp_processor_id() ||
630 tick_nohz_tick_stopped())
631 smp_send_reschedule(cpu);
632 return true;
633 }
634
635 return false;
636}
637
638void wake_up_nohz_cpu(int cpu)
639{
c5bfece2 640 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
641 wake_up_idle_cpu(cpu);
642}
643
ca38062e 644static inline bool got_nohz_idle_kick(void)
45bf76df 645{
1c792db7 646 int cpu = smp_processor_id();
873b4c65
VG
647
648 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
649 return false;
650
651 if (idle_cpu(cpu) && !need_resched())
652 return true;
653
654 /*
655 * We can't run Idle Load Balance on this CPU for this time so we
656 * cancel it and clear NOHZ_BALANCE_KICK
657 */
658 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
659 return false;
45bf76df
IM
660}
661
3451d024 662#else /* CONFIG_NO_HZ_COMMON */
45bf76df 663
ca38062e 664static inline bool got_nohz_idle_kick(void)
2069dd75 665{
ca38062e 666 return false;
2069dd75
PZ
667}
668
3451d024 669#endif /* CONFIG_NO_HZ_COMMON */
d842de87 670
ce831b38
FW
671#ifdef CONFIG_NO_HZ_FULL
672bool sched_can_stop_tick(void)
673{
674 struct rq *rq;
675
676 rq = this_rq();
677
678 /* Make sure rq->nr_running update is visible after the IPI */
679 smp_rmb();
680
681 /* More than one running task need preemption */
682 if (rq->nr_running > 1)
683 return false;
684
685 return true;
686}
687#endif /* CONFIG_NO_HZ_FULL */
d842de87 688
029632fb 689void sched_avg_update(struct rq *rq)
18d95a28 690{
e9e9250b
PZ
691 s64 period = sched_avg_period();
692
693 while ((s64)(rq->clock - rq->age_stamp) > period) {
0d98bb26
WD
694 /*
695 * Inline assembly required to prevent the compiler
696 * optimising this loop into a divmod call.
697 * See __iter_div_u64_rem() for another example of this.
698 */
699 asm("" : "+rm" (rq->age_stamp));
e9e9250b
PZ
700 rq->age_stamp += period;
701 rq->rt_avg /= 2;
702 }
18d95a28
PZ
703}
704
6d6bc0ad 705#else /* !CONFIG_SMP */
029632fb 706void resched_task(struct task_struct *p)
18d95a28 707{
05fa785c 708 assert_raw_spin_locked(&task_rq(p)->lock);
31656519 709 set_tsk_need_resched(p);
18d95a28 710}
6d6bc0ad 711#endif /* CONFIG_SMP */
18d95a28 712
a790de99
PT
713#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
714 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 715/*
8277434e
PT
716 * Iterate task_group tree rooted at *from, calling @down when first entering a
717 * node and @up when leaving it for the final time.
718 *
719 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 720 */
029632fb 721int walk_tg_tree_from(struct task_group *from,
8277434e 722 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
723{
724 struct task_group *parent, *child;
eb755805 725 int ret;
c09595f6 726
8277434e
PT
727 parent = from;
728
c09595f6 729down:
eb755805
PZ
730 ret = (*down)(parent, data);
731 if (ret)
8277434e 732 goto out;
c09595f6
PZ
733 list_for_each_entry_rcu(child, &parent->children, siblings) {
734 parent = child;
735 goto down;
736
737up:
738 continue;
739 }
eb755805 740 ret = (*up)(parent, data);
8277434e
PT
741 if (ret || parent == from)
742 goto out;
c09595f6
PZ
743
744 child = parent;
745 parent = parent->parent;
746 if (parent)
747 goto up;
8277434e 748out:
eb755805 749 return ret;
c09595f6
PZ
750}
751
029632fb 752int tg_nop(struct task_group *tg, void *data)
eb755805 753{
e2b245f8 754 return 0;
eb755805 755}
18d95a28
PZ
756#endif
757
45bf76df
IM
758static void set_load_weight(struct task_struct *p)
759{
f05998d4
NR
760 int prio = p->static_prio - MAX_RT_PRIO;
761 struct load_weight *load = &p->se.load;
762
dd41f596
IM
763 /*
764 * SCHED_IDLE tasks get minimal weight:
765 */
766 if (p->policy == SCHED_IDLE) {
c8b28116 767 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 768 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
769 return;
770 }
71f8bd46 771
c8b28116 772 load->weight = scale_load(prio_to_weight[prio]);
f05998d4 773 load->inv_weight = prio_to_wmult[prio];
71f8bd46
IM
774}
775
6fa3eb70
S
776#ifdef CONFIG_MTK_SCHED_CMP_TGS
777static void sched_tg_enqueue(struct rq *rq, struct task_struct *p)
778{
779 int id;
780 unsigned long flags;
781 struct task_struct *tg = p->group_leader;
782
783 if(group_leader_is_empty(p))
784 return;
785 id = get_cluster_id(rq->cpu);
786 if (unlikely(WARN_ON(id < 0)))
787 return;
788
789 raw_spin_lock_irqsave(&tg->thread_group_info_lock, flags);
790 tg->thread_group_info[id].nr_running++;
791 raw_spin_unlock_irqrestore(&tg->thread_group_info_lock, flags);
792
793#if 0
794 mt_sched_printf("enqueue %d:%s %d:%s %d %lu %lu %lu, %lu %lu %lu",
795 tg->pid, tg->comm, p->pid, p->comm, id, rq->cpu,
796 tg->thread_group_info[0].nr_running,
797 tg->thread_group_info[0].cfs_nr_running,
798 tg->thread_group_info[0].load_avg_ratio,
799 tg->thread_group_info[1].nr_running,
800 tg->thread_group_info[1].cfs_nr_running,
801 tg->thread_group_info[1].load_avg_ratio);
802#endif
803 //tgs_log(rq, p);
804}
805
806static void sched_tg_dequeue(struct rq *rq, struct task_struct *p)
807{
808 int id;
809 unsigned long flags;
810 struct task_struct *tg = p->group_leader;
811
812 if(group_leader_is_empty(p))
813 return;
814 id = get_cluster_id(rq->cpu);
815 if (unlikely(WARN_ON(id < 0)))
816 return;
817
818 raw_spin_lock_irqsave(&tg->thread_group_info_lock, flags);
819 //WARN_ON(!tg->thread_group_info[id].nr_running);
820 tg->thread_group_info[id].nr_running--;
821 raw_spin_unlock_irqrestore(&tg->thread_group_info_lock, flags);
822
823#if 0
824 mt_sched_printf("dequeue %d:%s %d:%s %d %d %lu %lu %lu, %lu %lu %lu",
825 tg->pid, tg->comm, p->pid, p->comm, id, rq->cpu,
826 tg->thread_group_info[0].nr_running,
827 tg->thread_group_info[0].cfs_nr_running,
828 tg->thread_group_info[0].load_avg_ratio,
829 tg->thread_group_info[1].nr_running,
830 tg->thread_group_info[1].cfs_nr_running,
831 tg->thread_group_info[1].load_avg_ratio);
832#endif
833 //tgs_log(rq, p);
834}
835
836#endif
837
838#ifdef CONFIG_MTK_SCHED_CMP_TGS
839static void tgs_log(struct rq *rq, struct task_struct *p)
840{
841#ifdef CONFIG_MT_SCHED_INFO
842 struct task_struct *tg = p->group_leader;
843
844 if(group_leader_is_empty(p))
845 return;
846
847 // if(!strncmp(tg->comm,"sched_test", 10)){
848 mt_sched_printf("%d:%s %d:%s %lu %lu %lu, %lu %lu %lu", tg->pid, tg->comm, p->pid, p->comm,
849 tg->thread_group_info[0].nr_running,
850 tg->thread_group_info[0].cfs_nr_running,
851 tg->thread_group_info[0].load_avg_ratio,
852 tg->thread_group_info[1].nr_running,
853 tg->thread_group_info[1].cfs_nr_running,
854 tg->thread_group_info[1].load_avg_ratio);
855 // }
856#endif
857}
858#endif
859
371fd7e7 860static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 861{
a64692a3 862 update_rq_clock(rq);
dd41f596 863 sched_info_queued(p);
371fd7e7 864 p->sched_class->enqueue_task(rq, p, flags);
6fa3eb70
S
865#ifdef CONFIG_MTK_SCHED_CMP_TGS
866 sched_tg_enqueue(rq, p);
867 tgs_log(rq, p);
868#endif
71f8bd46
IM
869}
870
371fd7e7 871static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 872{
a64692a3 873 update_rq_clock(rq);
46ac22ba 874 sched_info_dequeued(p);
371fd7e7 875 p->sched_class->dequeue_task(rq, p, flags);
6fa3eb70
S
876#ifdef CONFIG_MTK_SCHED_CMP_TGS
877 sched_tg_dequeue(rq, p);
878 tgs_log(rq, p);
879#endif
71f8bd46
IM
880}
881
029632fb 882void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
883{
884 if (task_contributes_to_load(p))
885 rq->nr_uninterruptible--;
886
371fd7e7 887 enqueue_task(rq, p, flags);
6fa3eb70
S
888
889#ifdef CONFIG_MT_LOAD_BALANCE_PROFILER
890 if( 2 <= rq->nr_running){
891 if (1 == cpumask_weight(&p->cpus_allowed))
892 mt_lbprof_update_state_has_lock(rq->cpu, MT_LBPROF_AFFINITY_STATE);
893 else
894 mt_lbprof_update_state_has_lock(rq->cpu, MT_LBPROF_N_TASK_STATE);
895 }else if ( (1 == rq->nr_running)){
896 mt_lbprof_update_state_has_lock(rq->cpu, MT_LBPROF_ONE_TASK_STATE);
897 }
898#endif
1e3c88bd
PZ
899}
900
029632fb 901void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
902{
903 if (task_contributes_to_load(p))
904 rq->nr_uninterruptible++;
905
371fd7e7 906 dequeue_task(rq, p, flags);
6fa3eb70
S
907
908#ifdef CONFIG_MT_LOAD_BALANCE_PROFILER
909 if ( 1 == rq->nr_running )
910 mt_lbprof_update_state_has_lock(rq->cpu, MT_LBPROF_ONE_TASK_STATE);
911 else if (0 == rq->nr_running)
912 mt_lbprof_update_state_has_lock(rq->cpu, MT_LBPROF_NO_TASK_STATE);
913#endif
1e3c88bd
PZ
914}
915
fe44d621 916static void update_rq_clock_task(struct rq *rq, s64 delta)
aa483808 917{
095c0aa8
GC
918/*
919 * In theory, the compile should just see 0 here, and optimize out the call
920 * to sched_rt_avg_update. But I don't trust it...
921 */
922#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
923 s64 steal = 0, irq_delta = 0;
924#endif
925#ifdef CONFIG_IRQ_TIME_ACCOUNTING
8e92c201 926 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
fe44d621
PZ
927
928 /*
929 * Since irq_time is only updated on {soft,}irq_exit, we might run into
930 * this case when a previous update_rq_clock() happened inside a
931 * {soft,}irq region.
932 *
933 * When this happens, we stop ->clock_task and only update the
934 * prev_irq_time stamp to account for the part that fit, so that a next
935 * update will consume the rest. This ensures ->clock_task is
936 * monotonic.
937 *
938 * It does however cause some slight miss-attribution of {soft,}irq
939 * time, a more accurate solution would be to update the irq_time using
940 * the current rq->clock timestamp, except that would require using
941 * atomic ops.
942 */
943 if (irq_delta > delta)
944 irq_delta = delta;
945
946 rq->prev_irq_time += irq_delta;
947 delta -= irq_delta;
095c0aa8
GC
948#endif
949#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
c5905afb 950 if (static_key_false((&paravirt_steal_rq_enabled))) {
095c0aa8
GC
951 u64 st;
952
953 steal = paravirt_steal_clock(cpu_of(rq));
954 steal -= rq->prev_steal_time_rq;
955
956 if (unlikely(steal > delta))
957 steal = delta;
958
959 st = steal_ticks(steal);
960 steal = st * TICK_NSEC;
961
962 rq->prev_steal_time_rq += steal;
963
964 delta -= steal;
965 }
966#endif
967
fe44d621
PZ
968 rq->clock_task += delta;
969
095c0aa8
GC
970#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
971 if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
972 sched_rt_avg_update(rq, irq_delta + steal);
973#endif
aa483808
VP
974}
975
34f971f6
PZ
976void sched_set_stop_task(int cpu, struct task_struct *stop)
977{
6fa3eb70
S
978 //struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
979 struct sched_param param = { .sched_priority = RTPM_PRIO_CPU_CALLBACK };
34f971f6
PZ
980 struct task_struct *old_stop = cpu_rq(cpu)->stop;
981
982 if (stop) {
983 /*
984 * Make it appear like a SCHED_FIFO task, its something
985 * userspace knows about and won't get confused about.
986 *
987 * Also, it will make PI more or less work without too
988 * much confusion -- but then, stop work should not
989 * rely on PI working anyway.
990 */
991 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
992
993 stop->sched_class = &stop_sched_class;
994 }
995
996 cpu_rq(cpu)->stop = stop;
997
998 if (old_stop) {
999 /*
1000 * Reset it back to a normal scheduling class so that
1001 * it can die in pieces.
1002 */
1003 old_stop->sched_class = &rt_sched_class;
1004 }
1005}
1006
14531189 1007/*
dd41f596 1008 * __normal_prio - return the priority that is based on the static prio
14531189 1009 */
14531189
IM
1010static inline int __normal_prio(struct task_struct *p)
1011{
dd41f596 1012 return p->static_prio;
14531189
IM
1013}
1014
b29739f9
IM
1015/*
1016 * Calculate the expected normal priority: i.e. priority
1017 * without taking RT-inheritance into account. Might be
1018 * boosted by interactivity modifiers. Changes upon fork,
1019 * setprio syscalls, and whenever the interactivity
1020 * estimator recalculates.
1021 */
36c8b586 1022static inline int normal_prio(struct task_struct *p)
b29739f9
IM
1023{
1024 int prio;
1025
e05606d3 1026 if (task_has_rt_policy(p))
b29739f9
IM
1027 prio = MAX_RT_PRIO-1 - p->rt_priority;
1028 else
1029 prio = __normal_prio(p);
1030 return prio;
1031}
1032
1033/*
1034 * Calculate the current priority, i.e. the priority
1035 * taken into account by the scheduler. This value might
1036 * be boosted by RT tasks, or might be boosted by
1037 * interactivity modifiers. Will be RT if the task got
1038 * RT-boosted. If not then it returns p->normal_prio.
1039 */
36c8b586 1040static int effective_prio(struct task_struct *p)
b29739f9
IM
1041{
1042 p->normal_prio = normal_prio(p);
1043 /*
1044 * If we are RT tasks or we were boosted to RT priority,
1045 * keep the priority unchanged. Otherwise, update priority
1046 * to the normal priority:
1047 */
1048 if (!rt_prio(p->prio))
1049 return p->normal_prio;
1050 return p->prio;
1051}
1052
1da177e4
LT
1053/**
1054 * task_curr - is this task currently executing on a CPU?
1055 * @p: the task in question.
1056 */
36c8b586 1057inline int task_curr(const struct task_struct *p)
1da177e4
LT
1058{
1059 return cpu_curr(task_cpu(p)) == p;
1060}
1061
cb469845
SR
1062static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1063 const struct sched_class *prev_class,
da7a735e 1064 int oldprio)
cb469845
SR
1065{
1066 if (prev_class != p->sched_class) {
1067 if (prev_class->switched_from)
da7a735e
PZ
1068 prev_class->switched_from(rq, p);
1069 p->sched_class->switched_to(rq, p);
1070 } else if (oldprio != p->prio)
1071 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
1072}
1073
029632fb 1074void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405
PZ
1075{
1076 const struct sched_class *class;
1077
1078 if (p->sched_class == rq->curr->sched_class) {
1079 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1080 } else {
1081 for_each_class(class) {
1082 if (class == rq->curr->sched_class)
1083 break;
1084 if (class == p->sched_class) {
1085 resched_task(rq->curr);
1086 break;
1087 }
1088 }
1089 }
1090
1091 /*
1092 * A queue event has occurred, and we're going to schedule. In
1093 * this case, we can save a useless back to back clock update.
1094 */
fd2f4419 1095 if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
1e5a7405
PZ
1096 rq->skip_clock_update = 1;
1097}
1098
582b336e
MT
1099static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
1100
1101void register_task_migration_notifier(struct notifier_block *n)
1102{
1103 atomic_notifier_chain_register(&task_migration_notifier, n);
1104}
1105
1da177e4 1106#ifdef CONFIG_SMP
dd41f596 1107void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 1108{
e2912009
PZ
1109#ifdef CONFIG_SCHED_DEBUG
1110 /*
1111 * We should never call set_task_cpu() on a blocked task,
1112 * ttwu() will sort out the placement.
1113 */
077614ee
PZ
1114 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1115 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
0122ec5b
PZ
1116
1117#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
1118 /*
1119 * The caller should hold either p->pi_lock or rq->lock, when changing
1120 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1121 *
1122 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 1123 * see task_group().
6c6c54e1
PZ
1124 *
1125 * Furthermore, all task_rq users should acquire both locks, see
1126 * task_rq_lock().
1127 */
0122ec5b
PZ
1128 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1129 lockdep_is_held(&task_rq(p)->lock)));
1130#endif
e2912009
PZ
1131#endif
1132
de1d7286 1133 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 1134
0c69774e 1135 if (task_cpu(p) != new_cpu) {
582b336e
MT
1136 struct task_migration_notifier tmn;
1137
0a74bef8
PT
1138 if (p->sched_class->migrate_task_rq)
1139 p->sched_class->migrate_task_rq(p, new_cpu);
0c69774e 1140 p->se.nr_migrations++;
a8b0ca17 1141 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
582b336e
MT
1142
1143 tmn.task = p;
1144 tmn.from_cpu = task_cpu(p);
1145 tmn.to_cpu = new_cpu;
1146
1147 atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
0c69774e 1148 }
dd41f596
IM
1149
1150 __set_task_cpu(p, new_cpu);
c65cc870
IM
1151}
1152
969c7921 1153struct migration_arg {
36c8b586 1154 struct task_struct *task;
1da177e4 1155 int dest_cpu;
70b97a7f 1156};
1da177e4 1157
969c7921
TH
1158static int migration_cpu_stop(void *data);
1159
1da177e4
LT
1160/*
1161 * wait_task_inactive - wait for a thread to unschedule.
1162 *
85ba2d86
RM
1163 * If @match_state is nonzero, it's the @p->state value just checked and
1164 * not expected to change. If it changes, i.e. @p might have woken up,
1165 * then return zero. When we succeed in waiting for @p to be off its CPU,
1166 * we return a positive number (its total switch count). If a second call
1167 * a short while later returns the same number, the caller can be sure that
1168 * @p has remained unscheduled the whole time.
1169 *
1da177e4
LT
1170 * The caller must ensure that the task *will* unschedule sometime soon,
1171 * else this function might spin for a *long* time. This function can't
1172 * be called with interrupts off, or it may introduce deadlock with
1173 * smp_call_function() if an IPI is sent by the same process we are
1174 * waiting to become inactive.
1175 */
85ba2d86 1176unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1da177e4
LT
1177{
1178 unsigned long flags;
dd41f596 1179 int running, on_rq;
85ba2d86 1180 unsigned long ncsw;
70b97a7f 1181 struct rq *rq;
1da177e4 1182
3a5c359a
AK
1183 for (;;) {
1184 /*
1185 * We do the initial early heuristics without holding
1186 * any task-queue locks at all. We'll only try to get
1187 * the runqueue lock when things look like they will
1188 * work out!
1189 */
1190 rq = task_rq(p);
fa490cfd 1191
3a5c359a
AK
1192 /*
1193 * If the task is actively running on another CPU
1194 * still, just relax and busy-wait without holding
1195 * any locks.
1196 *
1197 * NOTE! Since we don't hold any locks, it's not
1198 * even sure that "rq" stays as the right runqueue!
1199 * But we don't care, since "task_running()" will
1200 * return false if the runqueue has changed and p
1201 * is actually now running somewhere else!
1202 */
85ba2d86
RM
1203 while (task_running(rq, p)) {
1204 if (match_state && unlikely(p->state != match_state))
1205 return 0;
3a5c359a 1206 cpu_relax();
85ba2d86 1207 }
fa490cfd 1208
3a5c359a
AK
1209 /*
1210 * Ok, time to look more closely! We need the rq
1211 * lock now, to be *sure*. If we're wrong, we'll
1212 * just go back and repeat.
1213 */
1214 rq = task_rq_lock(p, &flags);
27a9da65 1215 trace_sched_wait_task(p);
3a5c359a 1216 running = task_running(rq, p);
fd2f4419 1217 on_rq = p->on_rq;
85ba2d86 1218 ncsw = 0;
f31e11d8 1219 if (!match_state || p->state == match_state)
93dcf55f 1220 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
0122ec5b 1221 task_rq_unlock(rq, p, &flags);
fa490cfd 1222
85ba2d86
RM
1223 /*
1224 * If it changed from the expected state, bail out now.
1225 */
1226 if (unlikely(!ncsw))
1227 break;
1228
3a5c359a
AK
1229 /*
1230 * Was it really running after all now that we
1231 * checked with the proper locks actually held?
1232 *
1233 * Oops. Go back and try again..
1234 */
1235 if (unlikely(running)) {
1236 cpu_relax();
1237 continue;
1238 }
fa490cfd 1239
3a5c359a
AK
1240 /*
1241 * It's not enough that it's not actively running,
1242 * it must be off the runqueue _entirely_, and not
1243 * preempted!
1244 *
80dd99b3 1245 * So if it was still runnable (but just not actively
3a5c359a
AK
1246 * running right now), it's preempted, and we should
1247 * yield - it could be a while.
1248 */
1249 if (unlikely(on_rq)) {
8eb90c30
TG
1250 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1251
1252 set_current_state(TASK_UNINTERRUPTIBLE);
1253 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
3a5c359a
AK
1254 continue;
1255 }
fa490cfd 1256
3a5c359a
AK
1257 /*
1258 * Ahh, all good. It wasn't running, and it wasn't
1259 * runnable, which means that it will never become
1260 * running in the future either. We're all done!
1261 */
1262 break;
1263 }
85ba2d86
RM
1264
1265 return ncsw;
1da177e4
LT
1266}
1267
1268/***
1269 * kick_process - kick a running thread to enter/exit the kernel
1270 * @p: the to-be-kicked thread
1271 *
1272 * Cause a process which is running on another CPU to enter
1273 * kernel-mode, without any delay. (to get signals handled.)
1274 *
25985edc 1275 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
1276 * because all it wants to ensure is that the remote task enters
1277 * the kernel. If the IPI races and the task has been migrated
1278 * to another CPU then no harm is done and the purpose has been
1279 * achieved as well.
1280 */
36c8b586 1281void kick_process(struct task_struct *p)
1da177e4
LT
1282{
1283 int cpu;
1284
1285 preempt_disable();
1286 cpu = task_cpu(p);
1287 if ((cpu != smp_processor_id()) && task_curr(p))
1288 smp_send_reschedule(cpu);
1289 preempt_enable();
1290}
b43e3521 1291EXPORT_SYMBOL_GPL(kick_process);
476d139c 1292#endif /* CONFIG_SMP */
1da177e4 1293
970b13ba 1294#ifdef CONFIG_SMP
30da688e 1295/*
013fdb80 1296 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
30da688e 1297 */
5da9a0fb
PZ
1298static int select_fallback_rq(int cpu, struct task_struct *p)
1299{
aa00d89c
TC
1300 int nid = cpu_to_node(cpu);
1301 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
1302 enum { cpuset, possible, fail } state = cpuset;
1303 int dest_cpu;
5da9a0fb 1304
aa00d89c
TC
1305 /*
1306 * If the node that the cpu is on has been offlined, cpu_to_node()
1307 * will return -1. There is no cpu on the node, and we should
1308 * select the cpu on the other node.
1309 */
1310 if (nid != -1) {
1311 nodemask = cpumask_of_node(nid);
1312
1313 /* Look for allowed, online CPU in same node. */
1314 for_each_cpu(dest_cpu, nodemask) {
1315 if (!cpu_online(dest_cpu))
1316 continue;
1317 if (!cpu_active(dest_cpu))
1318 continue;
1319 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1320 return dest_cpu;
1321 }
2baab4e9 1322 }
5da9a0fb 1323
2baab4e9
PZ
1324 for (;;) {
1325 /* Any allowed, online CPU? */
e3831edd 1326 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
2baab4e9
PZ
1327 if (!cpu_online(dest_cpu))
1328 continue;
1329 if (!cpu_active(dest_cpu))
1330 continue;
1331 goto out;
1332 }
5da9a0fb 1333
2baab4e9
PZ
1334 switch (state) {
1335 case cpuset:
1336 /* No more Mr. Nice Guy. */
1337 cpuset_cpus_allowed_fallback(p);
1338 state = possible;
1339 break;
1340
1341 case possible:
1342 do_set_cpus_allowed(p, cpu_possible_mask);
1343 state = fail;
1344 break;
1345
1346 case fail:
1347 BUG();
1348 break;
1349 }
1350 }
1351
1352out:
1353 if (state != cpuset) {
1354 /*
1355 * Don't tell them about moving exiting tasks or
1356 * kernel threads (both mm NULL), since they never
1357 * leave kernel.
1358 */
1359 if (p->mm && printk_ratelimit()) {
3984bb13 1360 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2baab4e9
PZ
1361 task_pid_nr(p), p->comm, cpu);
1362 }
5da9a0fb
PZ
1363 }
1364
1365 return dest_cpu;
1366}
1367
e2912009 1368/*
013fdb80 1369 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
e2912009 1370 */
970b13ba 1371static inline
7608dec2 1372int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
970b13ba 1373{
7608dec2 1374 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
e2912009
PZ
1375
1376 /*
1377 * In order not to call set_task_cpu() on a blocking task we need
1378 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1379 * cpu.
1380 *
1381 * Since this is common to all placement strategies, this lives here.
1382 *
1383 * [ this allows ->select_task() to simply return task_cpu(p) and
1384 * not worry about this generic constraint ]
1385 */
fa17b507 1386 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
70f11205 1387 !cpu_online(cpu)))
5da9a0fb 1388 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
1389
1390 return cpu;
970b13ba 1391}
09a40af5
MG
1392
1393static void update_avg(u64 *avg, u64 sample)
1394{
1395 s64 diff = sample - *avg;
1396 *avg += diff >> 3;
1397}
970b13ba
PZ
1398#endif
1399
d7c01d27 1400static void
b84cb5df 1401ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 1402{
d7c01d27 1403#ifdef CONFIG_SCHEDSTATS
b84cb5df
PZ
1404 struct rq *rq = this_rq();
1405
d7c01d27
PZ
1406#ifdef CONFIG_SMP
1407 int this_cpu = smp_processor_id();
1408
1409 if (cpu == this_cpu) {
1410 schedstat_inc(rq, ttwu_local);
1411 schedstat_inc(p, se.statistics.nr_wakeups_local);
1412 } else {
1413 struct sched_domain *sd;
1414
1415 schedstat_inc(p, se.statistics.nr_wakeups_remote);
057f3fad 1416 rcu_read_lock();
d7c01d27
PZ
1417 for_each_domain(this_cpu, sd) {
1418 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1419 schedstat_inc(sd, ttwu_wake_remote);
1420 break;
1421 }
1422 }
057f3fad 1423 rcu_read_unlock();
d7c01d27 1424 }
f339b9dc
PZ
1425
1426 if (wake_flags & WF_MIGRATED)
1427 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1428
d7c01d27
PZ
1429#endif /* CONFIG_SMP */
1430
1431 schedstat_inc(rq, ttwu_count);
9ed3811a 1432 schedstat_inc(p, se.statistics.nr_wakeups);
d7c01d27
PZ
1433
1434 if (wake_flags & WF_SYNC)
9ed3811a 1435 schedstat_inc(p, se.statistics.nr_wakeups_sync);
d7c01d27 1436
d7c01d27
PZ
1437#endif /* CONFIG_SCHEDSTATS */
1438}
1439
1440static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1441{
9ed3811a 1442 activate_task(rq, p, en_flags);
fd2f4419 1443 p->on_rq = 1;
c2f7115e
PZ
1444
1445 /* if a worker is waking up, notify workqueue */
1446 if (p->flags & PF_WQ_WORKER)
1447 wq_worker_waking_up(p, cpu_of(rq));
9ed3811a
TH
1448}
1449
23f41eeb
PZ
1450/*
1451 * Mark the task runnable and perform wakeup-preemption.
1452 */
89363381 1453static void
23f41eeb 1454ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
9ed3811a 1455{
9ed3811a 1456 check_preempt_curr(rq, p, wake_flags);
a8d7ad52 1457 trace_sched_wakeup(p, true);
9ed3811a
TH
1458
1459 p->state = TASK_RUNNING;
1460#ifdef CONFIG_SMP
1461 if (p->sched_class->task_woken)
1462 p->sched_class->task_woken(rq, p);
1463
e69c6341 1464 if (rq->idle_stamp) {
9ed3811a
TH
1465 u64 delta = rq->clock - rq->idle_stamp;
1466 u64 max = 2*sysctl_sched_migration_cost;
1467
1468 if (delta > max)
1469 rq->avg_idle = max;
1470 else
1471 update_avg(&rq->avg_idle, delta);
1472 rq->idle_stamp = 0;
1473 }
1474#endif
1475}
1476
c05fbafb
PZ
1477static void
1478ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1479{
1480#ifdef CONFIG_SMP
1481 if (p->sched_contributes_to_load)
1482 rq->nr_uninterruptible--;
1483#endif
1484
1485 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1486 ttwu_do_wakeup(rq, p, wake_flags);
1487}
1488
1489/*
1490 * Called in case the task @p isn't fully descheduled from its runqueue,
1491 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1492 * since all we need to do is flip p->state to TASK_RUNNING, since
1493 * the task is still ->on_rq.
1494 */
1495static int ttwu_remote(struct task_struct *p, int wake_flags)
1496{
1497 struct rq *rq;
1498 int ret = 0;
1499
1500 rq = __task_rq_lock(p);
1501 if (p->on_rq) {
1502 ttwu_do_wakeup(rq, p, wake_flags);
1503 ret = 1;
1504 }
1505 __task_rq_unlock(rq);
1506
1507 return ret;
1508}
1509
317f3941 1510#ifdef CONFIG_SMP
fa14ff4a 1511static void sched_ttwu_pending(void)
317f3941
PZ
1512{
1513 struct rq *rq = this_rq();
fa14ff4a
PZ
1514 struct llist_node *llist = llist_del_all(&rq->wake_list);
1515 struct task_struct *p;
317f3941
PZ
1516
1517 raw_spin_lock(&rq->lock);
1518
fa14ff4a
PZ
1519 while (llist) {
1520 p = llist_entry(llist, struct task_struct, wake_entry);
1521 llist = llist_next(llist);
317f3941
PZ
1522 ttwu_do_activate(rq, p, 0);
1523 }
1524
1525 raw_spin_unlock(&rq->lock);
1526}
6fa3eb70
S
1527enum ipi_msg_type {
1528 IPI_RESCHEDULE,
1529 IPI_CALL_FUNC,
1530 IPI_CALL_FUNC_SINGLE,
1531 IPI_CPU_STOP,
1532};
317f3941
PZ
1533void scheduler_ipi(void)
1534{
873b4c65
VG
1535 if (llist_empty(&this_rq()->wake_list)
1536 && !tick_nohz_full_cpu(smp_processor_id())
6fa3eb70
S
1537 && !got_nohz_idle_kick()){
1538 mt_trace_ISR_start(IPI_RESCHEDULE);
1539 mt_trace_ISR_end(IPI_RESCHEDULE);
c5d753a5 1540 return;
6fa3eb70 1541 }
c5d753a5
PZ
1542
1543 /*
1544 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1545 * traditionally all their work was done from the interrupt return
1546 * path. Now that we actually do some work, we need to make sure
1547 * we do call them.
1548 *
1549 * Some archs already do call them, luckily irq_enter/exit nest
1550 * properly.
1551 *
1552 * Arguably we should visit all archs and update all handlers,
1553 * however a fair share of IPIs are still resched only so this would
1554 * somewhat pessimize the simple resched case.
1555 */
1556 irq_enter();
6fa3eb70 1557 mt_trace_ISR_start(IPI_RESCHEDULE);
ff442c51 1558 tick_nohz_full_check();
fa14ff4a 1559 sched_ttwu_pending();
ca38062e
SS
1560
1561 /*
1562 * Check if someone kicked us for doing the nohz idle load balance.
1563 */
873b4c65 1564 if (unlikely(got_nohz_idle_kick())) {
6eb57e0d 1565 this_rq()->idle_balance = 1;
ca38062e 1566 raise_softirq_irqoff(SCHED_SOFTIRQ);
6eb57e0d 1567 }
6fa3eb70 1568 mt_trace_ISR_end(IPI_RESCHEDULE);
c5d753a5 1569 irq_exit();
317f3941
PZ
1570}
1571
1572static void ttwu_queue_remote(struct task_struct *p, int cpu)
1573{
fa14ff4a 1574 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
317f3941
PZ
1575 smp_send_reschedule(cpu);
1576}
d6aa8f85 1577
39be3501 1578bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623
PZ
1579{
1580 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1581}
d6aa8f85 1582#endif /* CONFIG_SMP */
317f3941 1583
c05fbafb
PZ
1584static void ttwu_queue(struct task_struct *p, int cpu)
1585{
1586 struct rq *rq = cpu_rq(cpu);
1587
17d9f311 1588#if defined(CONFIG_SMP)
39be3501 1589 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
f01114cb 1590 sched_clock_cpu(cpu); /* sync clocks x-cpu */
317f3941
PZ
1591 ttwu_queue_remote(p, cpu);
1592 return;
1593 }
1594#endif
1595
c05fbafb
PZ
1596 raw_spin_lock(&rq->lock);
1597 ttwu_do_activate(rq, p, 0);
1598 raw_spin_unlock(&rq->lock);
9ed3811a
TH
1599}
1600
1601/**
1da177e4 1602 * try_to_wake_up - wake up a thread
9ed3811a 1603 * @p: the thread to be awakened
1da177e4 1604 * @state: the mask of task states that can be woken
9ed3811a 1605 * @wake_flags: wake modifier flags (WF_*)
1da177e4
LT
1606 *
1607 * Put it on the run-queue if it's not already there. The "current"
1608 * thread is always on the run-queue (except when the actual
1609 * re-schedule is in progress), and as such you're allowed to do
1610 * the simpler "current->state = TASK_RUNNING" to mark yourself
1611 * runnable without the overhead of this.
1612 *
9ed3811a
TH
1613 * Returns %true if @p was woken up, %false if it was already running
1614 * or @state didn't match @p's state.
1da177e4 1615 */
e4a52bcb
PZ
1616static int
1617try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 1618{
1da177e4 1619 unsigned long flags;
c05fbafb 1620 int cpu, success = 0;
2398f2c6 1621
57f74b6e
ON
1622 /*
1623 * If we are going to wake up a thread waiting for CONDITION we
1624 * need to ensure that CONDITION=1 done by the caller can not be
1625 * reordered with p->state check below. This pairs with mb() in
1626 * set_current_state() the waiting thread does.
1627 */
1628 smp_mb__before_spinlock();
013fdb80 1629 raw_spin_lock_irqsave(&p->pi_lock, flags);
e9c84311 1630 if (!(p->state & state))
1da177e4
LT
1631 goto out;
1632
c05fbafb 1633 success = 1; /* we're going to change ->state */
1da177e4 1634 cpu = task_cpu(p);
1da177e4 1635
6a94ced1
BS
1636 /*
1637 * Ensure we load p->on_rq _after_ p->state, otherwise it would
1638 * be possible to, falsely, observe p->on_rq == 0 and get stuck
1639 * in smp_cond_load_acquire() below.
1640 *
1641 * sched_ttwu_pending() try_to_wake_up()
1642 * [S] p->on_rq = 1; [L] P->state
1643 * UNLOCK rq->lock -----.
1644 * \
1645 * +--- RMB
1646 * schedule() /
1647 * LOCK rq->lock -----'
1648 * UNLOCK rq->lock
1649 *
1650 * [task p]
1651 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
1652 *
1653 * Pairs with the UNLOCK+LOCK on rq->lock from the
1654 * last wakeup of our task and the schedule that got our task
1655 * current.
1656 */
1657 smp_rmb();
c05fbafb
PZ
1658 if (p->on_rq && ttwu_remote(p, wake_flags))
1659 goto stat;
1da177e4 1660
1da177e4 1661#ifdef CONFIG_SMP
c73d76df
PZ
1662 /*
1663 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
1664 * possible to, falsely, observe p->on_cpu == 0.
1665 *
1666 * One must be running (->on_cpu == 1) in order to remove oneself
1667 * from the runqueue.
1668 *
1669 * [S] ->on_cpu = 1; [L] ->on_rq
1670 * UNLOCK rq->lock
1671 * RMB
1672 * LOCK rq->lock
1673 * [S] ->on_rq = 0; [L] ->on_cpu
1674 *
1675 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
1676 * from the consecutive calls to schedule(); the first switching to our
1677 * task, the second putting it to sleep.
1678 */
1679 smp_rmb();
1680
e9c84311 1681 /*
c05fbafb
PZ
1682 * If the owning (remote) cpu is still in the middle of schedule() with
1683 * this task as prev, wait until its done referencing the task.
e9c84311 1684 */
f3e94786 1685 while (p->on_cpu)
e4a52bcb 1686 cpu_relax();
0970d299 1687 /*
e4a52bcb 1688 * Pairs with the smp_wmb() in finish_lock_switch().
0970d299 1689 */
e4a52bcb 1690 smp_rmb();
1da177e4 1691
a8e4f2ea 1692 p->sched_contributes_to_load = !!task_contributes_to_load(p);
e9c84311 1693 p->state = TASK_WAKING;
e7693a36 1694
e4a52bcb 1695 if (p->sched_class->task_waking)
74f8e4b2 1696 p->sched_class->task_waking(p);
efbbd05a 1697
7608dec2 1698 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
f339b9dc 1699 if (task_cpu(p) != cpu) {
6fa3eb70
S
1700#ifdef CONFIG_MT_LOAD_BALANCE_PROFILER
1701 char strings[128]="";
1702#endif
f339b9dc 1703 wake_flags |= WF_MIGRATED;
6fa3eb70
S
1704#ifdef CONFIG_MT_LOAD_BALANCE_PROFILER
1705 snprintf(strings, 128, "%d:%d:%s:wakeup:%d:%d:%s", task_cpu(current), current->pid, current->comm, cpu, p->pid, p->comm);
1706 trace_sched_lbprof_log(strings);
1707#endif
e4a52bcb 1708 set_task_cpu(p, cpu);
f339b9dc 1709 }
1da177e4 1710#endif /* CONFIG_SMP */
1da177e4 1711
c05fbafb
PZ
1712 ttwu_queue(p, cpu);
1713stat:
b84cb5df 1714 ttwu_stat(p, cpu, wake_flags);
1da177e4 1715out:
013fdb80 1716 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
1717
1718 return success;
1719}
1720
21aa9af0
TH
1721/**
1722 * try_to_wake_up_local - try to wake up a local task with rq lock held
1723 * @p: the thread to be awakened
1724 *
2acca55e 1725 * Put @p on the run-queue if it's not already there. The caller must
21aa9af0 1726 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2acca55e 1727 * the current task.
21aa9af0
TH
1728 */
1729static void try_to_wake_up_local(struct task_struct *p)
1730{
1731 struct rq *rq = task_rq(p);
21aa9af0 1732
383efcd0
TH
1733 if (WARN_ON_ONCE(rq != this_rq()) ||
1734 WARN_ON_ONCE(p == current))
1735 return;
1736
21aa9af0
TH
1737 lockdep_assert_held(&rq->lock);
1738
2acca55e
PZ
1739 if (!raw_spin_trylock(&p->pi_lock)) {
1740 raw_spin_unlock(&rq->lock);
1741 raw_spin_lock(&p->pi_lock);
1742 raw_spin_lock(&rq->lock);
1743 }
1744
21aa9af0 1745 if (!(p->state & TASK_NORMAL))
2acca55e 1746 goto out;
21aa9af0 1747
fd2f4419 1748 if (!p->on_rq)
d7c01d27
PZ
1749 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
1750
23f41eeb 1751 ttwu_do_wakeup(rq, p, 0);
b84cb5df 1752 ttwu_stat(p, smp_processor_id(), 0);
2acca55e
PZ
1753out:
1754 raw_spin_unlock(&p->pi_lock);
21aa9af0
TH
1755}
1756
50fa610a
DH
1757/**
1758 * wake_up_process - Wake up a specific process
1759 * @p: The process to be woken up.
1760 *
1761 * Attempt to wake up the nominated process and move it to the set of runnable
1762 * processes. Returns 1 if the process was woken up, 0 if it was already
1763 * running.
1764 *
1765 * It may be assumed that this function implies a write memory barrier before
1766 * changing the task state if and only if any tasks are woken up.
1767 */
7ad5b3a5 1768int wake_up_process(struct task_struct *p)
1da177e4 1769{
9067ac85 1770 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 1771}
1da177e4
LT
1772EXPORT_SYMBOL(wake_up_process);
1773
7ad5b3a5 1774int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
1775{
1776 return try_to_wake_up(p, state, 0);
1777}
1778
1da177e4
LT
1779/*
1780 * Perform scheduler related setup for a newly forked process p.
1781 * p is forked by current.
dd41f596
IM
1782 *
1783 * __sched_fork() is basic setup used by init_idle() too:
1784 */
1785static void __sched_fork(struct task_struct *p)
1786{
fd2f4419
PZ
1787 p->on_rq = 0;
1788
1789 p->se.on_rq = 0;
dd41f596
IM
1790 p->se.exec_start = 0;
1791 p->se.sum_exec_runtime = 0;
f6cf891c 1792 p->se.prev_sum_exec_runtime = 0;
6c594c21 1793 p->se.nr_migrations = 0;
da7a735e 1794 p->se.vruntime = 0;
fd2f4419 1795 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 1796
f4e26b12
PT
1797/*
1798 * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
1799 * removed when useful for applications beyond shares distribution (e.g.
1800 * load-balance).
1801 */
1802#if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
9d85f21c
PT
1803 p->se.avg.runnable_avg_period = 0;
1804 p->se.avg.runnable_avg_sum = 0;
6fa3eb70
S
1805#ifdef CONFIG_SCHED_HMP
1806 /* keep LOAD_AVG_MAX in sync with fair.c if load avg series is changed */
1807#define LOAD_AVG_MAX 47742
1808 if (p->mm) {
1809 p->se.avg.hmp_last_up_migration = 0;
1810 p->se.avg.hmp_last_down_migration = 0;
1811 p->se.avg.load_avg_ratio = 1023;
1812 p->se.avg.load_avg_contrib =
1813 (1023 * scale_load_down(p->se.load.weight));
1814 p->se.avg.runnable_avg_period = LOAD_AVG_MAX;
1815 p->se.avg.runnable_avg_sum = LOAD_AVG_MAX;
1816 p->se.avg.usage_avg_sum = LOAD_AVG_MAX;
1817 }
1818#endif
9d85f21c 1819#endif
6cfb0d5d 1820#ifdef CONFIG_SCHEDSTATS
41acab88 1821 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
6cfb0d5d 1822#endif
476d139c 1823
fa717060 1824 INIT_LIST_HEAD(&p->rt.run_list);
476d139c 1825
e107be36
AK
1826#ifdef CONFIG_PREEMPT_NOTIFIERS
1827 INIT_HLIST_HEAD(&p->preempt_notifiers);
1828#endif
cbee9f88
PZ
1829
1830#ifdef CONFIG_NUMA_BALANCING
1831 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
1832 p->mm->numa_next_scan = jiffies;
b8593bfd 1833 p->mm->numa_next_reset = jiffies;
cbee9f88
PZ
1834 p->mm->numa_scan_seq = 0;
1835 }
1836
1837 p->node_stamp = 0ULL;
1838 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
1839 p->numa_migrate_seq = p->mm ? p->mm->numa_scan_seq - 1 : 0;
4b96a29b 1840 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
cbee9f88
PZ
1841 p->numa_work.next = &p->numa_work;
1842#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
1843}
1844
1a687c2e 1845#ifdef CONFIG_NUMA_BALANCING
3105b86a 1846#ifdef CONFIG_SCHED_DEBUG
1a687c2e
MG
1847void set_numabalancing_state(bool enabled)
1848{
1849 if (enabled)
1850 sched_feat_set("NUMA");
1851 else
1852 sched_feat_set("NO_NUMA");
1853}
3105b86a
MG
1854#else
1855__read_mostly bool numabalancing_enabled;
1856
1857void set_numabalancing_state(bool enabled)
1858{
1859 numabalancing_enabled = enabled;
dd41f596 1860}
3105b86a 1861#endif /* CONFIG_SCHED_DEBUG */
1a687c2e 1862#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
1863
1864/*
1865 * fork()/clone()-time setup:
1866 */
3e51e3ed 1867void sched_fork(struct task_struct *p)
dd41f596 1868{
0122ec5b 1869 unsigned long flags;
dd41f596
IM
1870 int cpu = get_cpu();
1871
1872 __sched_fork(p);
06b83b5f 1873 /*
0017d735 1874 * We mark the process as running here. This guarantees that
06b83b5f
PZ
1875 * nobody will actually run it, and a signal or other external
1876 * event cannot wake it up and insert it on the runqueue either.
1877 */
0017d735 1878 p->state = TASK_RUNNING;
dd41f596 1879
c350a04e
MG
1880 /*
1881 * Make sure we do not leak PI boosting priority to the child.
1882 */
1883 p->prio = current->normal_prio;
1884
b9dc29e7
MG
1885 /*
1886 * Revert to default priority/policy on fork if requested.
1887 */
1888 if (unlikely(p->sched_reset_on_fork)) {
c350a04e 1889 if (task_has_rt_policy(p)) {
b9dc29e7 1890 p->policy = SCHED_NORMAL;
6c697bdf 1891 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
1892 p->rt_priority = 0;
1893 } else if (PRIO_TO_NICE(p->static_prio) < 0)
1894 p->static_prio = NICE_TO_PRIO(0);
1895
1896 p->prio = p->normal_prio = __normal_prio(p);
1897 set_load_weight(p);
6c697bdf 1898
b9dc29e7
MG
1899 /*
1900 * We don't need the reset flag anymore after the fork. It has
1901 * fulfilled its duty:
1902 */
1903 p->sched_reset_on_fork = 0;
1904 }
ca94c442 1905
2ddbf952
HS
1906 if (!rt_prio(p->prio))
1907 p->sched_class = &fair_sched_class;
b29739f9 1908
cd29fe6f
PZ
1909 if (p->sched_class->task_fork)
1910 p->sched_class->task_fork(p);
1911
86951599
PZ
1912 /*
1913 * The child is not yet in the pid-hash so no cgroup attach races,
1914 * and the cgroup is pinned to this child due to cgroup_fork()
1915 * is ran before sched_fork().
1916 *
1917 * Silence PROVE_RCU.
1918 */
0122ec5b 1919 raw_spin_lock_irqsave(&p->pi_lock, flags);
5f3edc1b 1920 set_task_cpu(p, cpu);
0122ec5b 1921 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5f3edc1b 1922
52f17b6c 1923#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
dd41f596 1924 if (likely(sched_info_on()))
52f17b6c 1925 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 1926#endif
3ca7a440
PZ
1927#if defined(CONFIG_SMP)
1928 p->on_cpu = 0;
4866cde0 1929#endif
bdd4e85d 1930#ifdef CONFIG_PREEMPT_COUNT
4866cde0 1931 /* Want to start with kernel preemption disabled. */
a1261f54 1932 task_thread_info(p)->preempt_count = 1;
1da177e4 1933#endif
806c09a7 1934#ifdef CONFIG_SMP
917b627d 1935 plist_node_init(&p->pushable_tasks, MAX_PRIO);
806c09a7 1936#endif
917b627d 1937
476d139c 1938 put_cpu();
1da177e4
LT
1939}
1940
1941/*
1942 * wake_up_new_task - wake up a newly created task for the first time.
1943 *
1944 * This function will do some initial scheduler statistics housekeeping
1945 * that must be done for every newly created context, then puts the task
1946 * on the runqueue and wakes it.
1947 */
3e51e3ed 1948void wake_up_new_task(struct task_struct *p)
1da177e4
LT
1949{
1950 unsigned long flags;
dd41f596 1951 struct rq *rq;
fabf318e 1952
ab2515c4 1953 raw_spin_lock_irqsave(&p->pi_lock, flags);
fabf318e
PZ
1954#ifdef CONFIG_SMP
1955 /*
1956 * Fork balancing, do it here and not earlier because:
1957 * - cpus_allowed can change in the fork path
1958 * - any previously selected cpu might disappear through hotplug
fabf318e 1959 */
ab2515c4 1960 set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
0017d735
PZ
1961#endif
1962
6fa3eb70
S
1963 /* Initialize new task's runnable average */
1964 init_task_runnable_average(p);
ab2515c4 1965 rq = __task_rq_lock(p);
cd29fe6f 1966 activate_task(rq, p, 0);
fd2f4419 1967 p->on_rq = 1;
89363381 1968 trace_sched_wakeup_new(p, true);
a7558e01 1969 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 1970#ifdef CONFIG_SMP
efbbd05a
PZ
1971 if (p->sched_class->task_woken)
1972 p->sched_class->task_woken(rq, p);
9a897c5a 1973#endif
0122ec5b 1974 task_rq_unlock(rq, p, &flags);
1da177e4
LT
1975}
1976
e107be36
AK
1977#ifdef CONFIG_PREEMPT_NOTIFIERS
1978
1979/**
80dd99b3 1980 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 1981 * @notifier: notifier struct to register
e107be36
AK
1982 */
1983void preempt_notifier_register(struct preempt_notifier *notifier)
1984{
1985 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1986}
1987EXPORT_SYMBOL_GPL(preempt_notifier_register);
1988
1989/**
1990 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 1991 * @notifier: notifier struct to unregister
e107be36
AK
1992 *
1993 * This is safe to call from within a preemption notifier.
1994 */
1995void preempt_notifier_unregister(struct preempt_notifier *notifier)
1996{
1997 hlist_del(&notifier->link);
1998}
1999EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2000
2001static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2002{
2003 struct preempt_notifier *notifier;
e107be36 2004
b67bfe0d 2005 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2006 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2007}
2008
2009static void
2010fire_sched_out_preempt_notifiers(struct task_struct *curr,
2011 struct task_struct *next)
2012{
2013 struct preempt_notifier *notifier;
e107be36 2014
b67bfe0d 2015 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2016 notifier->ops->sched_out(notifier, next);
2017}
2018
6d6bc0ad 2019#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36
AK
2020
2021static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2022{
2023}
2024
2025static void
2026fire_sched_out_preempt_notifiers(struct task_struct *curr,
2027 struct task_struct *next)
2028{
2029}
2030
6d6bc0ad 2031#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 2032
4866cde0
NP
2033/**
2034 * prepare_task_switch - prepare to switch tasks
2035 * @rq: the runqueue preparing to switch
421cee29 2036 * @prev: the current task that is being switched out
4866cde0
NP
2037 * @next: the task we are going to switch to.
2038 *
2039 * This is called with the rq lock held and interrupts off. It must
2040 * be paired with a subsequent finish_task_switch after the context
2041 * switch.
2042 *
2043 * prepare_task_switch sets up locking and calls architecture specific
2044 * hooks.
2045 */
e107be36
AK
2046static inline void
2047prepare_task_switch(struct rq *rq, struct task_struct *prev,
2048 struct task_struct *next)
4866cde0 2049{
895dd92c 2050 trace_sched_switch(prev, next);
fe4b04fa
PZ
2051 sched_info_switch(prev, next);
2052 perf_event_task_sched_out(prev, next);
e107be36 2053 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
2054 prepare_lock_switch(rq, next);
2055 prepare_arch_switch(next);
2056}
2057
1da177e4
LT
2058/**
2059 * finish_task_switch - clean up after a task-switch
344babaa 2060 * @rq: runqueue associated with task-switch
1da177e4
LT
2061 * @prev: the thread we just switched away from.
2062 *
4866cde0
NP
2063 * finish_task_switch must be called after the context switch, paired
2064 * with a prepare_task_switch call before the context switch.
2065 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2066 * and do any other architecture-specific cleanup actions.
1da177e4
LT
2067 *
2068 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 2069 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
2070 * with the lock held can cause deadlocks; see schedule() for
2071 * details.)
2072 */
a9957449 2073static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1da177e4
LT
2074 __releases(rq->lock)
2075{
1da177e4 2076 struct mm_struct *mm = rq->prev_mm;
55a101f8 2077 long prev_state;
1da177e4
LT
2078
2079 rq->prev_mm = NULL;
2080
2081 /*
2082 * A task struct has one reference for the use as "current".
c394cc9f 2083 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
2084 * schedule one last time. The schedule call will never return, and
2085 * the scheduled task must drop that reference.
c394cc9f 2086 * The test for TASK_DEAD must occur while the runqueue locks are
1da177e4
LT
2087 * still held, otherwise prev could be scheduled on another cpu, die
2088 * there before we look at prev->state, and then the reference would
2089 * be dropped twice.
2090 * Manfred Spraul <manfred@colorfullife.com>
2091 */
55a101f8 2092 prev_state = prev->state;
bf9fae9f 2093 vtime_task_switch(prev);
4866cde0 2094 finish_arch_switch(prev);
a8d757ef 2095 perf_event_task_sched_in(prev, current);
4866cde0 2096 finish_lock_switch(rq, prev);
01f23e16 2097 finish_arch_post_lock_switch();
e8fa1362 2098
e107be36 2099 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
2100 if (mm)
2101 mmdrop(mm);
c394cc9f 2102 if (unlikely(prev_state == TASK_DEAD)) {
c6fd91f0 2103 /*
2104 * Remove function-return probe instances associated with this
2105 * task and put them back on the free list.
9761eea8 2106 */
c6fd91f0 2107 kprobe_flush_task(prev);
1da177e4 2108 put_task_struct(prev);
c6fd91f0 2109 }
99e5ada9
FW
2110
2111 tick_nohz_task_switch(current);
1da177e4
LT
2112}
2113
3f029d3c
GH
2114#ifdef CONFIG_SMP
2115
2116/* assumes rq->lock is held */
2117static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2118{
2119 if (prev->sched_class->pre_schedule)
2120 prev->sched_class->pre_schedule(rq, prev);
2121}
2122
2123/* rq->lock is NOT held, but preemption is disabled */
2124static inline void post_schedule(struct rq *rq)
2125{
2126 if (rq->post_schedule) {
2127 unsigned long flags;
2128
05fa785c 2129 raw_spin_lock_irqsave(&rq->lock, flags);
3f029d3c
GH
2130 if (rq->curr->sched_class->post_schedule)
2131 rq->curr->sched_class->post_schedule(rq);
05fa785c 2132 raw_spin_unlock_irqrestore(&rq->lock, flags);
3f029d3c
GH
2133
2134 rq->post_schedule = 0;
2135 }
2136}
2137
2138#else
da19ab51 2139
3f029d3c
GH
2140static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2141{
2142}
2143
2144static inline void post_schedule(struct rq *rq)
2145{
1da177e4
LT
2146}
2147
3f029d3c
GH
2148#endif
2149
1da177e4
LT
2150/**
2151 * schedule_tail - first thing a freshly forked thread must call.
2152 * @prev: the thread we just switched away from.
2153 */
36c8b586 2154asmlinkage void schedule_tail(struct task_struct *prev)
1da177e4
LT
2155 __releases(rq->lock)
2156{
70b97a7f
IM
2157 struct rq *rq = this_rq();
2158
4866cde0 2159 finish_task_switch(rq, prev);
da19ab51 2160
3f029d3c
GH
2161 /*
2162 * FIXME: do we need to worry about rq being invalidated by the
2163 * task_switch?
2164 */
2165 post_schedule(rq);
70b97a7f 2166
4866cde0
NP
2167#ifdef __ARCH_WANT_UNLOCKED_CTXSW
2168 /* In this case, finish_task_switch does not reenable preemption */
2169 preempt_enable();
2170#endif
1da177e4 2171 if (current->set_child_tid)
b488893a 2172 put_user(task_pid_vnr(current), current->set_child_tid);
1da177e4
LT
2173}
2174
2175/*
2176 * context_switch - switch to the new MM and the new
2177 * thread's register state.
2178 */
dd41f596 2179static inline void
70b97a7f 2180context_switch(struct rq *rq, struct task_struct *prev,
36c8b586 2181 struct task_struct *next)
1da177e4 2182{
dd41f596 2183 struct mm_struct *mm, *oldmm;
1da177e4 2184
e107be36 2185 prepare_task_switch(rq, prev, next);
fe4b04fa 2186
6fa3eb70
S
2187#ifdef CONFIG_MT65XX_TRACER
2188 if(get_mt65xx_mon_mode() == MODE_SCHED_SWITCH)
2189 trace_mt65xx_mon_sched_switch(prev, next);
2190#endif
dd41f596
IM
2191 mm = next->mm;
2192 oldmm = prev->active_mm;
9226d125
ZA
2193 /*
2194 * For paravirt, this is coupled with an exit in switch_to to
2195 * combine the page table reload and the switch backend into
2196 * one hypercall.
2197 */
224101ed 2198 arch_start_context_switch(prev);
9226d125 2199
31915ab4 2200 if (!mm) {
1da177e4
LT
2201 next->active_mm = oldmm;
2202 atomic_inc(&oldmm->mm_count);
2203 enter_lazy_tlb(oldmm, next);
2204 } else
2205 switch_mm(oldmm, mm, next);
2206
31915ab4 2207 if (!prev->mm) {
1da177e4 2208 prev->active_mm = NULL;
1da177e4
LT
2209 rq->prev_mm = oldmm;
2210 }
3a5f5e48
IM
2211 /*
2212 * Since the runqueue lock will be released by the next
2213 * task (which is an invalid locking op but in the case
2214 * of the scheduler it's an obvious special-case), so we
2215 * do an early lockdep release here:
2216 */
2217#ifndef __ARCH_WANT_UNLOCKED_CTXSW
8a25d5de 2218 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3a5f5e48 2219#endif
1da177e4 2220
91d1aa43 2221 context_tracking_task_switch(prev, next);
1da177e4
LT
2222 /* Here we just switch the register state and the stack. */
2223 switch_to(prev, next, prev);
2224
dd41f596
IM
2225 barrier();
2226 /*
2227 * this_rq must be evaluated again because prev may have moved
2228 * CPUs since it called schedule(), thus the 'rq' on its stack
2229 * frame will be invalid.
2230 */
2231 finish_task_switch(this_rq(), prev);
1da177e4
LT
2232}
2233
2234/*
1c3e8264 2235 * nr_running and nr_context_switches:
1da177e4
LT
2236 *
2237 * externally visible scheduler statistics: current number of runnable
1c3e8264 2238 * threads, total number of context switches performed since bootup.
1da177e4
LT
2239 */
2240unsigned long nr_running(void)
2241{
2242 unsigned long i, sum = 0;
2243
2244 for_each_online_cpu(i)
2245 sum += cpu_rq(i)->nr_running;
2246
2247 return sum;
f711f609 2248}
1da177e4 2249
1da177e4 2250unsigned long long nr_context_switches(void)
46cb4b7c 2251{
cc94abfc
SR
2252 int i;
2253 unsigned long long sum = 0;
46cb4b7c 2254
0a945022 2255 for_each_possible_cpu(i)
1da177e4 2256 sum += cpu_rq(i)->nr_switches;
46cb4b7c 2257
1da177e4
LT
2258 return sum;
2259}
483b4ee6 2260
1da177e4
LT
2261unsigned long nr_iowait(void)
2262{
2263 unsigned long i, sum = 0;
483b4ee6 2264
0a945022 2265 for_each_possible_cpu(i)
1da177e4 2266 sum += atomic_read(&cpu_rq(i)->nr_iowait);
46cb4b7c 2267
1da177e4
LT
2268 return sum;
2269}
483b4ee6 2270
8c215bd3 2271unsigned long nr_iowait_cpu(int cpu)
69d25870 2272{
8c215bd3 2273 struct rq *this = cpu_rq(cpu);
69d25870
AV
2274 return atomic_read(&this->nr_iowait);
2275}
46cb4b7c 2276
69d25870
AV
2277unsigned long this_cpu_load(void)
2278{
2279 struct rq *this = this_rq();
2280 return this->cpu_load[0];
2281}
e790fb0b 2282
6fa3eb70
S
2283unsigned long get_cpu_load(int cpu)
2284{
2285 struct rq *this = cpu_rq(cpu);
2286 return this->cpu_load[0];
2287}
2288EXPORT_SYMBOL(get_cpu_load);
46cb4b7c 2289
5167e8d5
PZ
2290/*
2291 * Global load-average calculations
2292 *
2293 * We take a distributed and async approach to calculating the global load-avg
2294 * in order to minimize overhead.
2295 *
2296 * The global load average is an exponentially decaying average of nr_running +
2297 * nr_uninterruptible.
2298 *
2299 * Once every LOAD_FREQ:
2300 *
2301 * nr_active = 0;
2302 * for_each_possible_cpu(cpu)
2303 * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
2304 *
2305 * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
2306 *
2307 * Due to a number of reasons the above turns in the mess below:
2308 *
2309 * - for_each_possible_cpu() is prohibitively expensive on machines with
2310 * serious number of cpus, therefore we need to take a distributed approach
2311 * to calculating nr_active.
2312 *
2313 * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
2314 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
2315 *
2316 * So assuming nr_active := 0 when we start out -- true per definition, we
2317 * can simply take per-cpu deltas and fold those into a global accumulate
2318 * to obtain the same result. See calc_load_fold_active().
2319 *
2320 * Furthermore, in order to avoid synchronizing all per-cpu delta folding
2321 * across the machine, we assume 10 ticks is sufficient time for every
2322 * cpu to have completed this task.
2323 *
2324 * This places an upper-bound on the IRQ-off latency of the machine. Then
2325 * again, being late doesn't loose the delta, just wrecks the sample.
2326 *
2327 * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
2328 * this would add another cross-cpu cacheline miss and atomic operation
2329 * to the wakeup path. Instead we increment on whatever cpu the task ran
2330 * when it went into uninterruptible state and decrement on whatever cpu
2331 * did the wakeup. This means that only the sum of nr_uninterruptible over
2332 * all cpus yields the correct result.
2333 *
2334 * This covers the NO_HZ=n code, for extra head-aches, see the comment below.
2335 */
2336
dce48a84
TG
2337/* Variables and functions for calc_load */
2338static atomic_long_t calc_load_tasks;
2339static unsigned long calc_load_update;
2340unsigned long avenrun[3];
5167e8d5
PZ
2341EXPORT_SYMBOL(avenrun); /* should be removed */
2342
2343/**
2344 * get_avenrun - get the load average array
2345 * @loads: pointer to dest load array
2346 * @offset: offset to add
2347 * @shift: shift count to shift the result left
2348 *
2349 * These values are estimates at best, so no need for locking.
2350 */
2351void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
2352{
2353 loads[0] = (avenrun[0] + offset) << shift;
2354 loads[1] = (avenrun[1] + offset) << shift;
2355 loads[2] = (avenrun[2] + offset) << shift;
2356}
46cb4b7c 2357
74f5187a
PZ
2358static long calc_load_fold_active(struct rq *this_rq)
2359{
2360 long nr_active, delta = 0;
2361
2362 nr_active = this_rq->nr_running;
2363 nr_active += (long) this_rq->nr_uninterruptible;
2364
2365 if (nr_active != this_rq->calc_load_active) {
2366 delta = nr_active - this_rq->calc_load_active;
2367 this_rq->calc_load_active = nr_active;
2368 }
2369
2370 return delta;
2371}
2372
5167e8d5
PZ
2373/*
2374 * a1 = a0 * e + a * (1 - e)
2375 */
0f004f5a
PZ
2376static unsigned long
2377calc_load(unsigned long load, unsigned long exp, unsigned long active)
2378{
2379 load *= exp;
2380 load += active * (FIXED_1 - exp);
2381 load += 1UL << (FSHIFT - 1);
2382 return load >> FSHIFT;
2383}
2384
3451d024 2385#ifdef CONFIG_NO_HZ_COMMON
74f5187a 2386/*
5167e8d5
PZ
2387 * Handle NO_HZ for the global load-average.
2388 *
2389 * Since the above described distributed algorithm to compute the global
2390 * load-average relies on per-cpu sampling from the tick, it is affected by
2391 * NO_HZ.
2392 *
2393 * The basic idea is to fold the nr_active delta into a global idle-delta upon
2394 * entering NO_HZ state such that we can include this as an 'extra' cpu delta
2395 * when we read the global state.
2396 *
2397 * Obviously reality has to ruin such a delightfully simple scheme:
2398 *
2399 * - When we go NO_HZ idle during the window, we can negate our sample
2400 * contribution, causing under-accounting.
2401 *
2402 * We avoid this by keeping two idle-delta counters and flipping them
2403 * when the window starts, thus separating old and new NO_HZ load.
2404 *
2405 * The only trick is the slight shift in index flip for read vs write.
2406 *
2407 * 0s 5s 10s 15s
2408 * +10 +10 +10 +10
2409 * |-|-----------|-|-----------|-|-----------|-|
2410 * r:0 0 1 1 0 0 1 1 0
2411 * w:0 1 1 0 0 1 1 0 0
2412 *
2413 * This ensures we'll fold the old idle contribution in this window while
2414 * accumlating the new one.
2415 *
2416 * - When we wake up from NO_HZ idle during the window, we push up our
2417 * contribution, since we effectively move our sample point to a known
2418 * busy state.
2419 *
2420 * This is solved by pushing the window forward, and thus skipping the
2421 * sample, for this cpu (effectively using the idle-delta for this cpu which
2422 * was in effect at the time the window opened). This also solves the issue
2423 * of having to deal with a cpu having been in NOHZ idle for multiple
2424 * LOAD_FREQ intervals.
74f5187a
PZ
2425 *
2426 * When making the ILB scale, we should try to pull this in as well.
2427 */
5167e8d5
PZ
2428static atomic_long_t calc_load_idle[2];
2429static int calc_load_idx;
74f5187a 2430
5167e8d5 2431static inline int calc_load_write_idx(void)
74f5187a 2432{
5167e8d5
PZ
2433 int idx = calc_load_idx;
2434
2435 /*
2436 * See calc_global_nohz(), if we observe the new index, we also
2437 * need to observe the new update time.
2438 */
2439 smp_rmb();
2440
2441 /*
2442 * If the folding window started, make sure we start writing in the
2443 * next idle-delta.
2444 */
2445 if (!time_before(jiffies, calc_load_update))
2446 idx++;
2447
2448 return idx & 1;
2449}
2450
2451static inline int calc_load_read_idx(void)
2452{
2453 return calc_load_idx & 1;
2454}
2455
2456void calc_load_enter_idle(void)
2457{
2458 struct rq *this_rq = this_rq();
74f5187a
PZ
2459 long delta;
2460
5167e8d5
PZ
2461 /*
2462 * We're going into NOHZ mode, if there's any pending delta, fold it
2463 * into the pending idle delta.
2464 */
74f5187a 2465 delta = calc_load_fold_active(this_rq);
5167e8d5
PZ
2466 if (delta) {
2467 int idx = calc_load_write_idx();
2468 atomic_long_add(delta, &calc_load_idle[idx]);
2469 }
74f5187a
PZ
2470}
2471
5167e8d5 2472void calc_load_exit_idle(void)
74f5187a 2473{
5167e8d5
PZ
2474 struct rq *this_rq = this_rq();
2475
2476 /*
2477 * If we're still before the sample window, we're done.
2478 */
2479 if (time_before(jiffies, this_rq->calc_load_update))
2480 return;
74f5187a
PZ
2481
2482 /*
5167e8d5
PZ
2483 * We woke inside or after the sample window, this means we're already
2484 * accounted through the nohz accounting, so skip the entire deal and
2485 * sync up for the next window.
74f5187a 2486 */
5167e8d5
PZ
2487 this_rq->calc_load_update = calc_load_update;
2488 if (time_before(jiffies, this_rq->calc_load_update + 10))
2489 this_rq->calc_load_update += LOAD_FREQ;
2490}
2491
2492static long calc_load_fold_idle(void)
2493{
2494 int idx = calc_load_read_idx();
2495 long delta = 0;
2496
2497 if (atomic_long_read(&calc_load_idle[idx]))
2498 delta = atomic_long_xchg(&calc_load_idle[idx], 0);
74f5187a
PZ
2499
2500 return delta;
2501}
0f004f5a
PZ
2502
2503/**
2504 * fixed_power_int - compute: x^n, in O(log n) time
2505 *
2506 * @x: base of the power
2507 * @frac_bits: fractional bits of @x
2508 * @n: power to raise @x to.
2509 *
2510 * By exploiting the relation between the definition of the natural power
2511 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
2512 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
2513 * (where: n_i \elem {0, 1}, the binary vector representing n),
2514 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
2515 * of course trivially computable in O(log_2 n), the length of our binary
2516 * vector.
2517 */
2518static unsigned long
2519fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
2520{
2521 unsigned long result = 1UL << frac_bits;
2522
2523 if (n) for (;;) {
2524 if (n & 1) {
2525 result *= x;
2526 result += 1UL << (frac_bits - 1);
2527 result >>= frac_bits;
2528 }
2529 n >>= 1;
2530 if (!n)
2531 break;
2532 x *= x;
2533 x += 1UL << (frac_bits - 1);
2534 x >>= frac_bits;
2535 }
2536
2537 return result;
2538}
2539
2540/*
2541 * a1 = a0 * e + a * (1 - e)
2542 *
2543 * a2 = a1 * e + a * (1 - e)
2544 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
2545 * = a0 * e^2 + a * (1 - e) * (1 + e)
2546 *
2547 * a3 = a2 * e + a * (1 - e)
2548 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
2549 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
2550 *
2551 * ...
2552 *
2553 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
2554 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
2555 * = a0 * e^n + a * (1 - e^n)
2556 *
2557 * [1] application of the geometric series:
2558 *
2559 * n 1 - x^(n+1)
2560 * S_n := \Sum x^i = -------------
2561 * i=0 1 - x
2562 */
2563static unsigned long
2564calc_load_n(unsigned long load, unsigned long exp,
2565 unsigned long active, unsigned int n)
2566{
2567
2568 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
2569}
2570
2571/*
2572 * NO_HZ can leave us missing all per-cpu ticks calling
2573 * calc_load_account_active(), but since an idle CPU folds its delta into
2574 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
2575 * in the pending idle delta if our idle period crossed a load cycle boundary.
2576 *
2577 * Once we've updated the global active value, we need to apply the exponential
2578 * weights adjusted to the number of cycles missed.
2579 */
c308b56b 2580static void calc_global_nohz(void)
0f004f5a
PZ
2581{
2582 long delta, active, n;
2583
5167e8d5
PZ
2584 if (!time_before(jiffies, calc_load_update + 10)) {
2585 /*
2586 * Catch-up, fold however many we are behind still
2587 */
2588 delta = jiffies - calc_load_update - 10;
2589 n = 1 + (delta / LOAD_FREQ);
0f004f5a 2590
5167e8d5
PZ
2591 active = atomic_long_read(&calc_load_tasks);
2592 active = active > 0 ? active * FIXED_1 : 0;
0f004f5a 2593
5167e8d5
PZ
2594 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
2595 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
2596 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
0f004f5a 2597
5167e8d5
PZ
2598 calc_load_update += n * LOAD_FREQ;
2599 }
74f5187a 2600
5167e8d5
PZ
2601 /*
2602 * Flip the idle index...
2603 *
2604 * Make sure we first write the new time then flip the index, so that
2605 * calc_load_write_idx() will see the new time when it reads the new
2606 * index, this avoids a double flip messing things up.
2607 */
2608 smp_wmb();
2609 calc_load_idx++;
74f5187a 2610}
3451d024 2611#else /* !CONFIG_NO_HZ_COMMON */
0f004f5a 2612
5167e8d5
PZ
2613static inline long calc_load_fold_idle(void) { return 0; }
2614static inline void calc_global_nohz(void) { }
74f5187a 2615
3451d024 2616#endif /* CONFIG_NO_HZ_COMMON */
46cb4b7c 2617
46cb4b7c 2618/*
dce48a84
TG
2619 * calc_load - update the avenrun load estimates 10 ticks after the
2620 * CPUs have updated calc_load_tasks.
7835b98b 2621 */
0f004f5a 2622void calc_global_load(unsigned long ticks)
7835b98b 2623{
5167e8d5 2624 long active, delta;
1da177e4 2625
0f004f5a 2626 if (time_before(jiffies, calc_load_update + 10))
dce48a84 2627 return;
1da177e4 2628
5167e8d5
PZ
2629 /*
2630 * Fold the 'old' idle-delta to include all NO_HZ cpus.
2631 */
2632 delta = calc_load_fold_idle();
2633 if (delta)
2634 atomic_long_add(delta, &calc_load_tasks);
2635
dce48a84
TG
2636 active = atomic_long_read(&calc_load_tasks);
2637 active = active > 0 ? active * FIXED_1 : 0;
1da177e4 2638
dce48a84
TG
2639 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
2640 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
2641 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
dd41f596 2642
dce48a84 2643 calc_load_update += LOAD_FREQ;
c308b56b
PZ
2644
2645 /*
5167e8d5 2646 * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk.
c308b56b
PZ
2647 */
2648 calc_global_nohz();
dce48a84 2649}
1da177e4 2650
dce48a84 2651/*
74f5187a
PZ
2652 * Called from update_cpu_load() to periodically update this CPU's
2653 * active count.
dce48a84
TG
2654 */
2655static void calc_load_account_active(struct rq *this_rq)
2656{
74f5187a 2657 long delta;
08c183f3 2658
74f5187a
PZ
2659 if (time_before(jiffies, this_rq->calc_load_update))
2660 return;
783609c6 2661
74f5187a 2662 delta = calc_load_fold_active(this_rq);
74f5187a 2663 if (delta)
dce48a84 2664 atomic_long_add(delta, &calc_load_tasks);
74f5187a
PZ
2665
2666 this_rq->calc_load_update += LOAD_FREQ;
46cb4b7c
SS
2667}
2668
5167e8d5
PZ
2669/*
2670 * End of global load-average stuff
2671 */
2672
fdf3e95d
VP
2673/*
2674 * The exact cpuload at various idx values, calculated at every tick would be
2675 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
2676 *
2677 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
2678 * on nth tick when cpu may be busy, then we have:
2679 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2680 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
2681 *
2682 * decay_load_missed() below does efficient calculation of
2683 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2684 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
2685 *
2686 * The calculation is approximated on a 128 point scale.
2687 * degrade_zero_ticks is the number of ticks after which load at any
2688 * particular idx is approximated to be zero.
2689 * degrade_factor is a precomputed table, a row for each load idx.
2690 * Each column corresponds to degradation factor for a power of two ticks,
2691 * based on 128 point scale.
2692 * Example:
2693 * row 2, col 3 (=12) says that the degradation at load idx 2 after
2694 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
2695 *
2696 * With this power of 2 load factors, we can degrade the load n times
2697 * by looking at 1 bits in n and doing as many mult/shift instead of
2698 * n mult/shifts needed by the exact degradation.
2699 */
2700#define DEGRADE_SHIFT 7
2701static const unsigned char
2702 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
2703static const unsigned char
2704 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
2705 {0, 0, 0, 0, 0, 0, 0, 0},
2706 {64, 32, 8, 0, 0, 0, 0, 0},
2707 {96, 72, 40, 12, 1, 0, 0},
2708 {112, 98, 75, 43, 15, 1, 0},
2709 {120, 112, 98, 76, 45, 16, 2} };
2710
2711/*
2712 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
2713 * would be when CPU is idle and so we just decay the old load without
2714 * adding any new load.
2715 */
2716static unsigned long
2717decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
2718{
2719 int j = 0;
2720
2721 if (!missed_updates)
2722 return load;
2723
2724 if (missed_updates >= degrade_zero_ticks[idx])
2725 return 0;
2726
2727 if (idx == 1)
2728 return load >> missed_updates;
2729
2730 while (missed_updates) {
2731 if (missed_updates % 2)
2732 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
2733
2734 missed_updates >>= 1;
2735 j++;
2736 }
2737 return load;
2738}
2739
46cb4b7c 2740/*
dd41f596 2741 * Update rq->cpu_load[] statistics. This function is usually called every
fdf3e95d
VP
2742 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
2743 * every tick. We fix it up based on jiffies.
46cb4b7c 2744 */
556061b0
PZ
2745static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
2746 unsigned long pending_updates)
46cb4b7c 2747{
dd41f596 2748 int i, scale;
46cb4b7c 2749
dd41f596 2750 this_rq->nr_load_updates++;
46cb4b7c 2751
dd41f596 2752 /* Update our load: */
fdf3e95d
VP
2753 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
2754 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
dd41f596 2755 unsigned long old_load, new_load;
7d1e6a9b 2756
dd41f596 2757 /* scale is effectively 1 << i now, and >> i divides by scale */
46cb4b7c 2758
dd41f596 2759 old_load = this_rq->cpu_load[i];
fdf3e95d 2760 old_load = decay_load_missed(old_load, pending_updates - 1, i);
dd41f596 2761 new_load = this_load;
a25707f3
IM
2762 /*
2763 * Round up the averaging division if load is increasing. This
2764 * prevents us from getting stuck on 9 if the load is 10, for
2765 * example.
2766 */
2767 if (new_load > old_load)
fdf3e95d
VP
2768 new_load += scale - 1;
2769
2770 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
dd41f596 2771 }
da2b71ed
SS
2772
2773 sched_avg_update(this_rq);
fdf3e95d
VP
2774}
2775
6fa3eb70
S
2776# ifdef CONFIG_SMP
2777/* moved to kernel/sched/proc.c at Linux 3.11-rc4 */
2778static inline unsigned long get_rq_runnable_load(struct rq *rq)
2779{
2780 return rq->cfs.runnable_load_avg;
2781}
2782# else
2783static inline unsigned long get_rq_runnable_load(struct rq *rq)
2784{
2785 return rq->load.weight;
2786}
2787# endif
2788
3451d024 2789#ifdef CONFIG_NO_HZ_COMMON
5aaa0b7a
PZ
2790/*
2791 * There is no sane way to deal with nohz on smp when using jiffies because the
2792 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
2793 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
2794 *
2795 * Therefore we cannot use the delta approach from the regular tick since that
2796 * would seriously skew the load calculation. However we'll make do for those
2797 * updates happening while idle (nohz_idle_balance) or coming out of idle
2798 * (tick_nohz_idle_exit).
2799 *
2800 * This means we might still be one tick off for nohz periods.
2801 */
2802
556061b0
PZ
2803/*
2804 * Called from nohz_idle_balance() to update the load ratings before doing the
2805 * idle balance.
2806 */
6fa3eb70 2807/* moved to kernel/sched/proc.c at Linux 3.11-rc4 */
556061b0
PZ
2808void update_idle_cpu_load(struct rq *this_rq)
2809{
5aaa0b7a 2810 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
556061b0
PZ
2811 unsigned long load = this_rq->load.weight;
2812 unsigned long pending_updates;
2813
2814 /*
5aaa0b7a 2815 * bail if there's load or we're actually up-to-date.
556061b0
PZ
2816 */
2817 if (load || curr_jiffies == this_rq->last_load_update_tick)
2818 return;
2819
2820 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2821 this_rq->last_load_update_tick = curr_jiffies;
2822
2823 __update_cpu_load(this_rq, load, pending_updates);
2824}
2825
5aaa0b7a
PZ
2826/*
2827 * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
2828 */
6fa3eb70 2829/* moved to kernel/sched/proc.c at Linux 3.11-rc4 */
5aaa0b7a
PZ
2830void update_cpu_load_nohz(void)
2831{
2832 struct rq *this_rq = this_rq();
2833 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2834 unsigned long pending_updates;
2835
2836 if (curr_jiffies == this_rq->last_load_update_tick)
2837 return;
2838
2839 raw_spin_lock(&this_rq->lock);
2840 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2841 if (pending_updates) {
2842 this_rq->last_load_update_tick = curr_jiffies;
2843 /*
2844 * We were idle, this means load 0, the current load might be
2845 * !0 due to remote wakeups and the sort.
2846 */
2847 __update_cpu_load(this_rq, 0, pending_updates);
2848 }
2849 raw_spin_unlock(&this_rq->lock);
2850}
3451d024 2851#endif /* CONFIG_NO_HZ_COMMON */
5aaa0b7a 2852
556061b0
PZ
2853/*
2854 * Called from scheduler_tick()
2855 */
6fa3eb70 2856/* moved to kernel/sched/proc.c at Linux 3.11-rc4 */
fdf3e95d
VP
2857static void update_cpu_load_active(struct rq *this_rq)
2858{
6fa3eb70 2859 unsigned long load = get_rq_runnable_load(this_rq);
556061b0 2860 /*
5aaa0b7a 2861 * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
556061b0
PZ
2862 */
2863 this_rq->last_load_update_tick = jiffies;
6fa3eb70 2864 __update_cpu_load(this_rq, load, 1);
46cb4b7c 2865
74f5187a 2866 calc_load_account_active(this_rq);
46cb4b7c
SS
2867}
2868
dd41f596 2869#ifdef CONFIG_SMP
8a0be9ef 2870
46cb4b7c 2871/*
38022906
PZ
2872 * sched_exec - execve() is a valuable balancing opportunity, because at
2873 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 2874 */
38022906 2875void sched_exec(void)
46cb4b7c 2876{
38022906 2877 struct task_struct *p = current;
1da177e4 2878 unsigned long flags;
0017d735 2879 int dest_cpu;
46cb4b7c 2880
8f42ced9 2881 raw_spin_lock_irqsave(&p->pi_lock, flags);
7608dec2 2882 dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
0017d735
PZ
2883 if (dest_cpu == smp_processor_id())
2884 goto unlock;
38022906 2885
8f42ced9 2886 if (likely(cpu_active(dest_cpu))) {
969c7921 2887 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 2888
8f42ced9
PZ
2889 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2890 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
2891 return;
2892 }
0017d735 2893unlock:
8f42ced9 2894 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 2895}
dd41f596 2896
1da177e4
LT
2897#endif
2898
1da177e4 2899DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 2900DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
2901
2902EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 2903EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4
LT
2904
2905/*
c5f8d995 2906 * Return any ns on the sched_clock that have not yet been accounted in
f06febc9 2907 * @p in case that task is currently running.
c5f8d995
HS
2908 *
2909 * Called with task_rq_lock() held on @rq.
1da177e4 2910 */
c5f8d995
HS
2911static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
2912{
2913 u64 ns = 0;
2914
2915 if (task_current(rq, p)) {
2916 update_rq_clock(rq);
305e6835 2917 ns = rq->clock_task - p->se.exec_start;
c5f8d995
HS
2918 if ((s64)ns < 0)
2919 ns = 0;
2920 }
2921
2922 return ns;
2923}
2924
bb34d92f 2925unsigned long long task_delta_exec(struct task_struct *p)
1da177e4 2926{
1da177e4 2927 unsigned long flags;
41b86e9c 2928 struct rq *rq;
bb34d92f 2929 u64 ns = 0;
48f24c4d 2930
41b86e9c 2931 rq = task_rq_lock(p, &flags);
c5f8d995 2932 ns = do_task_delta_exec(p, rq);
0122ec5b 2933 task_rq_unlock(rq, p, &flags);
1508487e 2934
c5f8d995
HS
2935 return ns;
2936}
f06febc9 2937
c5f8d995
HS
2938/*
2939 * Return accounted runtime for the task.
2940 * In case the task is currently running, return the runtime plus current's
2941 * pending runtime that have not been accounted yet.
2942 */
2943unsigned long long task_sched_runtime(struct task_struct *p)
2944{
2945 unsigned long flags;
2946 struct rq *rq;
2947 u64 ns = 0;
2948
2949 rq = task_rq_lock(p, &flags);
2950 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
0122ec5b 2951 task_rq_unlock(rq, p, &flags);
c5f8d995
HS
2952
2953 return ns;
2954}
48f24c4d 2955
7835b98b
CL
2956/*
2957 * This function gets called by the timer code, with HZ frequency.
2958 * We call it with interrupts disabled.
7835b98b
CL
2959 */
2960void scheduler_tick(void)
2961{
7835b98b
CL
2962 int cpu = smp_processor_id();
2963 struct rq *rq = cpu_rq(cpu);
dd41f596 2964 struct task_struct *curr = rq->curr;
3e51f33f
PZ
2965
2966 sched_clock_tick();
dd41f596 2967
05fa785c 2968 raw_spin_lock(&rq->lock);
3e51f33f 2969 update_rq_clock(rq);
fa85ae24 2970 curr->sched_class->task_tick(rq, curr, 0);
6fa3eb70
S
2971 update_cpu_load_active(rq);
2972#ifdef CONFIG_MT_RT_SCHED
2973 mt_check_rt_policy(rq);
2974#endif
05fa785c 2975 raw_spin_unlock(&rq->lock);
7835b98b 2976
e9d2b064 2977 perf_event_task_tick();
6fa3eb70
S
2978#ifdef CONFIG_MT_SCHED_MONITOR
2979 if(smp_processor_id() == 0) //only record by CPU#0
2980 mt_save_irq_counts();
2981#endif
e418e1c2 2982#ifdef CONFIG_SMP
6eb57e0d 2983 rq->idle_balance = idle_cpu(cpu);
dd41f596 2984 trigger_load_balance(rq, cpu);
e418e1c2 2985#endif
265f22a9 2986 rq_last_tick_reset(rq);
1da177e4
LT
2987}
2988
265f22a9
FW
2989#ifdef CONFIG_NO_HZ_FULL
2990/**
2991 * scheduler_tick_max_deferment
2992 *
2993 * Keep at least one tick per second when a single
2994 * active task is running because the scheduler doesn't
2995 * yet completely support full dynticks environment.
2996 *
2997 * This makes sure that uptime, CFS vruntime, load
2998 * balancing, etc... continue to move forward, even
2999 * with a very low granularity.
3000 */
3001u64 scheduler_tick_max_deferment(void)
3002{
3003 struct rq *rq = this_rq();
3004 unsigned long next, now = ACCESS_ONCE(jiffies);
3005
3006 next = rq->last_sched_tick + HZ;
3007
3008 if (time_before_eq(next, now))
3009 return 0;
3010
3011 return jiffies_to_usecs(next - now) * NSEC_PER_USEC;
1da177e4 3012}
265f22a9 3013#endif
1da177e4 3014
132380a0 3015notrace unsigned long get_parent_ip(unsigned long addr)
6cd8a4bb
SR
3016{
3017 if (in_lock_functions(addr)) {
3018 addr = CALLER_ADDR2;
3019 if (in_lock_functions(addr))
3020 addr = CALLER_ADDR3;
3021 }
3022 return addr;
3023}
1da177e4 3024
7e49fcce
SR
3025#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3026 defined(CONFIG_PREEMPT_TRACER))
3027
43627582 3028void __kprobes add_preempt_count(int val)
1da177e4 3029{
6cd8a4bb 3030#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3031 /*
3032 * Underflow?
3033 */
9a11b49a
IM
3034 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3035 return;
6cd8a4bb 3036#endif
1da177e4 3037 preempt_count() += val;
6cd8a4bb 3038#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3039 /*
3040 * Spinlock count overflowing soon?
3041 */
33859f7f
MOS
3042 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3043 PREEMPT_MASK - 10);
6cd8a4bb 3044#endif
6fa3eb70
S
3045 //if (preempt_count() == val)
3046 // trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3047 if (preempt_count() == (val & ~PREEMPT_ACTIVE)){
3048#ifdef CONFIG_PREEMPT_TRACER
3049 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3050#endif
3051#ifdef CONFIG_PREEMPT_MONITOR
3052 if(unlikely(__raw_get_cpu_var(mtsched_mon_enabled) & 0x1)){
3053 //current->t_add_prmpt = sched_clock();
3054 MT_trace_preempt_off();
3055 }
3056#endif
3057 }
1da177e4
LT
3058}
3059EXPORT_SYMBOL(add_preempt_count);
3060
43627582 3061void __kprobes sub_preempt_count(int val)
1da177e4 3062{
6cd8a4bb 3063#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3064 /*
3065 * Underflow?
3066 */
01e3eb82 3067 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 3068 return;
1da177e4
LT
3069 /*
3070 * Is the spinlock portion underflowing?
3071 */
9a11b49a
IM
3072 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3073 !(preempt_count() & PREEMPT_MASK)))
3074 return;
6cd8a4bb 3075#endif
9a11b49a 3076
6fa3eb70
S
3077 //if (preempt_count() == val)
3078 // trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3079 if (preempt_count() == (val & ~PREEMPT_ACTIVE)){
3080#ifdef CONFIG_PREEMPT_TRACER
3081 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3082#endif
3083#ifdef CONFIG_PREEMPT_MONITOR
3084 if(unlikely(__raw_get_cpu_var(mtsched_mon_enabled) & 0x1)){
3085 MT_trace_preempt_on();
3086 }
3087#endif
3088 }
1da177e4
LT
3089 preempt_count() -= val;
3090}
3091EXPORT_SYMBOL(sub_preempt_count);
3092
3093#endif
3094
3095/*
dd41f596 3096 * Print scheduling while atomic bug:
1da177e4 3097 */
dd41f596 3098static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 3099{
664dfa65
DJ
3100 if (oops_in_progress)
3101 return;
3102
3df0fc5b
PZ
3103 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3104 prev->comm, prev->pid, preempt_count());
838225b4 3105
dd41f596 3106 debug_show_held_locks(prev);
e21f5b15 3107 print_modules();
dd41f596
IM
3108 if (irqs_disabled())
3109 print_irqtrace_events(prev);
6135fc1e 3110 dump_stack();
373d4d09 3111 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6fa3eb70 3112 BUG_ON(1);
dd41f596 3113}
1da177e4 3114
dd41f596
IM
3115/*
3116 * Various schedule()-time debugging checks and statistics:
3117 */
3118static inline void schedule_debug(struct task_struct *prev)
3119{
1da177e4 3120 /*
41a2d6cf 3121 * Test if we are atomic. Since do_exit() needs to call into
1da177e4
LT
3122 * schedule() atomically, we ignore that path for now.
3123 * Otherwise, whine if we are scheduling when we should not be.
3124 */
3f33a7ce 3125 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
dd41f596 3126 __schedule_bug(prev);
b3fbab05 3127 rcu_sleep_check();
dd41f596 3128
1da177e4
LT
3129 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3130
2d72376b 3131 schedstat_inc(this_rq(), sched_count);
dd41f596
IM
3132}
3133
6cecd084 3134static void put_prev_task(struct rq *rq, struct task_struct *prev)
df1c99d4 3135{
61eadef6 3136 if (prev->on_rq || rq->skip_clock_update < 0)
a64692a3 3137 update_rq_clock(rq);
6cecd084 3138 prev->sched_class->put_prev_task(rq, prev);
df1c99d4
MG
3139}
3140
dd41f596
IM
3141/*
3142 * Pick up the highest-prio task:
3143 */
3144static inline struct task_struct *
b67802ea 3145pick_next_task(struct rq *rq)
dd41f596 3146{
5522d5d5 3147 const struct sched_class *class;
dd41f596 3148 struct task_struct *p;
1da177e4
LT
3149
3150 /*
dd41f596
IM
3151 * Optimization: we know that if all tasks are in
3152 * the fair class we can call that function directly:
1da177e4 3153 */
953bfcd1 3154 if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
fb8d4724 3155 p = fair_sched_class.pick_next_task(rq);
dd41f596
IM
3156 if (likely(p))
3157 return p;
1da177e4
LT
3158 }
3159
34f971f6 3160 for_each_class(class) {
fb8d4724 3161 p = class->pick_next_task(rq);
dd41f596
IM
3162 if (p)
3163 return p;
dd41f596 3164 }
34f971f6
PZ
3165
3166 BUG(); /* the idle class will always have a runnable task */
dd41f596 3167}
1da177e4 3168
dd41f596 3169/*
c259e01a 3170 * __schedule() is the main scheduler function.
edde96ea
PE
3171 *
3172 * The main means of driving the scheduler and thus entering this function are:
3173 *
3174 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3175 *
3176 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3177 * paths. For example, see arch/x86/entry_64.S.
3178 *
3179 * To drive preemption between tasks, the scheduler sets the flag in timer
3180 * interrupt handler scheduler_tick().
3181 *
3182 * 3. Wakeups don't really cause entry into schedule(). They add a
3183 * task to the run-queue and that's it.
3184 *
3185 * Now, if the new task added to the run-queue preempts the current
3186 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3187 * called on the nearest possible occasion:
3188 *
3189 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3190 *
3191 * - in syscall or exception context, at the next outmost
3192 * preempt_enable(). (this might be as soon as the wake_up()'s
3193 * spin_unlock()!)
3194 *
3195 * - in IRQ context, return from interrupt-handler to
3196 * preemptible context
3197 *
3198 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3199 * then at the next:
3200 *
3201 * - cond_resched() call
3202 * - explicit schedule() call
3203 * - return from syscall or exception to user-space
3204 * - return from interrupt-handler to user-space
dd41f596 3205 */
c259e01a 3206static void __sched __schedule(void)
dd41f596
IM
3207{
3208 struct task_struct *prev, *next;
67ca7bde 3209 unsigned long *switch_count;
dd41f596 3210 struct rq *rq;
31656519 3211 int cpu;
dd41f596 3212
ff743345
PZ
3213need_resched:
3214 preempt_disable();
dd41f596
IM
3215 cpu = smp_processor_id();
3216 rq = cpu_rq(cpu);
25502a6c 3217 rcu_note_context_switch(cpu);
dd41f596 3218 prev = rq->curr;
dd41f596 3219
dd41f596 3220 schedule_debug(prev);
1da177e4 3221
31656519 3222 if (sched_feat(HRTICK))
f333fdc9 3223 hrtick_clear(rq);
6fa3eb70
S
3224#ifdef CONFIG_MT_SCHED_MONITOR
3225 __raw_get_cpu_var(MT_trace_in_sched) = 1;
3226#endif
8f4d37ec 3227
57f74b6e
ON
3228 /*
3229 * Make sure that signal_pending_state()->signal_pending() below
3230 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3231 * done by the caller to avoid the race with signal_wake_up().
3232 */
3233 smp_mb__before_spinlock();
05fa785c 3234 raw_spin_lock_irq(&rq->lock);
1da177e4 3235
246d86b5 3236 switch_count = &prev->nivcsw;
1da177e4 3237 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
21aa9af0 3238 if (unlikely(signal_pending_state(prev->state, prev))) {
1da177e4 3239 prev->state = TASK_RUNNING;
21aa9af0 3240 } else {
2acca55e
PZ
3241 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3242 prev->on_rq = 0;
3243
21aa9af0 3244 /*
2acca55e
PZ
3245 * If a worker went to sleep, notify and ask workqueue
3246 * whether it wants to wake up a task to maintain
3247 * concurrency.
21aa9af0
TH
3248 */
3249 if (prev->flags & PF_WQ_WORKER) {
3250 struct task_struct *to_wakeup;
3251
3252 to_wakeup = wq_worker_sleeping(prev, cpu);
3253 if (to_wakeup)
3254 try_to_wake_up_local(to_wakeup);
3255 }
21aa9af0 3256 }
dd41f596 3257 switch_count = &prev->nvcsw;
1da177e4
LT
3258 }
3259
3f029d3c 3260 pre_schedule(rq, prev);
f65eda4f 3261
dd41f596 3262 if (unlikely(!rq->nr_running))
1da177e4 3263 idle_balance(cpu, rq);
1da177e4 3264
df1c99d4 3265 put_prev_task(rq, prev);
b67802ea 3266 next = pick_next_task(rq);
f26f9aff
MG
3267 clear_tsk_need_resched(prev);
3268 rq->skip_clock_update = 0;
1da177e4 3269
1da177e4 3270 if (likely(prev != next)) {
1da177e4
LT
3271 rq->nr_switches++;
3272 rq->curr = next;
3273 ++*switch_count;
3274
dd41f596 3275 context_switch(rq, prev, next); /* unlocks the rq */
8f4d37ec 3276 /*
246d86b5
ON
3277 * The context switch have flipped the stack from under us
3278 * and restored the local variables which were saved when
3279 * this task called schedule() in the past. prev == current
3280 * is still correct, but it can be moved to another cpu/rq.
8f4d37ec
PZ
3281 */
3282 cpu = smp_processor_id();
3283 rq = cpu_rq(cpu);
1da177e4 3284 } else
05fa785c 3285 raw_spin_unlock_irq(&rq->lock);
1da177e4 3286
6fa3eb70
S
3287#ifdef CONFIG_MT_RT_SCHED
3288 mt_post_schedule(rq);
3289#endif
3290#ifdef CONFIG_MT_SCHED_MONITOR
3291 __raw_get_cpu_var(MT_trace_in_sched) = 0;
3292#endif
3f029d3c 3293 post_schedule(rq);
1da177e4 3294
ba74c144 3295 sched_preempt_enable_no_resched();
ff743345 3296 if (need_resched())
1da177e4
LT
3297 goto need_resched;
3298}
c259e01a 3299
9c40cef2
TG
3300static inline void sched_submit_work(struct task_struct *tsk)
3301{
3c7d5184 3302 if (!tsk->state || tsk_is_pi_blocked(tsk))
9c40cef2
TG
3303 return;
3304 /*
3305 * If we are going to sleep and we have plugged IO queued,
3306 * make sure to submit it to avoid deadlocks.
3307 */
3308 if (blk_needs_flush_plug(tsk))
3309 blk_schedule_flush_plug(tsk);
3310}
3311
6ebbe7a0 3312asmlinkage void __sched schedule(void)
c259e01a 3313{
9c40cef2
TG
3314 struct task_struct *tsk = current;
3315
3316 sched_submit_work(tsk);
c259e01a
TG
3317 __schedule();
3318}
1da177e4
LT
3319EXPORT_SYMBOL(schedule);
3320
91d1aa43 3321#ifdef CONFIG_CONTEXT_TRACKING
20ab65e3
FW
3322asmlinkage void __sched schedule_user(void)
3323{
3324 /*
3325 * If we come here after a random call to set_need_resched(),
3326 * or we have been woken up remotely but the IPI has not yet arrived,
3327 * we haven't yet exited the RCU idle mode. Do it here manually until
3328 * we find a better solution.
3329 */
91d1aa43 3330 user_exit();
20ab65e3 3331 schedule();
91d1aa43 3332 user_enter();
20ab65e3
FW
3333}
3334#endif
3335
c5491ea7
TG
3336/**
3337 * schedule_preempt_disabled - called with preemption disabled
3338 *
3339 * Returns with preemption disabled. Note: preempt_count must be 1
3340 */
3341void __sched schedule_preempt_disabled(void)
3342{
ba74c144 3343 sched_preempt_enable_no_resched();
c5491ea7
TG
3344 schedule();
3345 preempt_disable();
3346}
3347
1da177e4
LT
3348#ifdef CONFIG_PREEMPT
3349/*
2ed6e34f 3350 * this is the entry point to schedule() from in-kernel preemption
41a2d6cf 3351 * off of preempt_enable. Kernel preemptions off return from interrupt
1da177e4
LT
3352 * occur there and call schedule directly.
3353 */
d1f74e20 3354asmlinkage void __sched notrace preempt_schedule(void)
1da177e4
LT
3355{
3356 struct thread_info *ti = current_thread_info();
6478d880 3357
1da177e4
LT
3358 /*
3359 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 3360 * we do not want to preempt the current task. Just return..
1da177e4 3361 */
beed33a8 3362 if (likely(ti->preempt_count || irqs_disabled()))
1da177e4
LT
3363 return;
3364
3a5c359a 3365 do {
d1f74e20 3366 add_preempt_count_notrace(PREEMPT_ACTIVE);
c259e01a 3367 __schedule();
d1f74e20 3368 sub_preempt_count_notrace(PREEMPT_ACTIVE);
1da177e4 3369
3a5c359a
AK
3370 /*
3371 * Check again in case we missed a preemption opportunity
3372 * between schedule and now.
3373 */
3374 barrier();
5ed0cec0 3375 } while (need_resched());
1da177e4 3376}
1da177e4
LT
3377EXPORT_SYMBOL(preempt_schedule);
3378
3379/*
2ed6e34f 3380 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3381 * off of irq context.
3382 * Note, that this is called and return with irqs disabled. This will
3383 * protect us against recursive calling from irq.
3384 */
3385asmlinkage void __sched preempt_schedule_irq(void)
3386{
3387 struct thread_info *ti = current_thread_info();
b22366cd 3388 enum ctx_state prev_state;
6478d880 3389
2ed6e34f 3390 /* Catch callers which need to be fixed */
1da177e4
LT
3391 BUG_ON(ti->preempt_count || !irqs_disabled());
3392
b22366cd
FW
3393 prev_state = exception_enter();
3394
3a5c359a
AK
3395 do {
3396 add_preempt_count(PREEMPT_ACTIVE);
3a5c359a 3397 local_irq_enable();
c259e01a 3398 __schedule();
3a5c359a 3399 local_irq_disable();
3a5c359a 3400 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4 3401
3a5c359a
AK
3402 /*
3403 * Check again in case we missed a preemption opportunity
3404 * between schedule and now.
3405 */
3406 barrier();
5ed0cec0 3407 } while (need_resched());
b22366cd
FW
3408
3409 exception_exit(prev_state);
1da177e4
LT
3410}
3411
3412#endif /* CONFIG_PREEMPT */
3413
63859d4f 3414int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
95cdf3b7 3415 void *key)
1da177e4 3416{
63859d4f 3417 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 3418}
1da177e4
LT
3419EXPORT_SYMBOL(default_wake_function);
3420
3421/*
41a2d6cf
IM
3422 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3423 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
1da177e4
LT
3424 * number) then we wake all the non-exclusive tasks and one exclusive task.
3425 *
3426 * There are circumstances in which we can try to wake a task which has already
41a2d6cf 3427 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
1da177e4
LT
3428 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3429 */
78ddb08f 3430static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
63859d4f 3431 int nr_exclusive, int wake_flags, void *key)
1da177e4 3432{
2e45874c 3433 wait_queue_t *curr, *next;
1da177e4 3434
2e45874c 3435 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
48f24c4d
IM
3436 unsigned flags = curr->flags;
3437
63859d4f 3438 if (curr->func(curr, mode, wake_flags, key) &&
48f24c4d 3439 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
1da177e4
LT
3440 break;
3441 }
3442}
3443
3444/**
3445 * __wake_up - wake up threads blocked on a waitqueue.
3446 * @q: the waitqueue
3447 * @mode: which threads
3448 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 3449 * @key: is directly passed to the wakeup function
50fa610a
DH
3450 *
3451 * It may be assumed that this function implies a write memory barrier before
3452 * changing the task state if and only if any tasks are woken up.
1da177e4 3453 */
7ad5b3a5 3454void __wake_up(wait_queue_head_t *q, unsigned int mode,
95cdf3b7 3455 int nr_exclusive, void *key)
1da177e4
LT
3456{
3457 unsigned long flags;
3458
3459 spin_lock_irqsave(&q->lock, flags);
3460 __wake_up_common(q, mode, nr_exclusive, 0, key);
3461 spin_unlock_irqrestore(&q->lock, flags);
3462}
1da177e4
LT
3463EXPORT_SYMBOL(__wake_up);
3464
3465/*
3466 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3467 */
63b20011 3468void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr)
1da177e4 3469{
63b20011 3470 __wake_up_common(q, mode, nr, 0, NULL);
1da177e4 3471}
22c43c81 3472EXPORT_SYMBOL_GPL(__wake_up_locked);
1da177e4 3473
4ede816a
DL
3474void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
3475{
3476 __wake_up_common(q, mode, 1, 0, key);
3477}
bf294b41 3478EXPORT_SYMBOL_GPL(__wake_up_locked_key);
4ede816a 3479
1da177e4 3480/**
4ede816a 3481 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
1da177e4
LT
3482 * @q: the waitqueue
3483 * @mode: which threads
3484 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4ede816a 3485 * @key: opaque value to be passed to wakeup targets
1da177e4
LT
3486 *
3487 * The sync wakeup differs that the waker knows that it will schedule
3488 * away soon, so while the target thread will be woken up, it will not
3489 * be migrated to another CPU - ie. the two threads are 'synchronized'
3490 * with each other. This can prevent needless bouncing between CPUs.
3491 *
3492 * On UP it can prevent extra preemption.
50fa610a
DH
3493 *
3494 * It may be assumed that this function implies a write memory barrier before
3495 * changing the task state if and only if any tasks are woken up.
1da177e4 3496 */
4ede816a
DL
3497void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
3498 int nr_exclusive, void *key)
1da177e4
LT
3499{
3500 unsigned long flags;
7d478721 3501 int wake_flags = WF_SYNC;
1da177e4
LT
3502
3503 if (unlikely(!q))
3504 return;
3505
3506 if (unlikely(!nr_exclusive))
7d478721 3507 wake_flags = 0;
1da177e4
LT
3508
3509 spin_lock_irqsave(&q->lock, flags);
7d478721 3510 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
1da177e4
LT
3511 spin_unlock_irqrestore(&q->lock, flags);
3512}
4ede816a
DL
3513EXPORT_SYMBOL_GPL(__wake_up_sync_key);
3514
3515/*
3516 * __wake_up_sync - see __wake_up_sync_key()
3517 */
3518void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3519{
3520 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
3521}
1da177e4
LT
3522EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3523
65eb3dc6
KD
3524/**
3525 * complete: - signals a single thread waiting on this completion
3526 * @x: holds the state of this particular completion
3527 *
3528 * This will wake up a single thread waiting on this completion. Threads will be
3529 * awakened in the same order in which they were queued.
3530 *
3531 * See also complete_all(), wait_for_completion() and related routines.
50fa610a
DH
3532 *
3533 * It may be assumed that this function implies a write memory barrier before
3534 * changing the task state if and only if any tasks are woken up.
65eb3dc6 3535 */
b15136e9 3536void complete(struct completion *x)
1da177e4
LT
3537{
3538 unsigned long flags;
3539
3540 spin_lock_irqsave(&x->wait.lock, flags);
3541 x->done++;
d9514f6c 3542 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
1da177e4
LT
3543 spin_unlock_irqrestore(&x->wait.lock, flags);
3544}
3545EXPORT_SYMBOL(complete);
3546
65eb3dc6
KD
3547/**
3548 * complete_all: - signals all threads waiting on this completion
3549 * @x: holds the state of this particular completion
3550 *
3551 * This will wake up all threads waiting on this particular completion event.
50fa610a
DH
3552 *
3553 * It may be assumed that this function implies a write memory barrier before
3554 * changing the task state if and only if any tasks are woken up.
65eb3dc6 3555 */
b15136e9 3556void complete_all(struct completion *x)
1da177e4
LT
3557{
3558 unsigned long flags;
3559
3560 spin_lock_irqsave(&x->wait.lock, flags);
3561 x->done += UINT_MAX/2;
d9514f6c 3562 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
1da177e4
LT
3563 spin_unlock_irqrestore(&x->wait.lock, flags);
3564}
3565EXPORT_SYMBOL(complete_all);
3566
8cbbe86d 3567static inline long __sched
686855f5
VD
3568do_wait_for_common(struct completion *x,
3569 long (*action)(long), long timeout, int state)
1da177e4 3570{
1da177e4
LT
3571 if (!x->done) {
3572 DECLARE_WAITQUEUE(wait, current);
3573
a93d2f17 3574 __add_wait_queue_tail_exclusive(&x->wait, &wait);
1da177e4 3575 do {
94d3d824 3576 if (signal_pending_state(state, current)) {
ea71a546
ON
3577 timeout = -ERESTARTSYS;
3578 break;
8cbbe86d
AK
3579 }
3580 __set_current_state(state);
1da177e4 3581 spin_unlock_irq(&x->wait.lock);
686855f5 3582 timeout = action(timeout);
1da177e4 3583 spin_lock_irq(&x->wait.lock);
ea71a546 3584 } while (!x->done && timeout);
1da177e4 3585 __remove_wait_queue(&x->wait, &wait);
ea71a546
ON
3586 if (!x->done)
3587 return timeout;
1da177e4
LT
3588 }
3589 x->done--;
ea71a546 3590 return timeout ?: 1;
1da177e4 3591}
1da177e4 3592
686855f5
VD
3593static inline long __sched
3594__wait_for_common(struct completion *x,
3595 long (*action)(long), long timeout, int state)
1da177e4 3596{
1da177e4
LT
3597 might_sleep();
3598
3599 spin_lock_irq(&x->wait.lock);
686855f5 3600 timeout = do_wait_for_common(x, action, timeout, state);
1da177e4 3601 spin_unlock_irq(&x->wait.lock);
8cbbe86d
AK
3602 return timeout;
3603}
1da177e4 3604
686855f5
VD
3605static long __sched
3606wait_for_common(struct completion *x, long timeout, int state)
3607{
3608 return __wait_for_common(x, schedule_timeout, timeout, state);
3609}
3610
3611static long __sched
3612wait_for_common_io(struct completion *x, long timeout, int state)
3613{
3614 return __wait_for_common(x, io_schedule_timeout, timeout, state);
3615}
3616
65eb3dc6
KD
3617/**
3618 * wait_for_completion: - waits for completion of a task
3619 * @x: holds the state of this particular completion
3620 *
3621 * This waits to be signaled for completion of a specific task. It is NOT
3622 * interruptible and there is no timeout.
3623 *
3624 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
3625 * and interrupt capability. Also see complete().
3626 */
b15136e9 3627void __sched wait_for_completion(struct completion *x)
8cbbe86d
AK
3628{
3629 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
1da177e4 3630}
8cbbe86d 3631EXPORT_SYMBOL(wait_for_completion);
1da177e4 3632
65eb3dc6
KD
3633/**
3634 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
3635 * @x: holds the state of this particular completion
3636 * @timeout: timeout value in jiffies
3637 *
3638 * This waits for either a completion of a specific task to be signaled or for a
3639 * specified timeout to expire. The timeout is in jiffies. It is not
3640 * interruptible.
c6dc7f05
BF
3641 *
3642 * The return value is 0 if timed out, and positive (at least 1, or number of
3643 * jiffies left till timeout) if completed.
65eb3dc6 3644 */
b15136e9 3645unsigned long __sched
8cbbe86d 3646wait_for_completion_timeout(struct completion *x, unsigned long timeout)
1da177e4 3647{
8cbbe86d 3648 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
1da177e4 3649}
8cbbe86d 3650EXPORT_SYMBOL(wait_for_completion_timeout);
1da177e4 3651
686855f5
VD
3652/**
3653 * wait_for_completion_io: - waits for completion of a task
3654 * @x: holds the state of this particular completion
3655 *
3656 * This waits to be signaled for completion of a specific task. It is NOT
3657 * interruptible and there is no timeout. The caller is accounted as waiting
3658 * for IO.
3659 */
3660void __sched wait_for_completion_io(struct completion *x)
3661{
3662 wait_for_common_io(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3663}
3664EXPORT_SYMBOL(wait_for_completion_io);
3665
3666/**
3667 * wait_for_completion_io_timeout: - waits for completion of a task (w/timeout)
3668 * @x: holds the state of this particular completion
3669 * @timeout: timeout value in jiffies
3670 *
3671 * This waits for either a completion of a specific task to be signaled or for a
3672 * specified timeout to expire. The timeout is in jiffies. It is not
3673 * interruptible. The caller is accounted as waiting for IO.
3674 *
3675 * The return value is 0 if timed out, and positive (at least 1, or number of
3676 * jiffies left till timeout) if completed.
3677 */
3678unsigned long __sched
3679wait_for_completion_io_timeout(struct completion *x, unsigned long timeout)
3680{
3681 return wait_for_common_io(x, timeout, TASK_UNINTERRUPTIBLE);
3682}
3683EXPORT_SYMBOL(wait_for_completion_io_timeout);
3684
65eb3dc6
KD
3685/**
3686 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
3687 * @x: holds the state of this particular completion
3688 *
3689 * This waits for completion of a specific task to be signaled. It is
3690 * interruptible.
c6dc7f05
BF
3691 *
3692 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
65eb3dc6 3693 */
8cbbe86d 3694int __sched wait_for_completion_interruptible(struct completion *x)
0fec171c 3695{
51e97990
AK
3696 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3697 if (t == -ERESTARTSYS)
3698 return t;
3699 return 0;
0fec171c 3700}
8cbbe86d 3701EXPORT_SYMBOL(wait_for_completion_interruptible);
1da177e4 3702
65eb3dc6
KD
3703/**
3704 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
3705 * @x: holds the state of this particular completion
3706 * @timeout: timeout value in jiffies
3707 *
3708 * This waits for either a completion of a specific task to be signaled or for a
3709 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
c6dc7f05
BF
3710 *
3711 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3712 * positive (at least 1, or number of jiffies left till timeout) if completed.
65eb3dc6 3713 */
6bf41237 3714long __sched
8cbbe86d
AK
3715wait_for_completion_interruptible_timeout(struct completion *x,
3716 unsigned long timeout)
0fec171c 3717{
8cbbe86d 3718 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
0fec171c 3719}
8cbbe86d 3720EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
1da177e4 3721
65eb3dc6
KD
3722/**
3723 * wait_for_completion_killable: - waits for completion of a task (killable)
3724 * @x: holds the state of this particular completion
3725 *
3726 * This waits to be signaled for completion of a specific task. It can be
3727 * interrupted by a kill signal.
c6dc7f05
BF
3728 *
3729 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
65eb3dc6 3730 */
009e577e
MW
3731int __sched wait_for_completion_killable(struct completion *x)
3732{
3733 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
3734 if (t == -ERESTARTSYS)
3735 return t;
3736 return 0;
3737}
3738EXPORT_SYMBOL(wait_for_completion_killable);
3739
0aa12fb4
SW
3740/**
3741 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
3742 * @x: holds the state of this particular completion
3743 * @timeout: timeout value in jiffies
3744 *
3745 * This waits for either a completion of a specific task to be
3746 * signaled or for a specified timeout to expire. It can be
3747 * interrupted by a kill signal. The timeout is in jiffies.
c6dc7f05
BF
3748 *
3749 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3750 * positive (at least 1, or number of jiffies left till timeout) if completed.
0aa12fb4 3751 */
6bf41237 3752long __sched
0aa12fb4
SW
3753wait_for_completion_killable_timeout(struct completion *x,
3754 unsigned long timeout)
3755{
3756 return wait_for_common(x, timeout, TASK_KILLABLE);
3757}
3758EXPORT_SYMBOL(wait_for_completion_killable_timeout);
3759
be4de352
DC
3760/**
3761 * try_wait_for_completion - try to decrement a completion without blocking
3762 * @x: completion structure
3763 *
3764 * Returns: 0 if a decrement cannot be done without blocking
3765 * 1 if a decrement succeeded.
3766 *
3767 * If a completion is being used as a counting completion,
3768 * attempt to decrement the counter without blocking. This
3769 * enables us to avoid waiting if the resource the completion
3770 * is protecting is not available.
3771 */
3772bool try_wait_for_completion(struct completion *x)
3773{
7539a3b3 3774 unsigned long flags;
be4de352
DC
3775 int ret = 1;
3776
7539a3b3 3777 spin_lock_irqsave(&x->wait.lock, flags);
be4de352
DC
3778 if (!x->done)
3779 ret = 0;
3780 else
3781 x->done--;
7539a3b3 3782 spin_unlock_irqrestore(&x->wait.lock, flags);
be4de352
DC
3783 return ret;
3784}
3785EXPORT_SYMBOL(try_wait_for_completion);
3786
3787/**
3788 * completion_done - Test to see if a completion has any waiters
3789 * @x: completion structure
3790 *
3791 * Returns: 0 if there are waiters (wait_for_completion() in progress)
3792 * 1 if there are no waiters.
3793 *
3794 */
3795bool completion_done(struct completion *x)
3796{
7539a3b3 3797 unsigned long flags;
be4de352
DC
3798 int ret = 1;
3799
7539a3b3 3800 spin_lock_irqsave(&x->wait.lock, flags);
be4de352
DC
3801 if (!x->done)
3802 ret = 0;
7539a3b3 3803 spin_unlock_irqrestore(&x->wait.lock, flags);
be4de352
DC
3804 return ret;
3805}
3806EXPORT_SYMBOL(completion_done);
3807
8cbbe86d
AK
3808static long __sched
3809sleep_on_common(wait_queue_head_t *q, int state, long timeout)
1da177e4 3810{
0fec171c
IM
3811 unsigned long flags;
3812 wait_queue_t wait;
3813
3814 init_waitqueue_entry(&wait, current);
1da177e4 3815
8cbbe86d 3816 __set_current_state(state);
1da177e4 3817
8cbbe86d
AK
3818 spin_lock_irqsave(&q->lock, flags);
3819 __add_wait_queue(q, &wait);
3820 spin_unlock(&q->lock);
3821 timeout = schedule_timeout(timeout);
3822 spin_lock_irq(&q->lock);
3823 __remove_wait_queue(q, &wait);
3824 spin_unlock_irqrestore(&q->lock, flags);
3825
3826 return timeout;
3827}
3828
3829void __sched interruptible_sleep_on(wait_queue_head_t *q)
3830{
3831 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3832}
1da177e4
LT
3833EXPORT_SYMBOL(interruptible_sleep_on);
3834
0fec171c 3835long __sched
95cdf3b7 3836interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3837{
8cbbe86d 3838 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
1da177e4 3839}
1da177e4
LT
3840EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3841
0fec171c 3842void __sched sleep_on(wait_queue_head_t *q)
1da177e4 3843{
8cbbe86d 3844 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3845}
1da177e4
LT
3846EXPORT_SYMBOL(sleep_on);
3847
0fec171c 3848long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3849{
8cbbe86d 3850 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
1da177e4 3851}
1da177e4
LT
3852EXPORT_SYMBOL(sleep_on_timeout);
3853
b29739f9
IM
3854#ifdef CONFIG_RT_MUTEXES
3855
3856/*
3857 * rt_mutex_setprio - set the current priority of a task
3858 * @p: task
3859 * @prio: prio value (kernel-internal form)
3860 *
3861 * This function changes the 'effective' priority of a task. It does
3862 * not touch ->normal_prio like __setscheduler().
3863 *
3864 * Used by the rt_mutex code to implement priority inheritance logic.
3865 */
36c8b586 3866void rt_mutex_setprio(struct task_struct *p, int prio)
b29739f9 3867{
83b699ed 3868 int oldprio, on_rq, running;
70b97a7f 3869 struct rq *rq;
83ab0aa0 3870 const struct sched_class *prev_class;
b29739f9
IM
3871
3872 BUG_ON(prio < 0 || prio > MAX_PRIO);
3873
0122ec5b 3874 rq = __task_rq_lock(p);
b29739f9 3875
1c4dd99b
TG
3876 /*
3877 * Idle task boosting is a nono in general. There is one
3878 * exception, when PREEMPT_RT and NOHZ is active:
3879 *
3880 * The idle task calls get_next_timer_interrupt() and holds
3881 * the timer wheel base->lock on the CPU and another CPU wants
3882 * to access the timer (probably to cancel it). We can safely
3883 * ignore the boosting request, as the idle CPU runs this code
3884 * with interrupts disabled and will complete the lock
3885 * protected section without being interrupted. So there is no
3886 * real need to boost.
3887 */
3888 if (unlikely(p == rq->idle)) {
3889 WARN_ON(p != rq->curr);
3890 WARN_ON(p->pi_blocked_on);
3891 goto out_unlock;
3892 }
3893
a8027073 3894 trace_sched_pi_setprio(p, prio);
d5f9f942 3895 oldprio = p->prio;
83ab0aa0 3896 prev_class = p->sched_class;
fd2f4419 3897 on_rq = p->on_rq;
051a1d1a 3898 running = task_current(rq, p);
0e1f3483 3899 if (on_rq)
69be72c1 3900 dequeue_task(rq, p, 0);
0e1f3483
HS
3901 if (running)
3902 p->sched_class->put_prev_task(rq, p);
dd41f596
IM
3903
3904 if (rt_prio(prio))
3905 p->sched_class = &rt_sched_class;
3906 else
3907 p->sched_class = &fair_sched_class;
3908
b29739f9
IM
3909 p->prio = prio;
3910
0e1f3483
HS
3911 if (running)
3912 p->sched_class->set_curr_task(rq);
da7a735e 3913 if (on_rq)
371fd7e7 3914 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
cb469845 3915
da7a735e 3916 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 3917out_unlock:
0122ec5b 3918 __task_rq_unlock(rq);
b29739f9 3919}
b29739f9 3920#endif
6fa3eb70
S
3921
3922#ifdef CONFIG_MT_PRIO_TRACER
3923void set_user_nice_core(struct task_struct *p, long nice)
3924{
3925 int old_prio, delta, on_rq;
3926 unsigned long flags;
3927 struct rq *rq;
3928
3929 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3930 return;
3931 /*
3932 * We have to be careful, if called from sys_setpriority(),
3933 * the task might be in the middle of scheduling on another CPU.
3934 */
3935 rq = task_rq_lock(p, &flags);
3936 /*
3937 * The RT priorities are set via sched_setscheduler(), but we still
3938 * allow the 'normal' nice value to be set - but as expected
3939 * it wont have any effect on scheduling until the task is
3940 * SCHED_FIFO/SCHED_RR:
3941 */
3942 if (task_has_rt_policy(p)) {
3943 p->static_prio = NICE_TO_PRIO(nice);
3944 goto out_unlock;
3945 }
3946 on_rq = p->on_rq;
3947 if (on_rq)
3948 dequeue_task(rq, p, 0);
3949
3950 p->static_prio = NICE_TO_PRIO(nice);
3951 set_load_weight(p);
3952 old_prio = p->prio;
3953 p->prio = effective_prio(p);
3954 delta = p->prio - old_prio;
3955
3956 if (on_rq) {
3957 enqueue_task(rq, p, 0);
3958 /*
3959 * If the task increased its priority or is running and
3960 * lowered its priority, then reschedule its CPU:
3961 */
3962 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3963 resched_task(rq->curr);
3964 }
3965out_unlock:
3966 task_rq_unlock(rq, p, &flags);
3967}
3968
3969void set_user_nice(struct task_struct *p, long nice)
3970{
3971 set_user_nice_core(p, nice);
3972 /* setting nice implies to set a normal sched policy */
3973 update_prio_tracer(task_pid_nr(p), NICE_TO_PRIO(nice), 0, PTS_KRNL);
3974}
3975#else /* !CONFIG_MT_PRIO_TRACER */
36c8b586 3976void set_user_nice(struct task_struct *p, long nice)
1da177e4 3977{
dd41f596 3978 int old_prio, delta, on_rq;
1da177e4 3979 unsigned long flags;
70b97a7f 3980 struct rq *rq;
1da177e4
LT
3981
3982 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3983 return;
3984 /*
3985 * We have to be careful, if called from sys_setpriority(),
3986 * the task might be in the middle of scheduling on another CPU.
3987 */
3988 rq = task_rq_lock(p, &flags);
3989 /*
3990 * The RT priorities are set via sched_setscheduler(), but we still
3991 * allow the 'normal' nice value to be set - but as expected
3992 * it wont have any effect on scheduling until the task is
dd41f596 3993 * SCHED_FIFO/SCHED_RR:
1da177e4 3994 */
e05606d3 3995 if (task_has_rt_policy(p)) {
1da177e4
LT
3996 p->static_prio = NICE_TO_PRIO(nice);
3997 goto out_unlock;
3998 }
fd2f4419 3999 on_rq = p->on_rq;
c09595f6 4000 if (on_rq)
69be72c1 4001 dequeue_task(rq, p, 0);
1da177e4 4002
1da177e4 4003 p->static_prio = NICE_TO_PRIO(nice);
2dd73a4f 4004 set_load_weight(p);
b29739f9
IM
4005 old_prio = p->prio;
4006 p->prio = effective_prio(p);
4007 delta = p->prio - old_prio;
1da177e4 4008
dd41f596 4009 if (on_rq) {
371fd7e7 4010 enqueue_task(rq, p, 0);
1da177e4 4011 /*
d5f9f942
AM
4012 * If the task increased its priority or is running and
4013 * lowered its priority, then reschedule its CPU:
1da177e4 4014 */
d5f9f942 4015 if (delta < 0 || (delta > 0 && task_running(rq, p)))
1da177e4
LT
4016 resched_task(rq->curr);
4017 }
4018out_unlock:
0122ec5b 4019 task_rq_unlock(rq, p, &flags);
1da177e4 4020}
6fa3eb70 4021#endif
1da177e4
LT
4022EXPORT_SYMBOL(set_user_nice);
4023
e43379f1
MM
4024/*
4025 * can_nice - check if a task can reduce its nice value
4026 * @p: task
4027 * @nice: nice value
4028 */
36c8b586 4029int can_nice(const struct task_struct *p, const int nice)
e43379f1 4030{
024f4747
MM
4031 /* convert nice value [19,-20] to rlimit style value [1,40] */
4032 int nice_rlim = 20 - nice;
48f24c4d 4033
78d7d407 4034 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
4035 capable(CAP_SYS_NICE));
4036}
4037
1da177e4
LT
4038#ifdef __ARCH_WANT_SYS_NICE
4039
4040/*
4041 * sys_nice - change the priority of the current process.
4042 * @increment: priority increment
4043 *
4044 * sys_setpriority is a more generic, but much slower function that
4045 * does similar things.
4046 */
5add95d4 4047SYSCALL_DEFINE1(nice, int, increment)
1da177e4 4048{
48f24c4d 4049 long nice, retval;
1da177e4
LT
4050
4051 /*
4052 * Setpriority might change our priority at the same moment.
4053 * We don't have to worry. Conceptually one call occurs first
4054 * and we have a single winner.
4055 */
e43379f1
MM
4056 if (increment < -40)
4057 increment = -40;
1da177e4
LT
4058 if (increment > 40)
4059 increment = 40;
4060
2b8f836f 4061 nice = TASK_NICE(current) + increment;
1da177e4
LT
4062 if (nice < -20)
4063 nice = -20;
4064 if (nice > 19)
4065 nice = 19;
4066
e43379f1
MM
4067 if (increment < 0 && !can_nice(current, nice))
4068 return -EPERM;
4069
1da177e4
LT
4070 retval = security_task_setnice(current, nice);
4071 if (retval)
4072 return retval;
6fa3eb70
S
4073#ifdef CONFIG_MT_PRIO_TRACER
4074 set_user_nice_syscall(current, nice);
4075#else
1da177e4 4076 set_user_nice(current, nice);
6fa3eb70 4077#endif
1da177e4
LT
4078 return 0;
4079}
4080
4081#endif
4082
4083/**
4084 * task_prio - return the priority value of a given task.
4085 * @p: the task in question.
4086 *
4087 * This is the priority value as seen by users in /proc.
4088 * RT tasks are offset by -200. Normal tasks are centered
4089 * around 0, value goes from -16 to +15.
4090 */
36c8b586 4091int task_prio(const struct task_struct *p)
1da177e4
LT
4092{
4093 return p->prio - MAX_RT_PRIO;
4094}
4095
4096/**
4097 * task_nice - return the nice value of a given task.
4098 * @p: the task in question.
4099 */
36c8b586 4100int task_nice(const struct task_struct *p)
1da177e4
LT
4101{
4102 return TASK_NICE(p);
4103}
150d8bed 4104EXPORT_SYMBOL(task_nice);
1da177e4
LT
4105
4106/**
4107 * idle_cpu - is a given cpu idle currently?
4108 * @cpu: the processor in question.
4109 */
4110int idle_cpu(int cpu)
4111{
908a3283
TG
4112 struct rq *rq = cpu_rq(cpu);
4113
4114 if (rq->curr != rq->idle)
4115 return 0;
4116
4117 if (rq->nr_running)
4118 return 0;
4119
4120#ifdef CONFIG_SMP
4121 if (!llist_empty(&rq->wake_list))
4122 return 0;
4123#endif
4124
4125 return 1;
1da177e4
LT
4126}
4127
1da177e4
LT
4128/**
4129 * idle_task - return the idle task for a given cpu.
4130 * @cpu: the processor in question.
4131 */
36c8b586 4132struct task_struct *idle_task(int cpu)
1da177e4
LT
4133{
4134 return cpu_rq(cpu)->idle;
4135}
4136
4137/**
4138 * find_process_by_pid - find a process with a matching PID value.
4139 * @pid: the pid in question.
4140 */
a9957449 4141static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 4142{
228ebcbe 4143 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
4144}
4145
6fa3eb70
S
4146extern struct cpumask hmp_slow_cpu_mask;
4147
1da177e4 4148/* Actually do priority change: must hold rq lock. */
dd41f596
IM
4149static void
4150__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
1da177e4 4151{
1da177e4
LT
4152 p->policy = policy;
4153 p->rt_priority = prio;
b29739f9
IM
4154 p->normal_prio = normal_prio(p);
4155 /* we are holding p->pi_lock already */
4156 p->prio = rt_mutex_getprio(p);
6fa3eb70 4157 if (rt_prio(p->prio)) {
ffd44db5 4158 p->sched_class = &rt_sched_class;
6fa3eb70 4159 }
ffd44db5
PZ
4160 else
4161 p->sched_class = &fair_sched_class;
2dd73a4f 4162 set_load_weight(p);
1da177e4
LT
4163}
4164
c69e8d9c
DH
4165/*
4166 * check the target process has a UID that matches the current process's
4167 */
4168static bool check_same_owner(struct task_struct *p)
4169{
4170 const struct cred *cred = current_cred(), *pcred;
4171 bool match;
4172
4173 rcu_read_lock();
4174 pcred = __task_cred(p);
9c806aa0
EB
4175 match = (uid_eq(cred->euid, pcred->euid) ||
4176 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
4177 rcu_read_unlock();
4178 return match;
4179}
4180
6fa3eb70
S
4181static int check_mt_allow_rt(struct sched_param *param)
4182{
4183 int allow = 0;
4184 if(0 == MT_ALLOW_RT_PRIO_BIT){
4185 //this condition check will be removed
4186 return 1;
4187 }
4188
4189 if(param->sched_priority & MT_ALLOW_RT_PRIO_BIT){
4190 param->sched_priority &= ~MT_ALLOW_RT_PRIO_BIT;
4191 allow = 1;
4192 }
4193 return allow;
4194}
4195
961ccddd 4196static int __sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 4197 const struct sched_param *param, bool user)
1da177e4 4198{
83b699ed 4199 int retval, oldprio, oldpolicy = -1, on_rq, running;
1da177e4 4200 unsigned long flags;
83ab0aa0 4201 const struct sched_class *prev_class;
70b97a7f 4202 struct rq *rq;
ca94c442 4203 int reset_on_fork;
1da177e4 4204
66e5393a
SR
4205 /* may grab non-irq protected spin_locks */
4206 BUG_ON(in_interrupt());
1da177e4
LT
4207recheck:
4208 /* double check policy once rq lock held */
ca94c442
LP
4209 if (policy < 0) {
4210 reset_on_fork = p->sched_reset_on_fork;
1da177e4 4211 policy = oldpolicy = p->policy;
ca94c442
LP
4212 } else {
4213 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4214 policy &= ~SCHED_RESET_ON_FORK;
4215
4216 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4217 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4218 policy != SCHED_IDLE)
4219 return -EINVAL;
4220 }
4221
6fa3eb70
S
4222 if(rt_policy(policy)){
4223 if (!check_mt_allow_rt((struct sched_param *)param)){
4224 printk("[RT_MONITOR]WARNNING [%d:%s] SET NOT ALLOW RT Prio [%d] for proc [%d:%s]\n", current->pid, current->comm, param->sched_priority, p->pid, p->comm);
4225 //dump_stack();
4226 }
4227 }
4228
1da177e4
LT
4229 /*
4230 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
4231 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4232 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4
LT
4233 */
4234 if (param->sched_priority < 0 ||
95cdf3b7 4235 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
d46523ea 4236 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
1da177e4 4237 return -EINVAL;
e05606d3 4238 if (rt_policy(policy) != (param->sched_priority != 0))
1da177e4
LT
4239 return -EINVAL;
4240
37e4ab3f
OC
4241 /*
4242 * Allow unprivileged RT tasks to decrease priority:
4243 */
961ccddd 4244 if (user && !capable(CAP_SYS_NICE)) {
e05606d3 4245 if (rt_policy(policy)) {
a44702e8
ON
4246 unsigned long rlim_rtprio =
4247 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909
ON
4248
4249 /* can't set/change the rt policy */
4250 if (policy != p->policy && !rlim_rtprio)
4251 return -EPERM;
4252
4253 /* can't increase priority */
4254 if (param->sched_priority > p->rt_priority &&
4255 param->sched_priority > rlim_rtprio)
4256 return -EPERM;
4257 }
c02aa73b 4258
dd41f596 4259 /*
c02aa73b
DH
4260 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4261 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 4262 */
c02aa73b
DH
4263 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
4264 if (!can_nice(p, TASK_NICE(p)))
4265 return -EPERM;
4266 }
5fe1d75f 4267
37e4ab3f 4268 /* can't change other user's priorities */
c69e8d9c 4269 if (!check_same_owner(p))
37e4ab3f 4270 return -EPERM;
ca94c442
LP
4271
4272 /* Normal users shall not reset the sched_reset_on_fork flag */
4273 if (p->sched_reset_on_fork && !reset_on_fork)
4274 return -EPERM;
37e4ab3f 4275 }
1da177e4 4276
725aad24 4277 if (user) {
b0ae1981 4278 retval = security_task_setscheduler(p);
725aad24
JF
4279 if (retval)
4280 return retval;
4281 }
4282
b29739f9
IM
4283 /*
4284 * make sure no PI-waiters arrive (or leave) while we are
4285 * changing the priority of the task:
0122ec5b 4286 *
25985edc 4287 * To be able to change p->policy safely, the appropriate
1da177e4
LT
4288 * runqueue lock must be held.
4289 */
0122ec5b 4290 rq = task_rq_lock(p, &flags);
dc61b1d6 4291
34f971f6
PZ
4292 /*
4293 * Changing the policy of the stop threads its a very bad idea
4294 */
4295 if (p == rq->stop) {
0122ec5b 4296 task_rq_unlock(rq, p, &flags);
34f971f6
PZ
4297 return -EINVAL;
4298 }
4299
a51e9198
DF
4300 /*
4301 * If not changing anything there's no need to proceed further:
4302 */
4303 if (unlikely(policy == p->policy && (!rt_policy(policy) ||
4304 param->sched_priority == p->rt_priority))) {
45afb173 4305 task_rq_unlock(rq, p, &flags);
a51e9198
DF
4306 return 0;
4307 }
4308
dc61b1d6
PZ
4309#ifdef CONFIG_RT_GROUP_SCHED
4310 if (user) {
4311 /*
4312 * Do not allow realtime tasks into groups that have no runtime
4313 * assigned.
4314 */
4315 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
4316 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4317 !task_group_is_autogroup(task_group(p))) {
0122ec5b 4318 task_rq_unlock(rq, p, &flags);
dc61b1d6
PZ
4319 return -EPERM;
4320 }
4321 }
4322#endif
4323
1da177e4
LT
4324 /* recheck policy now with rq lock held */
4325 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4326 policy = oldpolicy = -1;
0122ec5b 4327 task_rq_unlock(rq, p, &flags);
1da177e4
LT
4328 goto recheck;
4329 }
fd2f4419 4330 on_rq = p->on_rq;
051a1d1a 4331 running = task_current(rq, p);
0e1f3483 4332 if (on_rq)
4ca9b72b 4333 dequeue_task(rq, p, 0);
0e1f3483
HS
4334 if (running)
4335 p->sched_class->put_prev_task(rq, p);
f6b53205 4336
ca94c442
LP
4337 p->sched_reset_on_fork = reset_on_fork;
4338
1da177e4 4339 oldprio = p->prio;
83ab0aa0 4340 prev_class = p->sched_class;
dd41f596 4341 __setscheduler(rq, p, policy, param->sched_priority);
f6b53205 4342
0e1f3483
HS
4343 if (running)
4344 p->sched_class->set_curr_task(rq);
da7a735e 4345 if (on_rq)
4ca9b72b 4346 enqueue_task(rq, p, 0);
cb469845 4347
da7a735e 4348 check_class_changed(rq, p, prev_class, oldprio);
0122ec5b 4349 task_rq_unlock(rq, p, &flags);
b29739f9 4350
95e02ca9
TG
4351 rt_mutex_adjust_pi(p);
4352
1da177e4
LT
4353 return 0;
4354}
961ccddd
RR
4355
4356/**
4357 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4358 * @p: the task in question.
4359 * @policy: new policy.
4360 * @param: structure containing the new RT priority.
4361 *
4362 * NOTE that the task may be already dead.
4363 */
6fa3eb70
S
4364#ifdef CONFIG_MT_PRIO_TRACER
4365int sched_setscheduler_core(struct task_struct *p, int policy,
4366 const struct sched_param *param)
4367{
4368 return __sched_setscheduler(p, policy, param, true);
4369}
4370
4371int sched_setscheduler(struct task_struct *p, int policy,
4372 const struct sched_param *param)
4373{
4374 int retval;
4375
4376 retval = sched_setscheduler_core(p, policy, param);
4377 if (!retval) {
4378 int prio = param->sched_priority & ~MT_ALLOW_RT_PRIO_BIT;
4379 if (!rt_policy(policy))
4380 prio = __normal_prio(p);
4381 else
4382 prio = MAX_RT_PRIO-1 - prio;
4383 update_prio_tracer(task_pid_nr(p), prio, policy, PTS_KRNL);
4384 }
4385 return retval;
4386}
4387#else /* !CONFIG_MT_PRIO_TRACER */
961ccddd 4388int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 4389 const struct sched_param *param)
961ccddd
RR
4390{
4391 return __sched_setscheduler(p, policy, param, true);
4392}
6fa3eb70 4393#endif
1da177e4
LT
4394EXPORT_SYMBOL_GPL(sched_setscheduler);
4395
961ccddd
RR
4396/**
4397 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4398 * @p: the task in question.
4399 * @policy: new policy.
4400 * @param: structure containing the new RT priority.
4401 *
4402 * Just like sched_setscheduler, only don't bother checking if the
4403 * current context has permission. For example, this is needed in
4404 * stop_machine(): we create temporary high priority worker threads,
4405 * but our caller might not have that capability.
4406 */
6fa3eb70
S
4407#ifdef CONFIG_MT_PRIO_TRACER
4408int sched_setscheduler_nocheck_core(struct task_struct *p, int policy,
4409 const struct sched_param *param)
4410{
4411 return __sched_setscheduler(p, policy, param, false);
4412}
4413
4414
4415int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4416 const struct sched_param *param)
4417{
4418 int retval;
4419
4420 retval = sched_setscheduler_nocheck_core(p, policy, param);
4421 if (!retval) {
4422 int prio = param->sched_priority & ~MT_ALLOW_RT_PRIO_BIT;
4423 if (!rt_policy(policy))
4424 prio = __normal_prio(p);
4425 else
4426 prio = MAX_RT_PRIO-1 - prio;
4427 update_prio_tracer(task_pid_nr(p), prio, policy, PTS_KRNL);
4428 }
4429 return retval;
4430}
4431#else /* !CONFIG_MT_PRIO_TRACER */
961ccddd 4432int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 4433 const struct sched_param *param)
961ccddd
RR
4434{
4435 return __sched_setscheduler(p, policy, param, false);
4436}
6fa3eb70 4437#endif
961ccddd 4438
95cdf3b7
IM
4439static int
4440do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4441{
1da177e4
LT
4442 struct sched_param lparam;
4443 struct task_struct *p;
36c8b586 4444 int retval;
1da177e4
LT
4445
4446 if (!param || pid < 0)
4447 return -EINVAL;
4448 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4449 return -EFAULT;
5fe1d75f
ON
4450
4451 rcu_read_lock();
4452 retval = -ESRCH;
1da177e4 4453 p = find_process_by_pid(pid);
6fa3eb70
S
4454#ifdef CONFIG_MT_PRIO_TRACER
4455 if (p != NULL)
4456 retval = sched_setscheduler_syscall(p, policy, &lparam);
4457#else
5fe1d75f
ON
4458 if (p != NULL)
4459 retval = sched_setscheduler(p, policy, &lparam);
6fa3eb70
S
4460#endif
4461
5fe1d75f 4462 rcu_read_unlock();
36c8b586 4463
1da177e4
LT
4464 return retval;
4465}
4466
4467/**
4468 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4469 * @pid: the pid in question.
4470 * @policy: new policy.
4471 * @param: structure containing the new RT priority.
4472 */
5add95d4
HC
4473SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4474 struct sched_param __user *, param)
1da177e4 4475{
c21761f1
JB
4476 /* negative values for policy are not valid */
4477 if (policy < 0)
4478 return -EINVAL;
4479
1da177e4
LT
4480 return do_sched_setscheduler(pid, policy, param);
4481}
4482
4483/**
4484 * sys_sched_setparam - set/change the RT priority of a thread
4485 * @pid: the pid in question.
4486 * @param: structure containing the new RT priority.
4487 */
5add95d4 4488SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4
LT
4489{
4490 return do_sched_setscheduler(pid, -1, param);
4491}
4492
4493/**
4494 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4495 * @pid: the pid in question.
4496 */
5add95d4 4497SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 4498{
36c8b586 4499 struct task_struct *p;
3a5c359a 4500 int retval;
1da177e4
LT
4501
4502 if (pid < 0)
3a5c359a 4503 return -EINVAL;
1da177e4
LT
4504
4505 retval = -ESRCH;
5fe85be0 4506 rcu_read_lock();
1da177e4
LT
4507 p = find_process_by_pid(pid);
4508 if (p) {
4509 retval = security_task_getscheduler(p);
4510 if (!retval)
ca94c442
LP
4511 retval = p->policy
4512 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 4513 }
5fe85be0 4514 rcu_read_unlock();
1da177e4
LT
4515 return retval;
4516}
4517
4518/**
ca94c442 4519 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
4520 * @pid: the pid in question.
4521 * @param: structure containing the RT priority.
4522 */
5add95d4 4523SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4
LT
4524{
4525 struct sched_param lp;
36c8b586 4526 struct task_struct *p;
3a5c359a 4527 int retval;
1da177e4
LT
4528
4529 if (!param || pid < 0)
3a5c359a 4530 return -EINVAL;
1da177e4 4531
5fe85be0 4532 rcu_read_lock();
1da177e4
LT
4533 p = find_process_by_pid(pid);
4534 retval = -ESRCH;
4535 if (!p)
4536 goto out_unlock;
4537
4538 retval = security_task_getscheduler(p);
4539 if (retval)
4540 goto out_unlock;
4541
4542 lp.sched_priority = p->rt_priority;
5fe85be0 4543 rcu_read_unlock();
1da177e4
LT
4544
4545 /*
4546 * This one might sleep, we cannot do it with a spinlock held ...
4547 */
4548 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4549
1da177e4
LT
4550 return retval;
4551
4552out_unlock:
5fe85be0 4553 rcu_read_unlock();
1da177e4
LT
4554 return retval;
4555}
4556
96f874e2 4557long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1da177e4 4558{
5a16f3d3 4559 cpumask_var_t cpus_allowed, new_mask;
36c8b586
IM
4560 struct task_struct *p;
4561 int retval;
1da177e4 4562
95402b38 4563 get_online_cpus();
23f5d142 4564 rcu_read_lock();
1da177e4
LT
4565
4566 p = find_process_by_pid(pid);
4567 if (!p) {
23f5d142 4568 rcu_read_unlock();
95402b38 4569 put_online_cpus();
6fa3eb70 4570 printk(KERN_DEBUG "SCHED: setaffinity find process %d fail\n", pid);
1da177e4
LT
4571 return -ESRCH;
4572 }
4573
23f5d142 4574 /* Prevent p going away */
1da177e4 4575 get_task_struct(p);
23f5d142 4576 rcu_read_unlock();
1da177e4 4577
14a40ffc
TH
4578 if (p->flags & PF_NO_SETAFFINITY) {
4579 retval = -EINVAL;
6fa3eb70 4580 printk(KERN_DEBUG "SCHED: setaffinity flags PF_NO_SETAFFINITY fail\n");
14a40ffc
TH
4581 goto out_put_task;
4582 }
5a16f3d3
RR
4583 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4584 retval = -ENOMEM;
6fa3eb70 4585 printk(KERN_DEBUG "SCHED: setaffinity allo_cpumask_var for cpus_allowed fail\n");
5a16f3d3
RR
4586 goto out_put_task;
4587 }
4588 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4589 retval = -ENOMEM;
6fa3eb70 4590 printk(KERN_DEBUG "SCHED: setaffinity allo_cpumask_var for new_mask fail\n");
5a16f3d3
RR
4591 goto out_free_cpus_allowed;
4592 }
1da177e4 4593 retval = -EPERM;
4c44aaaf
EB
4594 if (!check_same_owner(p)) {
4595 rcu_read_lock();
4596 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4597 rcu_read_unlock();
6fa3eb70 4598 printk(KERN_DEBUG "SCHED: setaffinity check_same_owner and task_ns_capable fail\n");
4c44aaaf
EB
4599 goto out_unlock;
4600 }
4601 rcu_read_unlock();
4602 }
1da177e4 4603
b0ae1981 4604 retval = security_task_setscheduler(p);
6fa3eb70
S
4605 if (retval){
4606 printk(KERN_DEBUG "SCHED: setaffinity security_task_setscheduler fail, status: %d\n", retval);
e7834f8f 4607 goto out_unlock;
6fa3eb70 4608 }
e7834f8f 4609
5a16f3d3
RR
4610 cpuset_cpus_allowed(p, cpus_allowed);
4611 cpumask_and(new_mask, in_mask, cpus_allowed);
49246274 4612again:
5a16f3d3 4613 retval = set_cpus_allowed_ptr(p, new_mask);
6fa3eb70
S
4614 if (retval)
4615 printk(KERN_DEBUG "SCHED: set_cpus_allowed_ptr status %d\n", retval);
1da177e4 4616
8707d8b8 4617 if (!retval) {
5a16f3d3
RR
4618 cpuset_cpus_allowed(p, cpus_allowed);
4619 if (!cpumask_subset(new_mask, cpus_allowed)) {
8707d8b8
PM
4620 /*
4621 * We must have raced with a concurrent cpuset
4622 * update. Just reset the cpus_allowed to the
4623 * cpuset's cpus_allowed
4624 */
5a16f3d3 4625 cpumask_copy(new_mask, cpus_allowed);
8707d8b8
PM
4626 goto again;
4627 }
4628 }
1da177e4 4629out_unlock:
5a16f3d3
RR
4630 free_cpumask_var(new_mask);
4631out_free_cpus_allowed:
4632 free_cpumask_var(cpus_allowed);
4633out_put_task:
1da177e4 4634 put_task_struct(p);
95402b38 4635 put_online_cpus();
6fa3eb70
S
4636 if (retval)
4637 printk(KERN_DEBUG "SCHED: setaffinity status %d\n", retval);
1da177e4
LT
4638 return retval;
4639}
4640
4641static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 4642 struct cpumask *new_mask)
1da177e4 4643{
96f874e2
RR
4644 if (len < cpumask_size())
4645 cpumask_clear(new_mask);
4646 else if (len > cpumask_size())
4647 len = cpumask_size();
4648
1da177e4
LT
4649 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4650}
4651
4652/**
4653 * sys_sched_setaffinity - set the cpu affinity of a process
4654 * @pid: pid of the process
4655 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4656 * @user_mask_ptr: user-space pointer to the new cpu mask
4657 */
5add95d4
HC
4658SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4659 unsigned long __user *, user_mask_ptr)
1da177e4 4660{
5a16f3d3 4661 cpumask_var_t new_mask;
1da177e4
LT
4662 int retval;
4663
5a16f3d3
RR
4664 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4665 return -ENOMEM;
1da177e4 4666
5a16f3d3
RR
4667 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4668 if (retval == 0)
4669 retval = sched_setaffinity(pid, new_mask);
4670 free_cpumask_var(new_mask);
4671 return retval;
1da177e4
LT
4672}
4673
96f874e2 4674long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 4675{
36c8b586 4676 struct task_struct *p;
31605683 4677 unsigned long flags;
1da177e4 4678 int retval;
1da177e4 4679
95402b38 4680 get_online_cpus();
23f5d142 4681 rcu_read_lock();
1da177e4
LT
4682
4683 retval = -ESRCH;
4684 p = find_process_by_pid(pid);
6fa3eb70
S
4685 if (!p){
4686 printk(KERN_DEBUG "SCHED: getaffinity find process %d fail\n", pid);
1da177e4 4687 goto out_unlock;
6fa3eb70 4688 }
1da177e4 4689
e7834f8f 4690 retval = security_task_getscheduler(p);
6fa3eb70
S
4691 if (retval){
4692 printk(KERN_DEBUG "SCHED: getaffinity security_task_getscheduler fail, status: %d\n", retval);
e7834f8f 4693 goto out_unlock;
6fa3eb70 4694 }
e7834f8f 4695
013fdb80 4696 raw_spin_lock_irqsave(&p->pi_lock, flags);
96f874e2 4697 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
013fdb80 4698 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4699
4700out_unlock:
23f5d142 4701 rcu_read_unlock();
95402b38 4702 put_online_cpus();
1da177e4 4703
6fa3eb70
S
4704 if (retval){
4705 printk(KERN_DEBUG "SCHED: getaffinity status %d\n", retval);
4706 }
9531b62f 4707 return retval;
1da177e4
LT
4708}
4709
4710/**
4711 * sys_sched_getaffinity - get the cpu affinity of a process
4712 * @pid: pid of the process
4713 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4714 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4715 */
5add95d4
HC
4716SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4717 unsigned long __user *, user_mask_ptr)
1da177e4
LT
4718{
4719 int ret;
f17c8607 4720 cpumask_var_t mask;
1da177e4 4721
84fba5ec 4722 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
4723 return -EINVAL;
4724 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
4725 return -EINVAL;
4726
f17c8607
RR
4727 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4728 return -ENOMEM;
1da177e4 4729
f17c8607
RR
4730 ret = sched_getaffinity(pid, mask);
4731 if (ret == 0) {
8bc037fb 4732 size_t retlen = min_t(size_t, len, cpumask_size());
cd3d8031
KM
4733
4734 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
4735 ret = -EFAULT;
4736 else
cd3d8031 4737 ret = retlen;
f17c8607
RR
4738 }
4739 free_cpumask_var(mask);
1da177e4 4740
f17c8607 4741 return ret;
1da177e4
LT
4742}
4743
4744/**
4745 * sys_sched_yield - yield the current processor to other threads.
4746 *
dd41f596
IM
4747 * This function yields the current CPU to other tasks. If there are no
4748 * other threads running on this CPU then this function will return.
1da177e4 4749 */
5add95d4 4750SYSCALL_DEFINE0(sched_yield)
1da177e4 4751{
70b97a7f 4752 struct rq *rq = this_rq_lock();
1da177e4 4753
2d72376b 4754 schedstat_inc(rq, yld_count);
4530d7ab 4755 current->sched_class->yield_task(rq);
1da177e4
LT
4756
4757 /*
4758 * Since we are going to call schedule() anyway, there's
4759 * no need to preempt or enable interrupts:
4760 */
4761 __release(rq->lock);
8a25d5de 4762 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
9828ea9d 4763 do_raw_spin_unlock(&rq->lock);
ba74c144 4764 sched_preempt_enable_no_resched();
1da177e4
LT
4765
4766 schedule();
4767
4768 return 0;
4769}
4770
d86ee480
PZ
4771static inline int should_resched(void)
4772{
4773 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
4774}
4775
e7b38404 4776static void __cond_resched(void)
1da177e4 4777{
e7aaaa69 4778 add_preempt_count(PREEMPT_ACTIVE);
c259e01a 4779 __schedule();
e7aaaa69 4780 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4
LT
4781}
4782
02b67cc3 4783int __sched _cond_resched(void)
1da177e4 4784{
d86ee480 4785 if (should_resched()) {
1da177e4
LT
4786 __cond_resched();
4787 return 1;
4788 }
4789 return 0;
4790}
02b67cc3 4791EXPORT_SYMBOL(_cond_resched);
1da177e4
LT
4792
4793/*
613afbf8 4794 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
4795 * call schedule, and on return reacquire the lock.
4796 *
41a2d6cf 4797 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
1da177e4
LT
4798 * operations here to prevent schedule() from being called twice (once via
4799 * spin_unlock(), once by hand).
4800 */
613afbf8 4801int __cond_resched_lock(spinlock_t *lock)
1da177e4 4802{
d86ee480 4803 int resched = should_resched();
6df3cecb
JK
4804 int ret = 0;
4805
f607c668
PZ
4806 lockdep_assert_held(lock);
4807
95c354fe 4808 if (spin_needbreak(lock) || resched) {
1da177e4 4809 spin_unlock(lock);
d86ee480 4810 if (resched)
95c354fe
NP
4811 __cond_resched();
4812 else
4813 cpu_relax();
6df3cecb 4814 ret = 1;
1da177e4 4815 spin_lock(lock);
1da177e4 4816 }
6df3cecb 4817 return ret;
1da177e4 4818}
613afbf8 4819EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 4820
613afbf8 4821int __sched __cond_resched_softirq(void)
1da177e4
LT
4822{
4823 BUG_ON(!in_softirq());
4824
d86ee480 4825 if (should_resched()) {
98d82567 4826 local_bh_enable();
1da177e4
LT
4827 __cond_resched();
4828 local_bh_disable();
4829 return 1;
4830 }
4831 return 0;
4832}
613afbf8 4833EXPORT_SYMBOL(__cond_resched_softirq);
1da177e4 4834
1da177e4
LT
4835/**
4836 * yield - yield the current processor to other threads.
4837 *
8e3fabfd
PZ
4838 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4839 *
4840 * The scheduler is at all times free to pick the calling task as the most
4841 * eligible task to run, if removing the yield() call from your code breaks
4842 * it, its already broken.
4843 *
4844 * Typical broken usage is:
4845 *
4846 * while (!event)
4847 * yield();
4848 *
4849 * where one assumes that yield() will let 'the other' process run that will
4850 * make event true. If the current task is a SCHED_FIFO task that will never
4851 * happen. Never use yield() as a progress guarantee!!
4852 *
4853 * If you want to use yield() to wait for something, use wait_event().
4854 * If you want to use yield() to be 'nice' for others, use cond_resched().
4855 * If you still want to use yield(), do not!
1da177e4
LT
4856 */
4857void __sched yield(void)
4858{
4859 set_current_state(TASK_RUNNING);
4860 sys_sched_yield();
4861}
1da177e4
LT
4862EXPORT_SYMBOL(yield);
4863
d95f4122
MG
4864/**
4865 * yield_to - yield the current processor to another thread in
4866 * your thread group, or accelerate that thread toward the
4867 * processor it's on.
16addf95
RD
4868 * @p: target task
4869 * @preempt: whether task preemption is allowed or not
d95f4122
MG
4870 *
4871 * It's the caller's job to ensure that the target task struct
4872 * can't go away on us before we can do any checks.
4873 *
7b270f60
PZ
4874 * Returns:
4875 * true (>0) if we indeed boosted the target task.
4876 * false (0) if we failed to boost the target.
4877 * -ESRCH if there's no task to yield to.
d95f4122
MG
4878 */
4879bool __sched yield_to(struct task_struct *p, bool preempt)
4880{
4881 struct task_struct *curr = current;
4882 struct rq *rq, *p_rq;
4883 unsigned long flags;
c3c18640 4884 int yielded = 0;
d95f4122
MG
4885
4886 local_irq_save(flags);
4887 rq = this_rq();
4888
4889again:
4890 p_rq = task_rq(p);
7b270f60
PZ
4891 /*
4892 * If we're the only runnable task on the rq and target rq also
4893 * has only one task, there's absolutely no point in yielding.
4894 */
4895 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4896 yielded = -ESRCH;
4897 goto out_irq;
4898 }
4899
d95f4122
MG
4900 double_rq_lock(rq, p_rq);
4901 while (task_rq(p) != p_rq) {
4902 double_rq_unlock(rq, p_rq);
4903 goto again;
4904 }
4905
4906 if (!curr->sched_class->yield_to_task)
7b270f60 4907 goto out_unlock;
d95f4122
MG
4908
4909 if (curr->sched_class != p->sched_class)
7b270f60 4910 goto out_unlock;
d95f4122
MG
4911
4912 if (task_running(p_rq, p) || p->state)
7b270f60 4913 goto out_unlock;
d95f4122
MG
4914
4915 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
6d1cafd8 4916 if (yielded) {
d95f4122 4917 schedstat_inc(rq, yld_count);
6d1cafd8
VP
4918 /*
4919 * Make p's CPU reschedule; pick_next_entity takes care of
4920 * fairness.
4921 */
4922 if (preempt && rq != p_rq)
4923 resched_task(p_rq->curr);
4924 }
d95f4122 4925
7b270f60 4926out_unlock:
d95f4122 4927 double_rq_unlock(rq, p_rq);
7b270f60 4928out_irq:
d95f4122
MG
4929 local_irq_restore(flags);
4930
7b270f60 4931 if (yielded > 0)
d95f4122
MG
4932 schedule();
4933
4934 return yielded;
4935}
4936EXPORT_SYMBOL_GPL(yield_to);
4937
1da177e4 4938/*
41a2d6cf 4939 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 4940 * that process accounting knows that this is a task in IO wait state.
1da177e4
LT
4941 */
4942void __sched io_schedule(void)
4943{
54d35f29 4944 struct rq *rq = raw_rq();
1da177e4 4945
0ff92245 4946 delayacct_blkio_start();
1da177e4 4947 atomic_inc(&rq->nr_iowait);
73c10101 4948 blk_flush_plug(current);
8f0dfc34 4949 current->in_iowait = 1;
1da177e4 4950 schedule();
8f0dfc34 4951 current->in_iowait = 0;
1da177e4 4952 atomic_dec(&rq->nr_iowait);
0ff92245 4953 delayacct_blkio_end();
1da177e4 4954}
1da177e4
LT
4955EXPORT_SYMBOL(io_schedule);
4956
4957long __sched io_schedule_timeout(long timeout)
4958{
54d35f29 4959 struct rq *rq = raw_rq();
1da177e4
LT
4960 long ret;
4961
0ff92245 4962 delayacct_blkio_start();
1da177e4 4963 atomic_inc(&rq->nr_iowait);
73c10101 4964 blk_flush_plug(current);
8f0dfc34 4965 current->in_iowait = 1;
1da177e4 4966 ret = schedule_timeout(timeout);
8f0dfc34 4967 current->in_iowait = 0;
1da177e4 4968 atomic_dec(&rq->nr_iowait);
0ff92245 4969 delayacct_blkio_end();
1da177e4
LT
4970 return ret;
4971}
4972
4973/**
4974 * sys_sched_get_priority_max - return maximum RT priority.
4975 * @policy: scheduling class.
4976 *
4977 * this syscall returns the maximum rt_priority that can be used
4978 * by a given scheduling class.
4979 */
5add95d4 4980SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
4981{
4982 int ret = -EINVAL;
4983
4984 switch (policy) {
4985 case SCHED_FIFO:
4986 case SCHED_RR:
4987 ret = MAX_USER_RT_PRIO-1;
4988 break;
4989 case SCHED_NORMAL:
b0a9499c 4990 case SCHED_BATCH:
dd41f596 4991 case SCHED_IDLE:
1da177e4
LT
4992 ret = 0;
4993 break;
4994 }
4995 return ret;
4996}
4997
4998/**
4999 * sys_sched_get_priority_min - return minimum RT priority.
5000 * @policy: scheduling class.
5001 *
5002 * this syscall returns the minimum rt_priority that can be used
5003 * by a given scheduling class.
5004 */
5add95d4 5005SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
5006{
5007 int ret = -EINVAL;
5008
5009 switch (policy) {
5010 case SCHED_FIFO:
5011 case SCHED_RR:
5012 ret = 1;
5013 break;
5014 case SCHED_NORMAL:
b0a9499c 5015 case SCHED_BATCH:
dd41f596 5016 case SCHED_IDLE:
1da177e4
LT
5017 ret = 0;
5018 }
5019 return ret;
5020}
5021
5022/**
5023 * sys_sched_rr_get_interval - return the default timeslice of a process.
5024 * @pid: pid of the process.
5025 * @interval: userspace pointer to the timeslice value.
5026 *
5027 * this syscall writes the default timeslice value of a given process
5028 * into the user-space timespec buffer. A value of '0' means infinity.
5029 */
17da2bd9 5030SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
754fe8d2 5031 struct timespec __user *, interval)
1da177e4 5032{
36c8b586 5033 struct task_struct *p;
a4ec24b4 5034 unsigned int time_slice;
dba091b9
TG
5035 unsigned long flags;
5036 struct rq *rq;
3a5c359a 5037 int retval;
1da177e4 5038 struct timespec t;
1da177e4
LT
5039
5040 if (pid < 0)
3a5c359a 5041 return -EINVAL;
1da177e4
LT
5042
5043 retval = -ESRCH;
1a551ae7 5044 rcu_read_lock();
1da177e4
LT
5045 p = find_process_by_pid(pid);
5046 if (!p)
5047 goto out_unlock;
5048
5049 retval = security_task_getscheduler(p);
5050 if (retval)
5051 goto out_unlock;
5052
dba091b9
TG
5053 rq = task_rq_lock(p, &flags);
5054 time_slice = p->sched_class->get_rr_interval(rq, p);
0122ec5b 5055 task_rq_unlock(rq, p, &flags);
a4ec24b4 5056
1a551ae7 5057 rcu_read_unlock();
a4ec24b4 5058 jiffies_to_timespec(time_slice, &t);
1da177e4 5059 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
1da177e4 5060 return retval;
3a5c359a 5061
1da177e4 5062out_unlock:
1a551ae7 5063 rcu_read_unlock();
1da177e4
LT
5064 return retval;
5065}
5066
7c731e0a 5067static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
6fa3eb70
S
5068#ifdef CONFIG_MT_DEBUG_MUTEXES
5069void mt_mutex_state(struct task_struct *p)
5070{
5071 struct task_struct *locker;
5072 if(p->blocked_on){
5073 locker = p->blocked_on->task_wait_on;
5074 if(find_task_by_vpid(locker->pid) != NULL){
5075 printk("Hint: wait on mutex, holder is [%d:%s:%ld]\n", locker->pid, locker->comm, locker->state);
5076 if(locker->state != TASK_RUNNING){
5077 printk("Mutex holder process[%d:%s] is not running now:\n", locker->pid, locker->comm);
5078 show_stack(locker, NULL);
5079 printk("----\n");
5080 }
5081 }else{
5082 printk("Hint: wait on mutex, but holder already released lock\n");
5083 }
5084 }
5085}
5086#endif
82a1fcb9 5087void sched_show_task(struct task_struct *p)
1da177e4 5088{
1da177e4 5089 unsigned long free = 0;
4e79752c 5090 int ppid;
36c8b586 5091 unsigned state;
1da177e4 5092
1da177e4 5093 state = p->state ? __ffs(p->state) + 1 : 0;
28d0686c 5094 printk(KERN_INFO "%-15.15s %c", p->comm,
2ed6e34f 5095 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4bd77321 5096#if BITS_PER_LONG == 32
1da177e4 5097 if (state == TASK_RUNNING)
3df0fc5b 5098 printk(KERN_CONT " running ");
1da177e4 5099 else
3df0fc5b 5100 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
1da177e4
LT
5101#else
5102 if (state == TASK_RUNNING)
3df0fc5b 5103 printk(KERN_CONT " running task ");
1da177e4 5104 else
3df0fc5b 5105 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
1da177e4
LT
5106#endif
5107#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 5108 free = stack_not_used(p);
1da177e4 5109#endif
4e79752c
PM
5110 rcu_read_lock();
5111 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5112 rcu_read_unlock();
3df0fc5b 5113 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4e79752c 5114 task_pid_nr(p), ppid,
aa47b7e0 5115 (unsigned long)task_thread_info(p)->flags);
1da177e4 5116
3d1cb205 5117 print_worker_info(KERN_INFO, p);
5fb5e6de 5118 show_stack(p, NULL);
6fa3eb70
S
5119#ifdef CONFIG_MT_DEBUG_MUTEXES
5120 mt_mutex_state(p);
5121#endif
1da177e4
LT
5122}
5123
e59e2ae2 5124void show_state_filter(unsigned long state_filter)
1da177e4 5125{
36c8b586 5126 struct task_struct *g, *p;
1da177e4 5127
4bd77321 5128#if BITS_PER_LONG == 32
3df0fc5b
PZ
5129 printk(KERN_INFO
5130 " task PC stack pid father\n");
1da177e4 5131#else
3df0fc5b
PZ
5132 printk(KERN_INFO
5133 " task PC stack pid father\n");
1da177e4 5134#endif
510f5acc 5135 rcu_read_lock();
1da177e4
LT
5136 do_each_thread(g, p) {
5137 /*
5138 * reset the NMI-timeout, listing all files on a slow
25985edc 5139 * console might take a lot of time:
1da177e4
LT
5140 */
5141 touch_nmi_watchdog();
39bc89fd 5142 if (!state_filter || (p->state & state_filter))
82a1fcb9 5143 sched_show_task(p);
1da177e4
LT
5144 } while_each_thread(g, p);
5145
04c9167f
JF
5146 touch_all_softlockup_watchdogs();
5147
dd41f596 5148#ifdef CONFIG_SCHED_DEBUG
4718919e
RV
5149 if (!state_filter)
5150 sysrq_sched_debug_show();
dd41f596 5151#endif
510f5acc 5152 rcu_read_unlock();
e59e2ae2
IM
5153 /*
5154 * Only show locks if all tasks are dumped:
5155 */
93335a21 5156 if (!state_filter)
e59e2ae2 5157 debug_show_all_locks();
1da177e4
LT
5158}
5159
1df21055
IM
5160void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5161{
dd41f596 5162 idle->sched_class = &idle_sched_class;
1df21055
IM
5163}
5164
f340c0d1
IM
5165/**
5166 * init_idle - set up an idle thread for a given CPU
5167 * @idle: task in question
5168 * @cpu: cpu the idle task belongs to
5169 *
5170 * NOTE: this function does not set the idle thread's NEED_RESCHED
5171 * flag, to make booting more robust.
5172 */
5c1e1767 5173void __cpuinit init_idle(struct task_struct *idle, int cpu)
1da177e4 5174{
70b97a7f 5175 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
5176 unsigned long flags;
5177
05fa785c 5178 raw_spin_lock_irqsave(&rq->lock, flags);
5cbd54ef 5179
dd41f596 5180 __sched_fork(idle);
06b83b5f 5181 idle->state = TASK_RUNNING;
dd41f596
IM
5182 idle->se.exec_start = sched_clock();
5183
1e1b6c51 5184 do_set_cpus_allowed(idle, cpumask_of(cpu));
6506cf6c
PZ
5185 /*
5186 * We're having a chicken and egg problem, even though we are
5187 * holding rq->lock, the cpu isn't yet set to this cpu so the
5188 * lockdep check in task_group() will fail.
5189 *
5190 * Similar case to sched_fork(). / Alternatively we could
5191 * use task_rq_lock() here and obtain the other rq->lock.
5192 *
5193 * Silence PROVE_RCU
5194 */
5195 rcu_read_lock();
dd41f596 5196 __set_task_cpu(idle, cpu);
6506cf6c 5197 rcu_read_unlock();
1da177e4 5198
1da177e4 5199 rq->curr = rq->idle = idle;
3ca7a440
PZ
5200#if defined(CONFIG_SMP)
5201 idle->on_cpu = 1;
4866cde0 5202#endif
05fa785c 5203 raw_spin_unlock_irqrestore(&rq->lock, flags);
1da177e4
LT
5204
5205 /* Set the preempt count _outside_ the spinlocks! */
a1261f54 5206 task_thread_info(idle)->preempt_count = 0;
55cd5340 5207
dd41f596
IM
5208 /*
5209 * The idle tasks have their own, simple scheduling class:
5210 */
5211 idle->sched_class = &idle_sched_class;
868baf07 5212 ftrace_graph_init_idle_task(idle, cpu);
45eacc69 5213 vtime_init_idle(idle, cpu);
f1c6f1a7
CE
5214#if defined(CONFIG_SMP)
5215 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5216#endif
19978ca6
IM
5217}
5218
1da177e4 5219#ifdef CONFIG_SMP
1e1b6c51
KM
5220void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
5221{
5222 if (p->sched_class && p->sched_class->set_cpus_allowed)
5223 p->sched_class->set_cpus_allowed(p, new_mask);
4939602a
PZ
5224
5225 cpumask_copy(&p->cpus_allowed, new_mask);
29baa747 5226 p->nr_cpus_allowed = cpumask_weight(new_mask);
1e1b6c51
KM
5227}
5228
1da177e4
LT
5229/*
5230 * This is how migration works:
5231 *
969c7921
TH
5232 * 1) we invoke migration_cpu_stop() on the target CPU using
5233 * stop_one_cpu().
5234 * 2) stopper starts to run (implicitly forcing the migrated thread
5235 * off the CPU)
5236 * 3) it checks whether the migrated task is still in the wrong runqueue.
5237 * 4) if it's in the wrong runqueue then the migration thread removes
1da177e4 5238 * it and puts it into the right queue.
969c7921
TH
5239 * 5) stopper completes and stop_one_cpu() returns and the migration
5240 * is done.
1da177e4
LT
5241 */
5242
5243/*
5244 * Change a given task's CPU affinity. Migrate the thread to a
5245 * proper CPU and schedule it away if the CPU it's executing on
5246 * is removed from the allowed bitmask.
5247 *
5248 * NOTE: the caller must have a valid reference to the task, the
41a2d6cf 5249 * task must not exit() & deallocate itself prematurely. The
1da177e4
LT
5250 * call is not atomic; no spinlocks may be held.
5251 */
96f874e2 5252int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1da177e4
LT
5253{
5254 unsigned long flags;
70b97a7f 5255 struct rq *rq;
969c7921 5256 unsigned int dest_cpu;
48f24c4d 5257 int ret = 0;
1da177e4
LT
5258
5259 rq = task_rq_lock(p, &flags);
e2912009 5260
db44fc01
YZ
5261 if (cpumask_equal(&p->cpus_allowed, new_mask))
5262 goto out;
5263
6ad4c188 5264 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
1da177e4 5265 ret = -EINVAL;
6fa3eb70 5266 printk(KERN_DEBUG "SCHED: intersects new_mask: %lu, cpu_active_mask: %lu\n", new_mask->bits[0], cpu_active_mask->bits[0]);
1da177e4
LT
5267 goto out;
5268 }
5269
1e1b6c51 5270 do_set_cpus_allowed(p, new_mask);
73fe6aae 5271
1da177e4 5272 /* Can the task run on the task's current CPU? If so, we're done */
96f874e2 5273 if (cpumask_test_cpu(task_cpu(p), new_mask))
1da177e4
LT
5274 goto out;
5275
969c7921 5276 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
bd8e7dde 5277 if (p->on_rq) {
969c7921 5278 struct migration_arg arg = { p, dest_cpu };
1da177e4 5279 /* Need help from migration thread: drop lock and wait. */
0122ec5b 5280 task_rq_unlock(rq, p, &flags);
969c7921 5281 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1da177e4
LT
5282 tlb_migrate_finish(p->mm);
5283 return 0;
5284 }
5285out:
0122ec5b 5286 task_rq_unlock(rq, p, &flags);
48f24c4d 5287
1da177e4
LT
5288 return ret;
5289}
cd8ba7cd 5290EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1da177e4
LT
5291
5292/*
41a2d6cf 5293 * Move (not current) task off this cpu, onto dest cpu. We're doing
1da177e4
LT
5294 * this because either it can't run here any more (set_cpus_allowed()
5295 * away from this CPU, or CPU going down), or because we're
5296 * attempting to rebalance this task on exec (sched_exec).
5297 *
5298 * So we race with normal scheduler movements, but that's OK, as long
5299 * as the task is no longer on this CPU.
efc30814
KK
5300 *
5301 * Returns non-zero if task was successfully migrated.
1da177e4 5302 */
efc30814 5303static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
1da177e4 5304{
70b97a7f 5305 struct rq *rq_dest, *rq_src;
e2912009 5306 int ret = 0;
1da177e4 5307
e761b772 5308 if (unlikely(!cpu_active(dest_cpu)))
efc30814 5309 return ret;
1da177e4
LT
5310
5311 rq_src = cpu_rq(src_cpu);
5312 rq_dest = cpu_rq(dest_cpu);
5313
0122ec5b 5314 raw_spin_lock(&p->pi_lock);
1da177e4
LT
5315 double_rq_lock(rq_src, rq_dest);
5316 /* Already moved. */
5317 if (task_cpu(p) != src_cpu)
b1e38734 5318 goto done;
1da177e4 5319 /* Affinity changed (again). */
fa17b507 5320 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
b1e38734 5321 goto fail;
1da177e4 5322
e2912009
PZ
5323 /*
5324 * If we're not on a rq, the next wake-up will ensure we're
5325 * placed properly.
5326 */
fd2f4419 5327 if (p->on_rq) {
4ca9b72b 5328 dequeue_task(rq_src, p, 0);
e2912009 5329 set_task_cpu(p, dest_cpu);
4ca9b72b 5330 enqueue_task(rq_dest, p, 0);
15afe09b 5331 check_preempt_curr(rq_dest, p, 0);
1da177e4 5332 }
b1e38734 5333done:
efc30814 5334 ret = 1;
b1e38734 5335fail:
1da177e4 5336 double_rq_unlock(rq_src, rq_dest);
0122ec5b 5337 raw_spin_unlock(&p->pi_lock);
efc30814 5338 return ret;
1da177e4
LT
5339}
5340
5341/*
969c7921
TH
5342 * migration_cpu_stop - this will be executed by a highprio stopper thread
5343 * and performs thread migration by bumping thread off CPU then
5344 * 'pushing' onto another runqueue.
1da177e4 5345 */
969c7921 5346static int migration_cpu_stop(void *data)
1da177e4 5347{
969c7921 5348 struct migration_arg *arg = data;
f7b4cddc 5349
969c7921
TH
5350 /*
5351 * The original target cpu might have gone down and we might
5352 * be on another cpu but it doesn't matter.
5353 */
f7b4cddc 5354 local_irq_disable();
969c7921 5355 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
f7b4cddc 5356 local_irq_enable();
1da177e4 5357 return 0;
f7b4cddc
ON
5358}
5359
1da177e4 5360#ifdef CONFIG_HOTPLUG_CPU
48c5ccae 5361
054b9108 5362/*
48c5ccae
PZ
5363 * Ensures that the idle task is using init_mm right before its cpu goes
5364 * offline.
054b9108 5365 */
48c5ccae 5366void idle_task_exit(void)
1da177e4 5367{
48c5ccae 5368 struct mm_struct *mm = current->active_mm;
e76bd8d9 5369
48c5ccae 5370 BUG_ON(cpu_online(smp_processor_id()));
e76bd8d9 5371
48c5ccae
PZ
5372 if (mm != &init_mm)
5373 switch_mm(mm, &init_mm, current);
5374 mmdrop(mm);
1da177e4
LT
5375}
5376
5377/*
5d180232
PZ
5378 * Since this CPU is going 'away' for a while, fold any nr_active delta
5379 * we might have. Assumes we're called after migrate_tasks() so that the
5380 * nr_active count is stable.
5381 *
5382 * Also see the comment "Global load-average calculations".
1da177e4 5383 */
5d180232 5384static void calc_load_migrate(struct rq *rq)
1da177e4 5385{
5d180232
PZ
5386 long delta = calc_load_fold_active(rq);
5387 if (delta)
5388 atomic_long_add(delta, &calc_load_tasks);
1da177e4
LT
5389}
5390
48f24c4d 5391/*
48c5ccae
PZ
5392 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5393 * try_to_wake_up()->select_task_rq().
5394 *
5395 * Called with rq->lock held even though we'er in stop_machine() and
5396 * there's no concurrency possible, we hold the required locks anyway
5397 * because of lock validation efforts.
1da177e4 5398 */
48c5ccae 5399static void migrate_tasks(unsigned int dead_cpu)
1da177e4 5400{
70b97a7f 5401 struct rq *rq = cpu_rq(dead_cpu);
48c5ccae
PZ
5402 struct task_struct *next, *stop = rq->stop;
5403 int dest_cpu;
1da177e4
LT
5404
5405 /*
48c5ccae
PZ
5406 * Fudge the rq selection such that the below task selection loop
5407 * doesn't get stuck on the currently eligible stop task.
5408 *
5409 * We're currently inside stop_machine() and the rq is either stuck
5410 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5411 * either way we should never end up calling schedule() until we're
5412 * done here.
1da177e4 5413 */
48c5ccae 5414 rq->stop = NULL;
6fa3eb70
S
5415 /* MTK patch: prevent could not migrate RT task when RT throttle*/
5416 unthrottle_offline_rt_rqs(rq);
48f24c4d 5417
dd41f596 5418 for ( ; ; ) {
48c5ccae
PZ
5419 /*
5420 * There's this thread running, bail when that's the only
5421 * remaining thread.
5422 */
5423 if (rq->nr_running == 1)
dd41f596 5424 break;
48c5ccae 5425
b67802ea 5426 next = pick_next_task(rq);
48c5ccae 5427 BUG_ON(!next);
79c53799 5428 next->sched_class->put_prev_task(rq, next);
e692ab53 5429
48c5ccae
PZ
5430 /* Find suitable destination for @next, with force if needed. */
5431 dest_cpu = select_fallback_rq(dead_cpu, next);
5432 raw_spin_unlock(&rq->lock);
5433
5434 __migrate_task(next, dead_cpu, dest_cpu);
5435
5436 raw_spin_lock(&rq->lock);
1da177e4 5437 }
dce48a84 5438
48c5ccae 5439 rq->stop = stop;
dce48a84 5440}
48c5ccae 5441
1da177e4
LT
5442#endif /* CONFIG_HOTPLUG_CPU */
5443
e692ab53
NP
5444#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5445
5446static struct ctl_table sd_ctl_dir[] = {
e0361851
AD
5447 {
5448 .procname = "sched_domain",
c57baf1e 5449 .mode = 0555,
e0361851 5450 },
56992309 5451 {}
e692ab53
NP
5452};
5453
5454static struct ctl_table sd_ctl_root[] = {
e0361851
AD
5455 {
5456 .procname = "kernel",
c57baf1e 5457 .mode = 0555,
e0361851
AD
5458 .child = sd_ctl_dir,
5459 },
56992309 5460 {}
e692ab53
NP
5461};
5462
5463static struct ctl_table *sd_alloc_ctl_entry(int n)
5464{
5465 struct ctl_table *entry =
5cf9f062 5466 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
e692ab53 5467
e692ab53
NP
5468 return entry;
5469}
5470
6382bc90
MM
5471static void sd_free_ctl_entry(struct ctl_table **tablep)
5472{
cd790076 5473 struct ctl_table *entry;
6382bc90 5474
cd790076
MM
5475 /*
5476 * In the intermediate directories, both the child directory and
5477 * procname are dynamically allocated and could fail but the mode
41a2d6cf 5478 * will always be set. In the lowest directory the names are
cd790076
MM
5479 * static strings and all have proc handlers.
5480 */
5481 for (entry = *tablep; entry->mode; entry++) {
6382bc90
MM
5482 if (entry->child)
5483 sd_free_ctl_entry(&entry->child);
cd790076
MM
5484 if (entry->proc_handler == NULL)
5485 kfree(entry->procname);
5486 }
6382bc90
MM
5487
5488 kfree(*tablep);
5489 *tablep = NULL;
5490}
5491
201c373e 5492static int min_load_idx = 0;
fd9b86d3 5493static int max_load_idx = CPU_LOAD_IDX_MAX-1;
201c373e 5494
e692ab53 5495static void
e0361851 5496set_table_entry(struct ctl_table *entry,
e692ab53 5497 const char *procname, void *data, int maxlen,
201c373e
NK
5498 umode_t mode, proc_handler *proc_handler,
5499 bool load_idx)
e692ab53 5500{
e692ab53
NP
5501 entry->procname = procname;
5502 entry->data = data;
5503 entry->maxlen = maxlen;
5504 entry->mode = mode;
5505 entry->proc_handler = proc_handler;
201c373e
NK
5506
5507 if (load_idx) {
5508 entry->extra1 = &min_load_idx;
5509 entry->extra2 = &max_load_idx;
5510 }
e692ab53
NP
5511}
5512
5513static struct ctl_table *
5514sd_alloc_ctl_domain_table(struct sched_domain *sd)
5515{
a5d8c348 5516 struct ctl_table *table = sd_alloc_ctl_entry(13);
e692ab53 5517
ad1cdc1d
MM
5518 if (table == NULL)
5519 return NULL;
5520
e0361851 5521 set_table_entry(&table[0], "min_interval", &sd->min_interval,
201c373e 5522 sizeof(long), 0644, proc_doulongvec_minmax, false);
e0361851 5523 set_table_entry(&table[1], "max_interval", &sd->max_interval,
201c373e 5524 sizeof(long), 0644, proc_doulongvec_minmax, false);
e0361851 5525 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
201c373e 5526 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5527 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
201c373e 5528 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5529 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
201c373e 5530 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5531 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
201c373e 5532 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5533 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
201c373e 5534 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5535 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
201c373e 5536 sizeof(int), 0644, proc_dointvec_minmax, false);
e0361851 5537 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
201c373e 5538 sizeof(int), 0644, proc_dointvec_minmax, false);
ace8b3d6 5539 set_table_entry(&table[9], "cache_nice_tries",
e692ab53 5540 &sd->cache_nice_tries,
201c373e 5541 sizeof(int), 0644, proc_dointvec_minmax, false);
ace8b3d6 5542 set_table_entry(&table[10], "flags", &sd->flags,
201c373e 5543 sizeof(int), 0644, proc_dointvec_minmax, false);
a5d8c348 5544 set_table_entry(&table[11], "name", sd->name,
201c373e 5545 CORENAME_MAX_SIZE, 0444, proc_dostring, false);
a5d8c348 5546 /* &table[12] is terminator */
e692ab53
NP
5547
5548 return table;
5549}
5550
9a4e7159 5551static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
e692ab53
NP
5552{
5553 struct ctl_table *entry, *table;
5554 struct sched_domain *sd;
5555 int domain_num = 0, i;
5556 char buf[32];
5557
5558 for_each_domain(cpu, sd)
5559 domain_num++;
5560 entry = table = sd_alloc_ctl_entry(domain_num + 1);
ad1cdc1d
MM
5561 if (table == NULL)
5562 return NULL;
e692ab53
NP
5563
5564 i = 0;
5565 for_each_domain(cpu, sd) {
5566 snprintf(buf, 32, "domain%d", i);
e692ab53 5567 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5568 entry->mode = 0555;
e692ab53
NP
5569 entry->child = sd_alloc_ctl_domain_table(sd);
5570 entry++;
5571 i++;
5572 }
5573 return table;
5574}
5575
5576static struct ctl_table_header *sd_sysctl_header;
6382bc90 5577static void register_sched_domain_sysctl(void)
e692ab53 5578{
6ad4c188 5579 int i, cpu_num = num_possible_cpus();
e692ab53
NP
5580 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5581 char buf[32];
5582
7378547f
MM
5583 WARN_ON(sd_ctl_dir[0].child);
5584 sd_ctl_dir[0].child = entry;
5585
ad1cdc1d
MM
5586 if (entry == NULL)
5587 return;
5588
6ad4c188 5589 for_each_possible_cpu(i) {
e692ab53 5590 snprintf(buf, 32, "cpu%d", i);
e692ab53 5591 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5592 entry->mode = 0555;
e692ab53 5593 entry->child = sd_alloc_ctl_cpu_table(i);
97b6ea7b 5594 entry++;
e692ab53 5595 }
7378547f
MM
5596
5597 WARN_ON(sd_sysctl_header);
e692ab53
NP
5598 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5599}
6382bc90 5600
7378547f 5601/* may be called multiple times per register */
6382bc90
MM
5602static void unregister_sched_domain_sysctl(void)
5603{
7378547f
MM
5604 if (sd_sysctl_header)
5605 unregister_sysctl_table(sd_sysctl_header);
6382bc90 5606 sd_sysctl_header = NULL;
7378547f
MM
5607 if (sd_ctl_dir[0].child)
5608 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6382bc90 5609}
e692ab53 5610#else
6382bc90
MM
5611static void register_sched_domain_sysctl(void)
5612{
5613}
5614static void unregister_sched_domain_sysctl(void)
e692ab53
NP
5615{
5616}
5617#endif
5618
1f11eb6a
GH
5619static void set_rq_online(struct rq *rq)
5620{
5621 if (!rq->online) {
5622 const struct sched_class *class;
5623
c6c4927b 5624 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5625 rq->online = 1;
5626
5627 for_each_class(class) {
5628 if (class->rq_online)
5629 class->rq_online(rq);
5630 }
5631 }
5632}
5633
5634static void set_rq_offline(struct rq *rq)
5635{
5636 if (rq->online) {
5637 const struct sched_class *class;
5638
5639 for_each_class(class) {
5640 if (class->rq_offline)
5641 class->rq_offline(rq);
5642 }
5643
c6c4927b 5644 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5645 rq->online = 0;
5646 }
5647}
5648
1da177e4
LT
5649/*
5650 * migration_call - callback that gets triggered when a CPU is added.
5651 * Here we can start up the necessary migration thread for the new CPU.
5652 */
48f24c4d
IM
5653static int __cpuinit
5654migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
1da177e4 5655{
48f24c4d 5656 int cpu = (long)hcpu;
1da177e4 5657 unsigned long flags;
969c7921 5658 struct rq *rq = cpu_rq(cpu);
1da177e4 5659
48c5ccae 5660 switch (action & ~CPU_TASKS_FROZEN) {
5be9361c 5661
1da177e4 5662 case CPU_UP_PREPARE:
a468d389 5663 rq->calc_load_update = calc_load_update;
0579a127 5664 account_reset_rq(rq);
1da177e4 5665 break;
48f24c4d 5666
1da177e4 5667 case CPU_ONLINE:
1f94ef59 5668 /* Update our root-domain */
05fa785c 5669 raw_spin_lock_irqsave(&rq->lock, flags);
1f94ef59 5670 if (rq->rd) {
c6c4927b 5671 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
1f11eb6a 5672 set_rq_online(rq);
1f94ef59 5673 }
05fa785c 5674 raw_spin_unlock_irqrestore(&rq->lock, flags);
1da177e4 5675 break;
48f24c4d 5676
1da177e4 5677#ifdef CONFIG_HOTPLUG_CPU
08f503b0 5678 case CPU_DYING:
317f3941 5679 sched_ttwu_pending();
57d885fe 5680 /* Update our root-domain */
05fa785c 5681 raw_spin_lock_irqsave(&rq->lock, flags);
57d885fe 5682 if (rq->rd) {
c6c4927b 5683 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
1f11eb6a 5684 set_rq_offline(rq);
57d885fe 5685 }
48c5ccae
PZ
5686 migrate_tasks(cpu);
5687 BUG_ON(rq->nr_running != 1); /* the migration thread */
05fa785c 5688 raw_spin_unlock_irqrestore(&rq->lock, flags);
5d180232 5689 break;
48c5ccae 5690
5d180232 5691 case CPU_DEAD:
f319da0c 5692 calc_load_migrate(rq);
57d885fe 5693 break;
1da177e4
LT
5694#endif
5695 }
49c022e6
PZ
5696
5697 update_max_interval();
5698
1da177e4
LT
5699 return NOTIFY_OK;
5700}
5701
f38b0820
PM
5702/*
5703 * Register at high priority so that task migration (migrate_all_tasks)
5704 * happens before everything else. This has to be lower priority than
cdd6c482 5705 * the notifier in the perf_event subsystem, though.
1da177e4 5706 */
26c2143b 5707static struct notifier_block __cpuinitdata migration_notifier = {
1da177e4 5708 .notifier_call = migration_call,
50a323b7 5709 .priority = CPU_PRI_MIGRATION,
1da177e4
LT
5710};
5711
3a101d05
TH
5712static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5713 unsigned long action, void *hcpu)
5714{
5715 switch (action & ~CPU_TASKS_FROZEN) {
3a101d05
TH
5716 case CPU_DOWN_FAILED:
5717 set_cpu_active((long)hcpu, true);
5718 return NOTIFY_OK;
5719 default:
5720 return NOTIFY_DONE;
5721 }
5722}
5723
5724static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5725 unsigned long action, void *hcpu)
5726{
5727 switch (action & ~CPU_TASKS_FROZEN) {
5728 case CPU_DOWN_PREPARE:
5729 set_cpu_active((long)hcpu, false);
5730 return NOTIFY_OK;
5731 default:
5732 return NOTIFY_DONE;
5733 }
5734}
5735
7babe8db 5736static int __init migration_init(void)
1da177e4
LT
5737{
5738 void *cpu = (void *)(long)smp_processor_id();
07dccf33 5739 int err;
48f24c4d 5740
3a101d05 5741 /* Initialize migration for the boot CPU */
07dccf33
AM
5742 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5743 BUG_ON(err == NOTIFY_BAD);
1da177e4
LT
5744 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5745 register_cpu_notifier(&migration_notifier);
7babe8db 5746
3a101d05
TH
5747 /* Register cpu active notifiers */
5748 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5749 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5750
a004cd42 5751 return 0;
1da177e4 5752}
7babe8db 5753early_initcall(migration_init);
1da177e4
LT
5754#endif
5755
5756#ifdef CONFIG_SMP
476f3534 5757
4cb98839
PZ
5758static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5759
3e9830dc 5760#ifdef CONFIG_SCHED_DEBUG
4dcf6aff 5761
d039ac60 5762static __read_mostly int sched_debug_enabled;
f6630114 5763
d039ac60 5764static int __init sched_debug_setup(char *str)
f6630114 5765{
d039ac60 5766 sched_debug_enabled = 1;
f6630114
MT
5767
5768 return 0;
5769}
d039ac60
PZ
5770early_param("sched_debug", sched_debug_setup);
5771
5772static inline bool sched_debug(void)
5773{
5774 return sched_debug_enabled;
5775}
f6630114 5776
7c16ec58 5777static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
96f874e2 5778 struct cpumask *groupmask)
1da177e4 5779{
4dcf6aff 5780 struct sched_group *group = sd->groups;
434d53b0 5781 char str[256];
1da177e4 5782
968ea6d8 5783 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
96f874e2 5784 cpumask_clear(groupmask);
4dcf6aff
IM
5785
5786 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5787
5788 if (!(sd->flags & SD_LOAD_BALANCE)) {
3df0fc5b 5789 printk("does not load-balance\n");
4dcf6aff 5790 if (sd->parent)
3df0fc5b
PZ
5791 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5792 " has parent");
4dcf6aff 5793 return -1;
41c7ce9a
NP
5794 }
5795
3df0fc5b 5796 printk(KERN_CONT "span %s level %s\n", str, sd->name);
4dcf6aff 5797
758b2cdc 5798 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
3df0fc5b
PZ
5799 printk(KERN_ERR "ERROR: domain->span does not contain "
5800 "CPU%d\n", cpu);
4dcf6aff 5801 }
758b2cdc 5802 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
3df0fc5b
PZ
5803 printk(KERN_ERR "ERROR: domain->groups does not contain"
5804 " CPU%d\n", cpu);
4dcf6aff 5805 }
1da177e4 5806
4dcf6aff 5807 printk(KERN_DEBUG "%*s groups:", level + 1, "");
1da177e4 5808 do {
4dcf6aff 5809 if (!group) {
3df0fc5b
PZ
5810 printk("\n");
5811 printk(KERN_ERR "ERROR: group is NULL\n");
1da177e4
LT
5812 break;
5813 }
5814
c3decf0d
PZ
5815 /*
5816 * Even though we initialize ->power to something semi-sane,
5817 * we leave power_orig unset. This allows us to detect if
5818 * domain iteration is still funny without causing /0 traps.
5819 */
5820 if (!group->sgp->power_orig) {
3df0fc5b
PZ
5821 printk(KERN_CONT "\n");
5822 printk(KERN_ERR "ERROR: domain->cpu_power not "
5823 "set\n");
4dcf6aff
IM
5824 break;
5825 }
1da177e4 5826
758b2cdc 5827 if (!cpumask_weight(sched_group_cpus(group))) {
3df0fc5b
PZ
5828 printk(KERN_CONT "\n");
5829 printk(KERN_ERR "ERROR: empty group\n");
4dcf6aff
IM
5830 break;
5831 }
1da177e4 5832
cb83b629
PZ
5833 if (!(sd->flags & SD_OVERLAP) &&
5834 cpumask_intersects(groupmask, sched_group_cpus(group))) {
3df0fc5b
PZ
5835 printk(KERN_CONT "\n");
5836 printk(KERN_ERR "ERROR: repeated CPUs\n");
4dcf6aff
IM
5837 break;
5838 }
1da177e4 5839
758b2cdc 5840 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
1da177e4 5841
968ea6d8 5842 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
381512cf 5843
3df0fc5b 5844 printk(KERN_CONT " %s", str);
9c3f75cb 5845 if (group->sgp->power != SCHED_POWER_SCALE) {
3df0fc5b 5846 printk(KERN_CONT " (cpu_power = %d)",
9c3f75cb 5847 group->sgp->power);
381512cf 5848 }
1da177e4 5849
4dcf6aff
IM
5850 group = group->next;
5851 } while (group != sd->groups);
3df0fc5b 5852 printk(KERN_CONT "\n");
1da177e4 5853
758b2cdc 5854 if (!cpumask_equal(sched_domain_span(sd), groupmask))
3df0fc5b 5855 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
1da177e4 5856
758b2cdc
RR
5857 if (sd->parent &&
5858 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
3df0fc5b
PZ
5859 printk(KERN_ERR "ERROR: parent span is not a superset "
5860 "of domain->span\n");
4dcf6aff
IM
5861 return 0;
5862}
1da177e4 5863
4dcf6aff
IM
5864static void sched_domain_debug(struct sched_domain *sd, int cpu)
5865{
5866 int level = 0;
1da177e4 5867
d039ac60 5868 if (!sched_debug_enabled)
f6630114
MT
5869 return;
5870
4dcf6aff
IM
5871 if (!sd) {
5872 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5873 return;
5874 }
1da177e4 5875
4dcf6aff
IM
5876 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5877
5878 for (;;) {
4cb98839 5879 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
4dcf6aff 5880 break;
1da177e4
LT
5881 level++;
5882 sd = sd->parent;
33859f7f 5883 if (!sd)
4dcf6aff
IM
5884 break;
5885 }
1da177e4 5886}
6d6bc0ad 5887#else /* !CONFIG_SCHED_DEBUG */
48f24c4d 5888# define sched_domain_debug(sd, cpu) do { } while (0)
d039ac60
PZ
5889static inline bool sched_debug(void)
5890{
5891 return false;
5892}
6d6bc0ad 5893#endif /* CONFIG_SCHED_DEBUG */
1da177e4 5894
1a20ff27 5895static int sd_degenerate(struct sched_domain *sd)
245af2c7 5896{
758b2cdc 5897 if (cpumask_weight(sched_domain_span(sd)) == 1)
245af2c7
SS
5898 return 1;
5899
5900 /* Following flags need at least 2 groups */
5901 if (sd->flags & (SD_LOAD_BALANCE |
5902 SD_BALANCE_NEWIDLE |
5903 SD_BALANCE_FORK |
89c4710e
SS
5904 SD_BALANCE_EXEC |
5905 SD_SHARE_CPUPOWER |
5906 SD_SHARE_PKG_RESOURCES)) {
245af2c7
SS
5907 if (sd->groups != sd->groups->next)
5908 return 0;
5909 }
5910
5911 /* Following flags don't use groups */
c88d5910 5912 if (sd->flags & (SD_WAKE_AFFINE))
245af2c7
SS
5913 return 0;
5914
5915 return 1;
5916}
5917
48f24c4d
IM
5918static int
5919sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
245af2c7
SS
5920{
5921 unsigned long cflags = sd->flags, pflags = parent->flags;
5922
5923 if (sd_degenerate(parent))
5924 return 1;
5925
758b2cdc 5926 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
245af2c7
SS
5927 return 0;
5928
245af2c7
SS
5929 /* Flags needing groups don't count if only 1 group in parent */
5930 if (parent->groups == parent->groups->next) {
5931 pflags &= ~(SD_LOAD_BALANCE |
5932 SD_BALANCE_NEWIDLE |
5933 SD_BALANCE_FORK |
89c4710e
SS
5934 SD_BALANCE_EXEC |
5935 SD_SHARE_CPUPOWER |
5936 SD_SHARE_PKG_RESOURCES);
5436499e
KC
5937 if (nr_node_ids == 1)
5938 pflags &= ~SD_SERIALIZE;
245af2c7
SS
5939 }
5940 if (~cflags & pflags)
5941 return 0;
5942
5943 return 1;
5944}
5945
dce840a0 5946static void free_rootdomain(struct rcu_head *rcu)
c6c4927b 5947{
dce840a0 5948 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
047106ad 5949
68e74568 5950 cpupri_cleanup(&rd->cpupri);
c6c4927b
RR
5951 free_cpumask_var(rd->rto_mask);
5952 free_cpumask_var(rd->online);
5953 free_cpumask_var(rd->span);
5954 kfree(rd);
5955}
5956
57d885fe
GH
5957static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5958{
a0490fa3 5959 struct root_domain *old_rd = NULL;
57d885fe 5960 unsigned long flags;
57d885fe 5961
05fa785c 5962 raw_spin_lock_irqsave(&rq->lock, flags);
57d885fe
GH
5963
5964 if (rq->rd) {
a0490fa3 5965 old_rd = rq->rd;
57d885fe 5966
c6c4927b 5967 if (cpumask_test_cpu(rq->cpu, old_rd->online))
1f11eb6a 5968 set_rq_offline(rq);
57d885fe 5969
c6c4927b 5970 cpumask_clear_cpu(rq->cpu, old_rd->span);
dc938520 5971
a0490fa3
IM
5972 /*
5973 * If we dont want to free the old_rt yet then
5974 * set old_rd to NULL to skip the freeing later
5975 * in this function:
5976 */
5977 if (!atomic_dec_and_test(&old_rd->refcount))
5978 old_rd = NULL;
57d885fe
GH
5979 }
5980
5981 atomic_inc(&rd->refcount);
5982 rq->rd = rd;
5983
c6c4927b 5984 cpumask_set_cpu(rq->cpu, rd->span);
00aec93d 5985 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
1f11eb6a 5986 set_rq_online(rq);
57d885fe 5987
05fa785c 5988 raw_spin_unlock_irqrestore(&rq->lock, flags);
a0490fa3
IM
5989
5990 if (old_rd)
dce840a0 5991 call_rcu_sched(&old_rd->rcu, free_rootdomain);
57d885fe
GH
5992}
5993
68c38fc3 5994static int init_rootdomain(struct root_domain *rd)
57d885fe
GH
5995{
5996 memset(rd, 0, sizeof(*rd));
5997
68c38fc3 5998 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
0c910d28 5999 goto out;
68c38fc3 6000 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
c6c4927b 6001 goto free_span;
68c38fc3 6002 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
c6c4927b 6003 goto free_online;
6e0534f2 6004
68c38fc3 6005 if (cpupri_init(&rd->cpupri) != 0)
68e74568 6006 goto free_rto_mask;
c6c4927b 6007 return 0;
6e0534f2 6008
68e74568
RR
6009free_rto_mask:
6010 free_cpumask_var(rd->rto_mask);
c6c4927b
RR
6011free_online:
6012 free_cpumask_var(rd->online);
6013free_span:
6014 free_cpumask_var(rd->span);
0c910d28 6015out:
c6c4927b 6016 return -ENOMEM;
57d885fe
GH
6017}
6018
029632fb
PZ
6019/*
6020 * By default the system creates a single root-domain with all cpus as
6021 * members (mimicking the global state we have today).
6022 */
6023struct root_domain def_root_domain;
6024
57d885fe
GH
6025static void init_defrootdomain(void)
6026{
68c38fc3 6027 init_rootdomain(&def_root_domain);
c6c4927b 6028
57d885fe
GH
6029 atomic_set(&def_root_domain.refcount, 1);
6030}
6031
dc938520 6032static struct root_domain *alloc_rootdomain(void)
57d885fe
GH
6033{
6034 struct root_domain *rd;
6035
6036 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6037 if (!rd)
6038 return NULL;
6039
68c38fc3 6040 if (init_rootdomain(rd) != 0) {
c6c4927b
RR
6041 kfree(rd);
6042 return NULL;
6043 }
57d885fe
GH
6044
6045 return rd;
6046}
6047
e3589f6c
PZ
6048static void free_sched_groups(struct sched_group *sg, int free_sgp)
6049{
6050 struct sched_group *tmp, *first;
6051
6052 if (!sg)
6053 return;
6054
6055 first = sg;
6056 do {
6057 tmp = sg->next;
6058
6059 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
6060 kfree(sg->sgp);
6061
6062 kfree(sg);
6063 sg = tmp;
6064 } while (sg != first);
6065}
6066
dce840a0
PZ
6067static void free_sched_domain(struct rcu_head *rcu)
6068{
6069 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
e3589f6c
PZ
6070
6071 /*
6072 * If its an overlapping domain it has private groups, iterate and
6073 * nuke them all.
6074 */
6075 if (sd->flags & SD_OVERLAP) {
6076 free_sched_groups(sd->groups, 1);
6077 } else if (atomic_dec_and_test(&sd->groups->ref)) {
9c3f75cb 6078 kfree(sd->groups->sgp);
dce840a0 6079 kfree(sd->groups);
9c3f75cb 6080 }
dce840a0
PZ
6081 kfree(sd);
6082}
6083
6084static void destroy_sched_domain(struct sched_domain *sd, int cpu)
6085{
6086 call_rcu(&sd->rcu, free_sched_domain);
6087}
6088
6089static void destroy_sched_domains(struct sched_domain *sd, int cpu)
6090{
6091 for (; sd; sd = sd->parent)
6092 destroy_sched_domain(sd, cpu);
6093}
6094
518cd623
PZ
6095/*
6096 * Keep a special pointer to the highest sched_domain that has
6097 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
6098 * allows us to avoid some pointer chasing select_idle_sibling().
6099 *
6100 * Also keep a unique ID per domain (we use the first cpu number in
6101 * the cpumask of the domain), this allows us to quickly tell if
39be3501 6102 * two cpus are in the same cache domain, see cpus_share_cache().
518cd623
PZ
6103 */
6104DEFINE_PER_CPU(struct sched_domain *, sd_llc);
6105DEFINE_PER_CPU(int, sd_llc_id);
6106
6107static void update_top_cache_domain(int cpu)
6108{
6109 struct sched_domain *sd;
6110 int id = cpu;
6111
6112 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
37407ea7 6113 if (sd)
518cd623
PZ
6114 id = cpumask_first(sched_domain_span(sd));
6115
6116 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
6117 per_cpu(sd_llc_id, cpu) = id;
6118}
6119
1da177e4 6120/*
0eab9146 6121 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
1da177e4
LT
6122 * hold the hotplug lock.
6123 */
0eab9146
IM
6124static void
6125cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
1da177e4 6126{
70b97a7f 6127 struct rq *rq = cpu_rq(cpu);
245af2c7
SS
6128 struct sched_domain *tmp;
6129
6130 /* Remove the sched domains which do not contribute to scheduling. */
f29c9b1c 6131 for (tmp = sd; tmp; ) {
245af2c7
SS
6132 struct sched_domain *parent = tmp->parent;
6133 if (!parent)
6134 break;
f29c9b1c 6135
1a848870 6136 if (sd_parent_degenerate(tmp, parent)) {
245af2c7 6137 tmp->parent = parent->parent;
1a848870
SS
6138 if (parent->parent)
6139 parent->parent->child = tmp;
dce840a0 6140 destroy_sched_domain(parent, cpu);
f29c9b1c
LZ
6141 } else
6142 tmp = tmp->parent;
245af2c7
SS
6143 }
6144
1a848870 6145 if (sd && sd_degenerate(sd)) {
dce840a0 6146 tmp = sd;
245af2c7 6147 sd = sd->parent;
dce840a0 6148 destroy_sched_domain(tmp, cpu);
1a848870
SS
6149 if (sd)
6150 sd->child = NULL;
6151 }
1da177e4 6152
4cb98839 6153 sched_domain_debug(sd, cpu);
1da177e4 6154
57d885fe 6155 rq_attach_root(rq, rd);
dce840a0 6156 tmp = rq->sd;
674311d5 6157 rcu_assign_pointer(rq->sd, sd);
dce840a0 6158 destroy_sched_domains(tmp, cpu);
518cd623 6159
6fa3eb70
S
6160#if defined (CONFIG_MTK_SCHED_CMP_PACK_SMALL_TASK) || defined (CONFIG_HMP_PACK_SMALL_TASK)
6161 update_packing_domain(cpu);
6162#endif /* CONFIG_MTK_SCHED_CMP_PACK_SMALL_TASK || CONFIG_HMP_PACK_SMALL_TASK */
518cd623 6163 update_top_cache_domain(cpu);
1da177e4
LT
6164}
6165
6166/* cpus with isolated domains */
dcc30a35 6167static cpumask_var_t cpu_isolated_map;
1da177e4
LT
6168
6169/* Setup the mask of cpus configured for isolated domains */
6170static int __init isolated_cpu_setup(char *str)
6171{
bdddd296 6172 alloc_bootmem_cpumask_var(&cpu_isolated_map);
968ea6d8 6173 cpulist_parse(str, cpu_isolated_map);
1da177e4
LT
6174 return 1;
6175}
6176
8927f494 6177__setup("isolcpus=", isolated_cpu_setup);
1da177e4 6178
d3081f52
PZ
6179static const struct cpumask *cpu_cpu_mask(int cpu)
6180{
6181 return cpumask_of_node(cpu_to_node(cpu));
6182}
6183
dce840a0
PZ
6184struct sd_data {
6185 struct sched_domain **__percpu sd;
6186 struct sched_group **__percpu sg;
9c3f75cb 6187 struct sched_group_power **__percpu sgp;
dce840a0
PZ
6188};
6189
49a02c51 6190struct s_data {
21d42ccf 6191 struct sched_domain ** __percpu sd;
49a02c51
AH
6192 struct root_domain *rd;
6193};
6194
2109b99e 6195enum s_alloc {
2109b99e 6196 sa_rootdomain,
21d42ccf 6197 sa_sd,
dce840a0 6198 sa_sd_storage,
2109b99e
AH
6199 sa_none,
6200};
6201
54ab4ff4
PZ
6202struct sched_domain_topology_level;
6203
6204typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
eb7a74e6
PZ
6205typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
6206
e3589f6c
PZ
6207#define SDTL_OVERLAP 0x01
6208
eb7a74e6 6209struct sched_domain_topology_level {
2c402dc3
PZ
6210 sched_domain_init_f init;
6211 sched_domain_mask_f mask;
e3589f6c 6212 int flags;
cb83b629 6213 int numa_level;
54ab4ff4 6214 struct sd_data data;
eb7a74e6
PZ
6215};
6216
c1174876
PZ
6217/*
6218 * Build an iteration mask that can exclude certain CPUs from the upwards
6219 * domain traversal.
6220 *
6221 * Asymmetric node setups can result in situations where the domain tree is of
6222 * unequal depth, make sure to skip domains that already cover the entire
6223 * range.
6224 *
6225 * In that case build_sched_domains() will have terminated the iteration early
6226 * and our sibling sd spans will be empty. Domains should always include the
6227 * cpu they're built on, so check that.
6228 *
6229 */
6230static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
6231{
6232 const struct cpumask *span = sched_domain_span(sd);
6233 struct sd_data *sdd = sd->private;
6234 struct sched_domain *sibling;
6235 int i;
6236
6237 for_each_cpu(i, span) {
6238 sibling = *per_cpu_ptr(sdd->sd, i);
6239 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6240 continue;
6241
6242 cpumask_set_cpu(i, sched_group_mask(sg));
6243 }
6244}
6245
6246/*
6247 * Return the canonical balance cpu for this group, this is the first cpu
6248 * of this group that's also in the iteration mask.
6249 */
6250int group_balance_cpu(struct sched_group *sg)
6251{
6252 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6253}
6254
e3589f6c
PZ
6255static int
6256build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6257{
6258 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6259 const struct cpumask *span = sched_domain_span(sd);
6260 struct cpumask *covered = sched_domains_tmpmask;
6261 struct sd_data *sdd = sd->private;
6262 struct sched_domain *child;
6263 int i;
6264
6265 cpumask_clear(covered);
6266
6267 for_each_cpu(i, span) {
6268 struct cpumask *sg_span;
6269
6270 if (cpumask_test_cpu(i, covered))
6271 continue;
6272
c1174876
PZ
6273 child = *per_cpu_ptr(sdd->sd, i);
6274
6275 /* See the comment near build_group_mask(). */
6276 if (!cpumask_test_cpu(i, sched_domain_span(child)))
6277 continue;
6278
e3589f6c 6279 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
4d78a223 6280 GFP_KERNEL, cpu_to_node(cpu));
e3589f6c
PZ
6281
6282 if (!sg)
6283 goto fail;
6284
6285 sg_span = sched_group_cpus(sg);
e3589f6c
PZ
6286 if (child->child) {
6287 child = child->child;
6288 cpumask_copy(sg_span, sched_domain_span(child));
6289 } else
6290 cpumask_set_cpu(i, sg_span);
6291
6292 cpumask_or(covered, covered, sg_span);
6293
74a5ce20 6294 sg->sgp = *per_cpu_ptr(sdd->sgp, i);
c1174876
PZ
6295 if (atomic_inc_return(&sg->sgp->ref) == 1)
6296 build_group_mask(sd, sg);
6297
c3decf0d
PZ
6298 /*
6299 * Initialize sgp->power such that even if we mess up the
6300 * domains and no possible iteration will get us here, we won't
6301 * die on a /0 trap.
6302 */
6303 sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span);
e3589f6c 6304
c1174876
PZ
6305 /*
6306 * Make sure the first group of this domain contains the
6307 * canonical balance cpu. Otherwise the sched_domain iteration
6308 * breaks. See update_sg_lb_stats().
6309 */
74a5ce20 6310 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
c1174876 6311 group_balance_cpu(sg) == cpu)
e3589f6c
PZ
6312 groups = sg;
6313
6314 if (!first)
6315 first = sg;
6316 if (last)
6317 last->next = sg;
6318 last = sg;
6319 last->next = first;
6320 }
6321 sd->groups = groups;
6322
6323 return 0;
6324
6325fail:
6326 free_sched_groups(first, 0);
6327
6328 return -ENOMEM;
6329}
6330
dce840a0 6331static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
1da177e4 6332{
dce840a0
PZ
6333 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6334 struct sched_domain *child = sd->child;
1da177e4 6335
dce840a0
PZ
6336 if (child)
6337 cpu = cpumask_first(sched_domain_span(child));
1e9f28fa 6338
9c3f75cb 6339 if (sg) {
dce840a0 6340 *sg = *per_cpu_ptr(sdd->sg, cpu);
9c3f75cb 6341 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
e3589f6c 6342 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
9c3f75cb 6343 }
dce840a0
PZ
6344
6345 return cpu;
1e9f28fa 6346}
1e9f28fa 6347
01a08546 6348/*
dce840a0
PZ
6349 * build_sched_groups will build a circular linked list of the groups
6350 * covered by the given span, and will set each group's ->cpumask correctly,
6351 * and ->cpu_power to 0.
e3589f6c
PZ
6352 *
6353 * Assumes the sched_domain tree is fully constructed
01a08546 6354 */
e3589f6c
PZ
6355static int
6356build_sched_groups(struct sched_domain *sd, int cpu)
1da177e4 6357{
dce840a0
PZ
6358 struct sched_group *first = NULL, *last = NULL;
6359 struct sd_data *sdd = sd->private;
6360 const struct cpumask *span = sched_domain_span(sd);
f96225fd 6361 struct cpumask *covered;
dce840a0 6362 int i;
9c1cfda2 6363
e3589f6c
PZ
6364 get_group(cpu, sdd, &sd->groups);
6365 atomic_inc(&sd->groups->ref);
6366
6367 if (cpu != cpumask_first(sched_domain_span(sd)))
6368 return 0;
6369
f96225fd
PZ
6370 lockdep_assert_held(&sched_domains_mutex);
6371 covered = sched_domains_tmpmask;
6372
dce840a0 6373 cpumask_clear(covered);
6711cab4 6374
dce840a0
PZ
6375 for_each_cpu(i, span) {
6376 struct sched_group *sg;
6377 int group = get_group(i, sdd, &sg);
6378 int j;
6711cab4 6379
dce840a0
PZ
6380 if (cpumask_test_cpu(i, covered))
6381 continue;
6711cab4 6382
dce840a0 6383 cpumask_clear(sched_group_cpus(sg));
9c3f75cb 6384 sg->sgp->power = 0;
c1174876 6385 cpumask_setall(sched_group_mask(sg));
0601a88d 6386
dce840a0
PZ
6387 for_each_cpu(j, span) {
6388 if (get_group(j, sdd, NULL) != group)
6389 continue;
0601a88d 6390
dce840a0
PZ
6391 cpumask_set_cpu(j, covered);
6392 cpumask_set_cpu(j, sched_group_cpus(sg));
6393 }
0601a88d 6394
dce840a0
PZ
6395 if (!first)
6396 first = sg;
6397 if (last)
6398 last->next = sg;
6399 last = sg;
6400 }
6401 last->next = first;
e3589f6c
PZ
6402
6403 return 0;
0601a88d 6404}
51888ca2 6405
89c4710e
SS
6406/*
6407 * Initialize sched groups cpu_power.
6408 *
6409 * cpu_power indicates the capacity of sched group, which is used while
6410 * distributing the load between different sched groups in a sched domain.
6411 * Typically cpu_power for all the groups in a sched domain will be same unless
6412 * there are asymmetries in the topology. If there are asymmetries, group
6413 * having more cpu_power will pickup more load compared to the group having
6414 * less cpu_power.
89c4710e
SS
6415 */
6416static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6417{
e3589f6c 6418 struct sched_group *sg = sd->groups;
89c4710e 6419
e3589f6c
PZ
6420 WARN_ON(!sd || !sg);
6421
6422 do {
6423 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6424 sg = sg->next;
6425 } while (sg != sd->groups);
89c4710e 6426
c1174876 6427 if (cpu != group_balance_cpu(sg))
e3589f6c 6428 return;
aae6d3dd 6429
d274cb30 6430 update_group_power(sd, cpu);
69e1e811 6431 atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
89c4710e
SS
6432}
6433
029632fb
PZ
6434int __weak arch_sd_sibling_asym_packing(void)
6435{
6436 return 0*SD_ASYM_PACKING;
89c4710e
SS
6437}
6438
6fa3eb70
S
6439#if defined (CONFIG_MTK_SCHED_CMP_PACK_SMALL_TASK) || defined (CONFIG_HMP_PACK_SMALL_TASK)
6440int __weak arch_sd_share_power_line(void)
6441{
6442 return 0*SD_SHARE_POWERLINE;
6443}
6444#endif /* CONFIG_MTK_SCHED_CMP_PACK_SMALL_TASK || CONFIG_HMP_PACK_SMALL_TASK */
7c16ec58
MT
6445/*
6446 * Initializers for schedule domains
6447 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6448 */
6449
a5d8c348
IM
6450#ifdef CONFIG_SCHED_DEBUG
6451# define SD_INIT_NAME(sd, type) sd->name = #type
6452#else
6453# define SD_INIT_NAME(sd, type) do { } while (0)
6454#endif
6455
54ab4ff4
PZ
6456#define SD_INIT_FUNC(type) \
6457static noinline struct sched_domain * \
6458sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
6459{ \
6460 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
6461 *sd = SD_##type##_INIT; \
54ab4ff4
PZ
6462 SD_INIT_NAME(sd, type); \
6463 sd->private = &tl->data; \
6464 return sd; \
7c16ec58
MT
6465}
6466
6467SD_INIT_FUNC(CPU)
7c16ec58
MT
6468#ifdef CONFIG_SCHED_SMT
6469 SD_INIT_FUNC(SIBLING)
6470#endif
6471#ifdef CONFIG_SCHED_MC
6472 SD_INIT_FUNC(MC)
6473#endif
01a08546
HC
6474#ifdef CONFIG_SCHED_BOOK
6475 SD_INIT_FUNC(BOOK)
6476#endif
7c16ec58 6477
1d3504fc 6478static int default_relax_domain_level = -1;
60495e77 6479int sched_domain_level_max;
1d3504fc
HS
6480
6481static int __init setup_relax_domain_level(char *str)
6482{
a841f8ce
DS
6483 if (kstrtoint(str, 0, &default_relax_domain_level))
6484 pr_warn("Unable to set relax_domain_level\n");
30e0e178 6485
1d3504fc
HS
6486 return 1;
6487}
6488__setup("relax_domain_level=", setup_relax_domain_level);
6489
6490static void set_domain_attribute(struct sched_domain *sd,
6491 struct sched_domain_attr *attr)
6492{
6493 int request;
6494
6495 if (!attr || attr->relax_domain_level < 0) {
6496 if (default_relax_domain_level < 0)
6497 return;
6498 else
6499 request = default_relax_domain_level;
6500 } else
6501 request = attr->relax_domain_level;
6502 if (request < sd->level) {
6503 /* turn off idle balance on this domain */
c88d5910 6504 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
1d3504fc
HS
6505 } else {
6506 /* turn on idle balance on this domain */
c88d5910 6507 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
1d3504fc
HS
6508 }
6509}
6510
54ab4ff4
PZ
6511static void __sdt_free(const struct cpumask *cpu_map);
6512static int __sdt_alloc(const struct cpumask *cpu_map);
6513
2109b99e
AH
6514static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6515 const struct cpumask *cpu_map)
6516{
6517 switch (what) {
2109b99e 6518 case sa_rootdomain:
822ff793
PZ
6519 if (!atomic_read(&d->rd->refcount))
6520 free_rootdomain(&d->rd->rcu); /* fall through */
21d42ccf
PZ
6521 case sa_sd:
6522 free_percpu(d->sd); /* fall through */
dce840a0 6523 case sa_sd_storage:
54ab4ff4 6524 __sdt_free(cpu_map); /* fall through */
2109b99e
AH
6525 case sa_none:
6526 break;
6527 }
6528}
3404c8d9 6529
2109b99e
AH
6530static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6531 const struct cpumask *cpu_map)
6532{
dce840a0
PZ
6533 memset(d, 0, sizeof(*d));
6534
54ab4ff4
PZ
6535 if (__sdt_alloc(cpu_map))
6536 return sa_sd_storage;
dce840a0
PZ
6537 d->sd = alloc_percpu(struct sched_domain *);
6538 if (!d->sd)
6539 return sa_sd_storage;
2109b99e 6540 d->rd = alloc_rootdomain();
dce840a0 6541 if (!d->rd)
21d42ccf 6542 return sa_sd;
2109b99e
AH
6543 return sa_rootdomain;
6544}
57d885fe 6545
dce840a0
PZ
6546/*
6547 * NULL the sd_data elements we've used to build the sched_domain and
6548 * sched_group structure so that the subsequent __free_domain_allocs()
6549 * will not free the data we're using.
6550 */
6551static void claim_allocations(int cpu, struct sched_domain *sd)
6552{
6553 struct sd_data *sdd = sd->private;
dce840a0
PZ
6554
6555 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6556 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6557
e3589f6c 6558 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
dce840a0 6559 *per_cpu_ptr(sdd->sg, cpu) = NULL;
e3589f6c
PZ
6560
6561 if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
9c3f75cb 6562 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
dce840a0
PZ
6563}
6564
2c402dc3
PZ
6565#ifdef CONFIG_SCHED_SMT
6566static const struct cpumask *cpu_smt_mask(int cpu)
7f4588f3 6567{
2c402dc3 6568 return topology_thread_cpumask(cpu);
3bd65a80 6569}
2c402dc3 6570#endif
7f4588f3 6571
d069b916
PZ
6572/*
6573 * Topology list, bottom-up.
6574 */
2c402dc3 6575static struct sched_domain_topology_level default_topology[] = {
d069b916
PZ
6576#ifdef CONFIG_SCHED_SMT
6577 { sd_init_SIBLING, cpu_smt_mask, },
01a08546 6578#endif
1e9f28fa 6579#ifdef CONFIG_SCHED_MC
2c402dc3 6580 { sd_init_MC, cpu_coregroup_mask, },
1e9f28fa 6581#endif
d069b916
PZ
6582#ifdef CONFIG_SCHED_BOOK
6583 { sd_init_BOOK, cpu_book_mask, },
6584#endif
6585 { sd_init_CPU, cpu_cpu_mask, },
eb7a74e6
PZ
6586 { NULL, },
6587};
6588
6589static struct sched_domain_topology_level *sched_domain_topology = default_topology;
6590
cb83b629
PZ
6591#ifdef CONFIG_NUMA
6592
6593static int sched_domains_numa_levels;
cb83b629
PZ
6594static int *sched_domains_numa_distance;
6595static struct cpumask ***sched_domains_numa_masks;
6596static int sched_domains_curr_level;
6597
cb83b629
PZ
6598static inline int sd_local_flags(int level)
6599{
10717dcd 6600 if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE)
cb83b629
PZ
6601 return 0;
6602
6603 return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE;
6604}
6605
6606static struct sched_domain *
6607sd_numa_init(struct sched_domain_topology_level *tl, int cpu)
6608{
6609 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6610 int level = tl->numa_level;
6611 int sd_weight = cpumask_weight(
6612 sched_domains_numa_masks[level][cpu_to_node(cpu)]);
6613
6614 *sd = (struct sched_domain){
6615 .min_interval = sd_weight,
6616 .max_interval = 2*sd_weight,
6617 .busy_factor = 32,
870a0bb5 6618 .imbalance_pct = 125,
cb83b629
PZ
6619 .cache_nice_tries = 2,
6620 .busy_idx = 3,
6621 .idle_idx = 2,
6622 .newidle_idx = 0,
6623 .wake_idx = 0,
6624 .forkexec_idx = 0,
6625
6626 .flags = 1*SD_LOAD_BALANCE
6627 | 1*SD_BALANCE_NEWIDLE
6628 | 0*SD_BALANCE_EXEC
6629 | 0*SD_BALANCE_FORK
6630 | 0*SD_BALANCE_WAKE
6631 | 0*SD_WAKE_AFFINE
cb83b629 6632 | 0*SD_SHARE_CPUPOWER
cb83b629
PZ
6633 | 0*SD_SHARE_PKG_RESOURCES
6634 | 1*SD_SERIALIZE
6635 | 0*SD_PREFER_SIBLING
6636 | sd_local_flags(level)
6637 ,
6638 .last_balance = jiffies,
6639 .balance_interval = sd_weight,
6640 };
6641 SD_INIT_NAME(sd, NUMA);
6642 sd->private = &tl->data;
6643
6644 /*
6645 * Ugly hack to pass state to sd_numa_mask()...
6646 */
6647 sched_domains_curr_level = tl->numa_level;
6648
6649 return sd;
6650}
6651
6652static const struct cpumask *sd_numa_mask(int cpu)
6653{
6654 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6655}
6656
d039ac60
PZ
6657static void sched_numa_warn(const char *str)
6658{
6659 static int done = false;
6660 int i,j;
6661
6662 if (done)
6663 return;
6664
6665 done = true;
6666
6667 printk(KERN_WARNING "ERROR: %s\n\n", str);
6668
6669 for (i = 0; i < nr_node_ids; i++) {
6670 printk(KERN_WARNING " ");
6671 for (j = 0; j < nr_node_ids; j++)
6672 printk(KERN_CONT "%02d ", node_distance(i,j));
6673 printk(KERN_CONT "\n");
6674 }
6675 printk(KERN_WARNING "\n");
6676}
6677
6678static bool find_numa_distance(int distance)
6679{
6680 int i;
6681
6682 if (distance == node_distance(0, 0))
6683 return true;
6684
6685 for (i = 0; i < sched_domains_numa_levels; i++) {
6686 if (sched_domains_numa_distance[i] == distance)
6687 return true;
6688 }
6689
6690 return false;
6691}
6692
cb83b629
PZ
6693static void sched_init_numa(void)
6694{
6695 int next_distance, curr_distance = node_distance(0, 0);
6696 struct sched_domain_topology_level *tl;
6697 int level = 0;
6698 int i, j, k;
6699
cb83b629
PZ
6700 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6701 if (!sched_domains_numa_distance)
6702 return;
6703
6704 /*
6705 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6706 * unique distances in the node_distance() table.
6707 *
6708 * Assumes node_distance(0,j) includes all distances in
6709 * node_distance(i,j) in order to avoid cubic time.
cb83b629
PZ
6710 */
6711 next_distance = curr_distance;
6712 for (i = 0; i < nr_node_ids; i++) {
6713 for (j = 0; j < nr_node_ids; j++) {
d039ac60
PZ
6714 for (k = 0; k < nr_node_ids; k++) {
6715 int distance = node_distance(i, k);
6716
6717 if (distance > curr_distance &&
6718 (distance < next_distance ||
6719 next_distance == curr_distance))
6720 next_distance = distance;
6721
6722 /*
6723 * While not a strong assumption it would be nice to know
6724 * about cases where if node A is connected to B, B is not
6725 * equally connected to A.
6726 */
6727 if (sched_debug() && node_distance(k, i) != distance)
6728 sched_numa_warn("Node-distance not symmetric");
6729
6730 if (sched_debug() && i && !find_numa_distance(distance))
6731 sched_numa_warn("Node-0 not representative");
6732 }
6733 if (next_distance != curr_distance) {
6734 sched_domains_numa_distance[level++] = next_distance;
6735 sched_domains_numa_levels = level;
6736 curr_distance = next_distance;
6737 } else break;
cb83b629 6738 }
d039ac60
PZ
6739
6740 /*
6741 * In case of sched_debug() we verify the above assumption.
6742 */
6743 if (!sched_debug())
6744 break;
cb83b629
PZ
6745 }
6746 /*
6747 * 'level' contains the number of unique distances, excluding the
6748 * identity distance node_distance(i,i).
6749 *
28b4a521 6750 * The sched_domains_numa_distance[] array includes the actual distance
cb83b629
PZ
6751 * numbers.
6752 */
6753
5f7865f3
TC
6754 /*
6755 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6756 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6757 * the array will contain less then 'level' members. This could be
6758 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6759 * in other functions.
6760 *
6761 * We reset it to 'level' at the end of this function.
6762 */
6763 sched_domains_numa_levels = 0;
6764
cb83b629
PZ
6765 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6766 if (!sched_domains_numa_masks)
6767 return;
6768
6769 /*
6770 * Now for each level, construct a mask per node which contains all
6771 * cpus of nodes that are that many hops away from us.
6772 */
6773 for (i = 0; i < level; i++) {
6774 sched_domains_numa_masks[i] =
6775 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6776 if (!sched_domains_numa_masks[i])
6777 return;
6778
6779 for (j = 0; j < nr_node_ids; j++) {
2ea45800 6780 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
cb83b629
PZ
6781 if (!mask)
6782 return;
6783
6784 sched_domains_numa_masks[i][j] = mask;
6785
6786 for (k = 0; k < nr_node_ids; k++) {
dd7d8634 6787 if (node_distance(j, k) > sched_domains_numa_distance[i])
cb83b629
PZ
6788 continue;
6789
6790 cpumask_or(mask, mask, cpumask_of_node(k));
6791 }
6792 }
6793 }
6794
6795 tl = kzalloc((ARRAY_SIZE(default_topology) + level) *
6796 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6797 if (!tl)
6798 return;
6799
6800 /*
6801 * Copy the default topology bits..
6802 */
6803 for (i = 0; default_topology[i].init; i++)
6804 tl[i] = default_topology[i];
6805
6806 /*
6807 * .. and append 'j' levels of NUMA goodness.
6808 */
6809 for (j = 0; j < level; i++, j++) {
6810 tl[i] = (struct sched_domain_topology_level){
6811 .init = sd_numa_init,
6812 .mask = sd_numa_mask,
6813 .flags = SDTL_OVERLAP,
6814 .numa_level = j,
6815 };
6816 }
6817
6818 sched_domain_topology = tl;
5f7865f3
TC
6819
6820 sched_domains_numa_levels = level;
cb83b629 6821}
301a5cba
TC
6822
6823static void sched_domains_numa_masks_set(int cpu)
6824{
6825 int i, j;
6826 int node = cpu_to_node(cpu);
6827
6828 for (i = 0; i < sched_domains_numa_levels; i++) {
6829 for (j = 0; j < nr_node_ids; j++) {
6830 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6831 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6832 }
6833 }
6834}
6835
6836static void sched_domains_numa_masks_clear(int cpu)
6837{
6838 int i, j;
6839 for (i = 0; i < sched_domains_numa_levels; i++) {
6840 for (j = 0; j < nr_node_ids; j++)
6841 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6842 }
6843}
6844
6845/*
6846 * Update sched_domains_numa_masks[level][node] array when new cpus
6847 * are onlined.
6848 */
6849static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6850 unsigned long action,
6851 void *hcpu)
6852{
6853 int cpu = (long)hcpu;
6854
6855 switch (action & ~CPU_TASKS_FROZEN) {
6856 case CPU_ONLINE:
6857 sched_domains_numa_masks_set(cpu);
6858 break;
6859
6860 case CPU_DEAD:
6861 sched_domains_numa_masks_clear(cpu);
6862 break;
6863
6864 default:
6865 return NOTIFY_DONE;
6866 }
6867
6868 return NOTIFY_OK;
cb83b629
PZ
6869}
6870#else
6871static inline void sched_init_numa(void)
6872{
6873}
301a5cba
TC
6874
6875static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6876 unsigned long action,
6877 void *hcpu)
6878{
6879 return 0;
6880}
cb83b629
PZ
6881#endif /* CONFIG_NUMA */
6882
54ab4ff4
PZ
6883static int __sdt_alloc(const struct cpumask *cpu_map)
6884{
6885 struct sched_domain_topology_level *tl;
6886 int j;
6887
6888 for (tl = sched_domain_topology; tl->init; tl++) {
6889 struct sd_data *sdd = &tl->data;
6890
6891 sdd->sd = alloc_percpu(struct sched_domain *);
6892 if (!sdd->sd)
6893 return -ENOMEM;
6894
6895 sdd->sg = alloc_percpu(struct sched_group *);
6896 if (!sdd->sg)
6897 return -ENOMEM;
6898
9c3f75cb
PZ
6899 sdd->sgp = alloc_percpu(struct sched_group_power *);
6900 if (!sdd->sgp)
6901 return -ENOMEM;
6902
54ab4ff4
PZ
6903 for_each_cpu(j, cpu_map) {
6904 struct sched_domain *sd;
6905 struct sched_group *sg;
9c3f75cb 6906 struct sched_group_power *sgp;
54ab4ff4
PZ
6907
6908 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6909 GFP_KERNEL, cpu_to_node(j));
6910 if (!sd)
6911 return -ENOMEM;
6912
6913 *per_cpu_ptr(sdd->sd, j) = sd;
6914
6915 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6916 GFP_KERNEL, cpu_to_node(j));
6917 if (!sg)
6918 return -ENOMEM;
6919
30b4e9eb
IM
6920 sg->next = sg;
6921
54ab4ff4 6922 *per_cpu_ptr(sdd->sg, j) = sg;
9c3f75cb 6923
c1174876 6924 sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(),
9c3f75cb
PZ
6925 GFP_KERNEL, cpu_to_node(j));
6926 if (!sgp)
6927 return -ENOMEM;
6928
6929 *per_cpu_ptr(sdd->sgp, j) = sgp;
54ab4ff4
PZ
6930 }
6931 }
6932
6933 return 0;
6934}
6935
6936static void __sdt_free(const struct cpumask *cpu_map)
6937{
6938 struct sched_domain_topology_level *tl;
6939 int j;
6940
6941 for (tl = sched_domain_topology; tl->init; tl++) {
6942 struct sd_data *sdd = &tl->data;
6943
6944 for_each_cpu(j, cpu_map) {
fb2cf2c6 6945 struct sched_domain *sd;
6946
6947 if (sdd->sd) {
6948 sd = *per_cpu_ptr(sdd->sd, j);
6949 if (sd && (sd->flags & SD_OVERLAP))
6950 free_sched_groups(sd->groups, 0);
6951 kfree(*per_cpu_ptr(sdd->sd, j));
6952 }
6953
6954 if (sdd->sg)
6955 kfree(*per_cpu_ptr(sdd->sg, j));
6956 if (sdd->sgp)
6957 kfree(*per_cpu_ptr(sdd->sgp, j));
54ab4ff4
PZ
6958 }
6959 free_percpu(sdd->sd);
fb2cf2c6 6960 sdd->sd = NULL;
54ab4ff4 6961 free_percpu(sdd->sg);
fb2cf2c6 6962 sdd->sg = NULL;
9c3f75cb 6963 free_percpu(sdd->sgp);
fb2cf2c6 6964 sdd->sgp = NULL;
54ab4ff4
PZ
6965 }
6966}
6967
2c402dc3
PZ
6968struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6969 struct s_data *d, const struct cpumask *cpu_map,
d069b916 6970 struct sched_domain_attr *attr, struct sched_domain *child,
2c402dc3
PZ
6971 int cpu)
6972{
54ab4ff4 6973 struct sched_domain *sd = tl->init(tl, cpu);
2c402dc3 6974 if (!sd)
d069b916 6975 return child;
2c402dc3 6976
2c402dc3 6977 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
60495e77
PZ
6978 if (child) {
6979 sd->level = child->level + 1;
6980 sched_domain_level_max = max(sched_domain_level_max, sd->level);
d069b916 6981 child->parent = sd;
60495e77 6982 }
d069b916 6983 sd->child = child;
a841f8ce 6984 set_domain_attribute(sd, attr);
2c402dc3
PZ
6985
6986 return sd;
6987}
6988
2109b99e
AH
6989/*
6990 * Build sched domains for a given set of cpus and attach the sched domains
6991 * to the individual cpus
6992 */
dce840a0
PZ
6993static int build_sched_domains(const struct cpumask *cpu_map,
6994 struct sched_domain_attr *attr)
2109b99e
AH
6995{
6996 enum s_alloc alloc_state = sa_none;
dce840a0 6997 struct sched_domain *sd;
2109b99e 6998 struct s_data d;
822ff793 6999 int i, ret = -ENOMEM;
9c1cfda2 7000
2109b99e
AH
7001 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7002 if (alloc_state != sa_rootdomain)
7003 goto error;
9c1cfda2 7004
dce840a0 7005 /* Set up domains for cpus specified by the cpu_map. */
abcd083a 7006 for_each_cpu(i, cpu_map) {
eb7a74e6
PZ
7007 struct sched_domain_topology_level *tl;
7008
3bd65a80 7009 sd = NULL;
e3589f6c 7010 for (tl = sched_domain_topology; tl->init; tl++) {
2c402dc3 7011 sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
e3589f6c
PZ
7012 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7013 sd->flags |= SD_OVERLAP;
d110235d
PZ
7014 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7015 break;
e3589f6c 7016 }
d274cb30 7017
d069b916
PZ
7018 while (sd->child)
7019 sd = sd->child;
7020
21d42ccf 7021 *per_cpu_ptr(d.sd, i) = sd;
dce840a0
PZ
7022 }
7023
7024 /* Build the groups for the domains */
7025 for_each_cpu(i, cpu_map) {
7026 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7027 sd->span_weight = cpumask_weight(sched_domain_span(sd));
e3589f6c
PZ
7028 if (sd->flags & SD_OVERLAP) {
7029 if (build_overlap_sched_groups(sd, i))
7030 goto error;
7031 } else {
7032 if (build_sched_groups(sd, i))
7033 goto error;
7034 }
1cf51902 7035 }
a06dadbe 7036 }
9c1cfda2 7037
1da177e4 7038 /* Calculate CPU power for physical packages and nodes */
a9c9a9b6
PZ
7039 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7040 if (!cpumask_test_cpu(i, cpu_map))
7041 continue;
9c1cfda2 7042
dce840a0
PZ
7043 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7044 claim_allocations(i, sd);
cd4ea6ae 7045 init_sched_groups_power(i, sd);
dce840a0 7046 }
f712c0c7 7047 }
9c1cfda2 7048
1da177e4 7049 /* Attach the domains */
dce840a0 7050 rcu_read_lock();
abcd083a 7051 for_each_cpu(i, cpu_map) {
21d42ccf 7052 sd = *per_cpu_ptr(d.sd, i);
49a02c51 7053 cpu_attach_domain(sd, d.rd, i);
1da177e4 7054 }
dce840a0 7055 rcu_read_unlock();
51888ca2 7056
822ff793 7057 ret = 0;
51888ca2 7058error:
2109b99e 7059 __free_domain_allocs(&d, alloc_state, cpu_map);
822ff793 7060 return ret;
1da177e4 7061}
029190c5 7062
acc3f5d7 7063static cpumask_var_t *doms_cur; /* current sched domains */
029190c5 7064static int ndoms_cur; /* number of sched domains in 'doms_cur' */
4285f594
IM
7065static struct sched_domain_attr *dattr_cur;
7066 /* attribues of custom domains in 'doms_cur' */
029190c5
PJ
7067
7068/*
7069 * Special case: If a kmalloc of a doms_cur partition (array of
4212823f
RR
7070 * cpumask) fails, then fallback to a single sched domain,
7071 * as determined by the single cpumask fallback_doms.
029190c5 7072 */
4212823f 7073static cpumask_var_t fallback_doms;
029190c5 7074
ee79d1bd
HC
7075/*
7076 * arch_update_cpu_topology lets virtualized architectures update the
7077 * cpu core maps. It is supposed to return 1 if the topology changed
7078 * or 0 if it stayed the same.
7079 */
7080int __attribute__((weak)) arch_update_cpu_topology(void)
22e52b07 7081{
ee79d1bd 7082 return 0;
22e52b07
HC
7083}
7084
acc3f5d7
RR
7085cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7086{
7087 int i;
7088 cpumask_var_t *doms;
7089
7090 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7091 if (!doms)
7092 return NULL;
7093 for (i = 0; i < ndoms; i++) {
7094 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7095 free_sched_domains(doms, i);
7096 return NULL;
7097 }
7098 }
7099 return doms;
7100}
7101
7102void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7103{
7104 unsigned int i;
7105 for (i = 0; i < ndoms; i++)
7106 free_cpumask_var(doms[i]);
7107 kfree(doms);
7108}
7109
1a20ff27 7110/*
41a2d6cf 7111 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
029190c5
PJ
7112 * For now this just excludes isolated cpus, but could be used to
7113 * exclude other special cases in the future.
1a20ff27 7114 */
c4a8849a 7115static int init_sched_domains(const struct cpumask *cpu_map)
1a20ff27 7116{
7378547f
MM
7117 int err;
7118
22e52b07 7119 arch_update_cpu_topology();
029190c5 7120 ndoms_cur = 1;
acc3f5d7 7121 doms_cur = alloc_sched_domains(ndoms_cur);
029190c5 7122 if (!doms_cur)
acc3f5d7
RR
7123 doms_cur = &fallback_doms;
7124 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
dce840a0 7125 err = build_sched_domains(doms_cur[0], NULL);
6382bc90 7126 register_sched_domain_sysctl();
7378547f
MM
7127
7128 return err;
1a20ff27
DG
7129}
7130
1a20ff27
DG
7131/*
7132 * Detach sched domains from a group of cpus specified in cpu_map
7133 * These cpus will now be attached to the NULL domain
7134 */
96f874e2 7135static void detach_destroy_domains(const struct cpumask *cpu_map)
1a20ff27
DG
7136{
7137 int i;
7138
dce840a0 7139 rcu_read_lock();
abcd083a 7140 for_each_cpu(i, cpu_map)
57d885fe 7141 cpu_attach_domain(NULL, &def_root_domain, i);
dce840a0 7142 rcu_read_unlock();
1a20ff27
DG
7143}
7144
1d3504fc
HS
7145/* handle null as "default" */
7146static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7147 struct sched_domain_attr *new, int idx_new)
7148{
7149 struct sched_domain_attr tmp;
7150
7151 /* fast path */
7152 if (!new && !cur)
7153 return 1;
7154
7155 tmp = SD_ATTR_INIT;
7156 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7157 new ? (new + idx_new) : &tmp,
7158 sizeof(struct sched_domain_attr));
7159}
7160
029190c5
PJ
7161/*
7162 * Partition sched domains as specified by the 'ndoms_new'
41a2d6cf 7163 * cpumasks in the array doms_new[] of cpumasks. This compares
029190c5
PJ
7164 * doms_new[] to the current sched domain partitioning, doms_cur[].
7165 * It destroys each deleted domain and builds each new domain.
7166 *
acc3f5d7 7167 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
41a2d6cf
IM
7168 * The masks don't intersect (don't overlap.) We should setup one
7169 * sched domain for each mask. CPUs not in any of the cpumasks will
7170 * not be load balanced. If the same cpumask appears both in the
029190c5
PJ
7171 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7172 * it as it is.
7173 *
acc3f5d7
RR
7174 * The passed in 'doms_new' should be allocated using
7175 * alloc_sched_domains. This routine takes ownership of it and will
7176 * free_sched_domains it when done with it. If the caller failed the
7177 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7178 * and partition_sched_domains() will fallback to the single partition
7179 * 'fallback_doms', it also forces the domains to be rebuilt.
029190c5 7180 *
96f874e2 7181 * If doms_new == NULL it will be replaced with cpu_online_mask.
700018e0
LZ
7182 * ndoms_new == 0 is a special case for destroying existing domains,
7183 * and it will not create the default domain.
dfb512ec 7184 *
029190c5
PJ
7185 * Call with hotplug lock held
7186 */
acc3f5d7 7187void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1d3504fc 7188 struct sched_domain_attr *dattr_new)
029190c5 7189{
dfb512ec 7190 int i, j, n;
d65bd5ec 7191 int new_topology;
029190c5 7192
712555ee 7193 mutex_lock(&sched_domains_mutex);
a1835615 7194
7378547f
MM
7195 /* always unregister in case we don't destroy any domains */
7196 unregister_sched_domain_sysctl();
7197
d65bd5ec
HC
7198 /* Let architecture update cpu core mappings. */
7199 new_topology = arch_update_cpu_topology();
7200
dfb512ec 7201 n = doms_new ? ndoms_new : 0;
029190c5
PJ
7202
7203 /* Destroy deleted domains */
7204 for (i = 0; i < ndoms_cur; i++) {
d65bd5ec 7205 for (j = 0; j < n && !new_topology; j++) {
acc3f5d7 7206 if (cpumask_equal(doms_cur[i], doms_new[j])
1d3504fc 7207 && dattrs_equal(dattr_cur, i, dattr_new, j))
029190c5
PJ
7208 goto match1;
7209 }
7210 /* no match - a current sched domain not in new doms_new[] */
acc3f5d7 7211 detach_destroy_domains(doms_cur[i]);
029190c5
PJ
7212match1:
7213 ;
7214 }
7215
e761b772
MK
7216 if (doms_new == NULL) {
7217 ndoms_cur = 0;
acc3f5d7 7218 doms_new = &fallback_doms;
6ad4c188 7219 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
faa2f98f 7220 WARN_ON_ONCE(dattr_new);
e761b772
MK
7221 }
7222
029190c5
PJ
7223 /* Build new domains */
7224 for (i = 0; i < ndoms_new; i++) {
d65bd5ec 7225 for (j = 0; j < ndoms_cur && !new_topology; j++) {
acc3f5d7 7226 if (cpumask_equal(doms_new[i], doms_cur[j])
1d3504fc 7227 && dattrs_equal(dattr_new, i, dattr_cur, j))
029190c5
PJ
7228 goto match2;
7229 }
7230 /* no match - add a new doms_new */
dce840a0 7231 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
029190c5
PJ
7232match2:
7233 ;
7234 }
7235
7236 /* Remember the new sched domains */
acc3f5d7
RR
7237 if (doms_cur != &fallback_doms)
7238 free_sched_domains(doms_cur, ndoms_cur);
1d3504fc 7239 kfree(dattr_cur); /* kfree(NULL) is safe */
029190c5 7240 doms_cur = doms_new;
1d3504fc 7241 dattr_cur = dattr_new;
029190c5 7242 ndoms_cur = ndoms_new;
7378547f
MM
7243
7244 register_sched_domain_sysctl();
a1835615 7245
712555ee 7246 mutex_unlock(&sched_domains_mutex);
029190c5
PJ
7247}
7248
d35be8ba
SB
7249static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
7250
1da177e4 7251/*
3a101d05
TH
7252 * Update cpusets according to cpu_active mask. If cpusets are
7253 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7254 * around partition_sched_domains().
d35be8ba
SB
7255 *
7256 * If we come here as part of a suspend/resume, don't touch cpusets because we
7257 * want to restore it back to its original state upon resume anyway.
1da177e4 7258 */
0b2e918a
TH
7259static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7260 void *hcpu)
e761b772 7261{
d35be8ba
SB
7262 switch (action) {
7263 case CPU_ONLINE_FROZEN:
7264 case CPU_DOWN_FAILED_FROZEN:
7265
7266 /*
7267 * num_cpus_frozen tracks how many CPUs are involved in suspend
7268 * resume sequence. As long as this is not the last online
7269 * operation in the resume sequence, just build a single sched
7270 * domain, ignoring cpusets.
7271 */
7272 num_cpus_frozen--;
7273 if (likely(num_cpus_frozen)) {
7274 partition_sched_domains(1, NULL, NULL);
7275 break;
7276 }
7277
7278 /*
7279 * This is the last CPU online operation. So fall through and
7280 * restore the original sched domains by considering the
7281 * cpuset configurations.
7282 */
7283
e761b772 7284 case CPU_ONLINE:
6ad4c188 7285 case CPU_DOWN_FAILED:
7ddf96b0 7286 cpuset_update_active_cpus(true);
d35be8ba 7287 break;
3a101d05
TH
7288 default:
7289 return NOTIFY_DONE;
7290 }
d35be8ba 7291 return NOTIFY_OK;
3a101d05 7292}
e761b772 7293
0b2e918a
TH
7294static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7295 void *hcpu)
3a101d05 7296{
d35be8ba 7297 switch (action) {
3a101d05 7298 case CPU_DOWN_PREPARE:
7ddf96b0 7299 cpuset_update_active_cpus(false);
d35be8ba
SB
7300 break;
7301 case CPU_DOWN_PREPARE_FROZEN:
7302 num_cpus_frozen++;
7303 partition_sched_domains(1, NULL, NULL);
7304 break;
e761b772
MK
7305 default:
7306 return NOTIFY_DONE;
7307 }
d35be8ba 7308 return NOTIFY_OK;
e761b772 7309}
e761b772 7310
1da177e4
LT
7311void __init sched_init_smp(void)
7312{
dcc30a35
RR
7313 cpumask_var_t non_isolated_cpus;
7314
7315 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
cb5fd13f 7316 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
5c1e1767 7317
cb83b629
PZ
7318 sched_init_numa();
7319
95402b38 7320 get_online_cpus();
712555ee 7321 mutex_lock(&sched_domains_mutex);
c4a8849a 7322 init_sched_domains(cpu_active_mask);
dcc30a35
RR
7323 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7324 if (cpumask_empty(non_isolated_cpus))
7325 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
712555ee 7326 mutex_unlock(&sched_domains_mutex);
95402b38 7327 put_online_cpus();
e761b772 7328
301a5cba 7329 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
3a101d05
TH
7330 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7331 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
e761b772
MK
7332
7333 /* RT runtime code needs to handle some hotplug events */
7334 hotcpu_notifier(update_runtime, 0);
7335
b328ca18 7336 init_hrtick();
5c1e1767
NP
7337
7338 /* Move init over to a non-isolated CPU */
dcc30a35 7339 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
5c1e1767 7340 BUG();
19978ca6 7341 sched_init_granularity();
dcc30a35 7342 free_cpumask_var(non_isolated_cpus);
4212823f 7343
0e3900e6 7344 init_sched_rt_class();
1da177e4
LT
7345}
7346#else
7347void __init sched_init_smp(void)
7348{
19978ca6 7349 sched_init_granularity();
1da177e4
LT
7350}
7351#endif /* CONFIG_SMP */
7352
cd1bb94b
AB
7353const_debug unsigned int sysctl_timer_migration = 1;
7354
1da177e4
LT
7355int in_sched_functions(unsigned long addr)
7356{
1da177e4
LT
7357 return in_lock_functions(addr) ||
7358 (addr >= (unsigned long)__sched_text_start
7359 && addr < (unsigned long)__sched_text_end);
7360}
7361
029632fb 7362#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
7363/*
7364 * Default task group.
7365 * Every task in system belongs to this group at bootup.
7366 */
029632fb 7367struct task_group root_task_group;
35cf4e50 7368LIST_HEAD(task_groups);
052f1dc7 7369#endif
6f505b16 7370
e6252c3e 7371DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
6f505b16 7372
1da177e4
LT
7373void __init sched_init(void)
7374{
dd41f596 7375 int i, j;
434d53b0
MT
7376 unsigned long alloc_size = 0, ptr;
7377
7378#ifdef CONFIG_FAIR_GROUP_SCHED
7379 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7380#endif
7381#ifdef CONFIG_RT_GROUP_SCHED
7382 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
eff766a6 7383#endif
df7c8e84 7384#ifdef CONFIG_CPUMASK_OFFSTACK
8c083f08 7385 alloc_size += num_possible_cpus() * cpumask_size();
434d53b0 7386#endif
434d53b0 7387 if (alloc_size) {
36b7b6d4 7388 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
434d53b0
MT
7389
7390#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 7391 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
7392 ptr += nr_cpu_ids * sizeof(void **);
7393
07e06b01 7394 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 7395 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 7396
6d6bc0ad 7397#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 7398#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 7399 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
7400 ptr += nr_cpu_ids * sizeof(void **);
7401
07e06b01 7402 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
7403 ptr += nr_cpu_ids * sizeof(void **);
7404
6d6bc0ad 7405#endif /* CONFIG_RT_GROUP_SCHED */
df7c8e84
RR
7406#ifdef CONFIG_CPUMASK_OFFSTACK
7407 for_each_possible_cpu(i) {
e6252c3e 7408 per_cpu(load_balance_mask, i) = (void *)ptr;
df7c8e84
RR
7409 ptr += cpumask_size();
7410 }
7411#endif /* CONFIG_CPUMASK_OFFSTACK */
434d53b0 7412 }
dd41f596 7413
57d885fe
GH
7414#ifdef CONFIG_SMP
7415 init_defrootdomain();
7416#endif
7417
d0b27fa7
PZ
7418 init_rt_bandwidth(&def_rt_bandwidth,
7419 global_rt_period(), global_rt_runtime());
7420
7421#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 7422 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 7423 global_rt_period(), global_rt_runtime());
6d6bc0ad 7424#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 7425
7c941438 7426#ifdef CONFIG_CGROUP_SCHED
07e06b01
YZ
7427 list_add(&root_task_group.list, &task_groups);
7428 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 7429 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 7430 autogroup_init(&init_task);
54c707e9 7431
7c941438 7432#endif /* CONFIG_CGROUP_SCHED */
6f505b16 7433
0a945022 7434 for_each_possible_cpu(i) {
70b97a7f 7435 struct rq *rq;
1da177e4
LT
7436
7437 rq = cpu_rq(i);
05fa785c 7438 raw_spin_lock_init(&rq->lock);
7897986b 7439 rq->nr_running = 0;
dce48a84
TG
7440 rq->calc_load_active = 0;
7441 rq->calc_load_update = jiffies + LOAD_FREQ;
6fa3eb70
S
7442#ifdef CONFIG_PROVE_LOCKING
7443 rq->cpu = i;
7444#endif
acb5a9ba 7445 init_cfs_rq(&rq->cfs);
6f505b16 7446 init_rt_rq(&rq->rt, rq);
dd41f596 7447#ifdef CONFIG_FAIR_GROUP_SCHED
029632fb 7448 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6f505b16 7449 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
354d60c2 7450 /*
07e06b01 7451 * How much cpu bandwidth does root_task_group get?
354d60c2
DG
7452 *
7453 * In case of task-groups formed thr' the cgroup filesystem, it
7454 * gets 100% of the cpu resources in the system. This overall
7455 * system cpu resource is divided among the tasks of
07e06b01 7456 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
7457 * based on each entity's (task or task-group's) weight
7458 * (se->load.weight).
7459 *
07e06b01 7460 * In other words, if root_task_group has 10 tasks of weight
354d60c2
DG
7461 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7462 * then A0's share of the cpu resource is:
7463 *
0d905bca 7464 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 7465 *
07e06b01
YZ
7466 * We achieve this by letting root_task_group's tasks sit
7467 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 7468 */
ab84d31e 7469 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
07e06b01 7470 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
7471#endif /* CONFIG_FAIR_GROUP_SCHED */
7472
7473 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 7474#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 7475 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
07e06b01 7476 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 7477#endif
1da177e4 7478
dd41f596
IM
7479 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7480 rq->cpu_load[j] = 0;
fdf3e95d
VP
7481
7482 rq->last_load_update_tick = jiffies;
7483
1da177e4 7484#ifdef CONFIG_SMP
41c7ce9a 7485 rq->sd = NULL;
57d885fe 7486 rq->rd = NULL;
1399fa78 7487 rq->cpu_power = SCHED_POWER_SCALE;
3f029d3c 7488 rq->post_schedule = 0;
1da177e4 7489 rq->active_balance = 0;
dd41f596 7490 rq->next_balance = jiffies;
1da177e4 7491 rq->push_cpu = 0;
0a2966b4 7492 rq->cpu = i;
1f11eb6a 7493 rq->online = 0;
eae0c9df
MG
7494 rq->idle_stamp = 0;
7495 rq->avg_idle = 2*sysctl_sched_migration_cost;
367456c7
PZ
7496
7497 INIT_LIST_HEAD(&rq->cfs_tasks);
7498
dc938520 7499 rq_attach_root(rq, &def_root_domain);
3451d024 7500#ifdef CONFIG_NO_HZ_COMMON
1c792db7 7501 rq->nohz_flags = 0;
83cd4fe2 7502#endif
265f22a9
FW
7503#ifdef CONFIG_NO_HZ_FULL
7504 rq->last_sched_tick = 0;
7505#endif
1da177e4 7506#endif
8f4d37ec 7507 init_rq_hrtick(rq);
1da177e4 7508 atomic_set(&rq->nr_iowait, 0);
1da177e4
LT
7509 }
7510
2dd73a4f 7511 set_load_weight(&init_task);
b50f60ce 7512
e107be36
AK
7513#ifdef CONFIG_PREEMPT_NOTIFIERS
7514 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7515#endif
7516
b50f60ce 7517#ifdef CONFIG_RT_MUTEXES
732375c6 7518 plist_head_init(&init_task.pi_waiters);
b50f60ce
HC
7519#endif
7520
1da177e4
LT
7521 /*
7522 * The boot idle thread does lazy MMU switching as well:
7523 */
7524 atomic_inc(&init_mm.mm_count);
7525 enter_lazy_tlb(&init_mm, current);
7526
7527 /*
7528 * Make us the idle thread. Technically, schedule() should not be
7529 * called from this thread, however somewhere below it might be,
7530 * but because we are the idle thread, we just pick up running again
7531 * when this runqueue becomes "idle".
7532 */
7533 init_idle(current, smp_processor_id());
dce48a84
TG
7534
7535 calc_load_update = jiffies + LOAD_FREQ;
7536
dd41f596
IM
7537 /*
7538 * During early bootup we pretend to be a normal task:
7539 */
7540 current->sched_class = &fair_sched_class;
6892b75e 7541
bf4d83f6 7542#ifdef CONFIG_SMP
4cb98839 7543 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
bdddd296
RR
7544 /* May be allocated at isolcpus cmdline parse time */
7545 if (cpu_isolated_map == NULL)
7546 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
29d5e047 7547 idle_thread_set_boot_cpu();
029632fb
PZ
7548#endif
7549 init_sched_fair_class();
6a7b3dc3 7550
6892b75e 7551 scheduler_running = 1;
1da177e4
LT
7552}
7553
d902db1e 7554#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2
FW
7555static inline int preempt_count_equals(int preempt_offset)
7556{
234da7bc 7557 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
e4aafea2 7558
4ba8216c 7559 return (nested == preempt_offset);
e4aafea2
FW
7560}
7561
6fa3eb70
S
7562static int __might_sleep_init_called;
7563int __init __might_sleep_init(void)
7564{
7565 __might_sleep_init_called = 1;
7566 return 0;
7567}
7568early_initcall(__might_sleep_init);
7569
d894837f 7570void __might_sleep(const char *file, int line, int preempt_offset)
1da177e4 7571{
1da177e4
LT
7572 static unsigned long prev_jiffy; /* ratelimiting */
7573
b3fbab05 7574 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
e4aafea2 7575 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
6fa3eb70
S
7576 oops_in_progress)
7577 return;
7578 if (system_state != SYSTEM_RUNNING &&
7579 (!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
aef745fc
IM
7580 return;
7581 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7582 return;
7583 prev_jiffy = jiffies;
7584
3df0fc5b
PZ
7585 printk(KERN_ERR
7586 "BUG: sleeping function called from invalid context at %s:%d\n",
7587 file, line);
7588 printk(KERN_ERR
7589 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7590 in_atomic(), irqs_disabled(),
7591 current->pid, current->comm);
aef745fc
IM
7592
7593 debug_show_held_locks(current);
7594 if (irqs_disabled())
7595 print_irqtrace_events(current);
7596 dump_stack();
1da177e4
LT
7597}
7598EXPORT_SYMBOL(__might_sleep);
7599#endif
7600
7601#ifdef CONFIG_MAGIC_SYSRQ
3a5e4dc1
AK
7602static void normalize_task(struct rq *rq, struct task_struct *p)
7603{
da7a735e
PZ
7604 const struct sched_class *prev_class = p->sched_class;
7605 int old_prio = p->prio;
3a5e4dc1 7606 int on_rq;
3e51f33f 7607
fd2f4419 7608 on_rq = p->on_rq;
3a5e4dc1 7609 if (on_rq)
4ca9b72b 7610 dequeue_task(rq, p, 0);
3a5e4dc1
AK
7611 __setscheduler(rq, p, SCHED_NORMAL, 0);
7612 if (on_rq) {
4ca9b72b 7613 enqueue_task(rq, p, 0);
3a5e4dc1
AK
7614 resched_task(rq->curr);
7615 }
da7a735e
PZ
7616
7617 check_class_changed(rq, p, prev_class, old_prio);
3a5e4dc1
AK
7618}
7619
1da177e4
LT
7620void normalize_rt_tasks(void)
7621{
a0f98a1c 7622 struct task_struct *g, *p;
1da177e4 7623 unsigned long flags;
70b97a7f 7624 struct rq *rq;
1da177e4 7625
4cf5d77a 7626 read_lock_irqsave(&tasklist_lock, flags);
a0f98a1c 7627 do_each_thread(g, p) {
178be793
IM
7628 /*
7629 * Only normalize user tasks:
7630 */
7631 if (!p->mm)
7632 continue;
7633
6cfb0d5d 7634 p->se.exec_start = 0;
6cfb0d5d 7635#ifdef CONFIG_SCHEDSTATS
41acab88
LDM
7636 p->se.statistics.wait_start = 0;
7637 p->se.statistics.sleep_start = 0;
7638 p->se.statistics.block_start = 0;
6cfb0d5d 7639#endif
dd41f596
IM
7640
7641 if (!rt_task(p)) {
7642 /*
7643 * Renice negative nice level userspace
7644 * tasks back to 0:
7645 */
7646 if (TASK_NICE(p) < 0 && p->mm)
7647 set_user_nice(p, 0);
1da177e4 7648 continue;
dd41f596 7649 }
1da177e4 7650
1d615482 7651 raw_spin_lock(&p->pi_lock);
b29739f9 7652 rq = __task_rq_lock(p);
1da177e4 7653
178be793 7654 normalize_task(rq, p);
3a5e4dc1 7655
b29739f9 7656 __task_rq_unlock(rq);
1d615482 7657 raw_spin_unlock(&p->pi_lock);
a0f98a1c
IM
7658 } while_each_thread(g, p);
7659
4cf5d77a 7660 read_unlock_irqrestore(&tasklist_lock, flags);
1da177e4
LT
7661}
7662
7663#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 7664
67fc4e0c 7665#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 7666/*
67fc4e0c 7667 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
7668 *
7669 * They can only be called when the whole system has been
7670 * stopped - every CPU needs to be quiescent, and no scheduling
7671 * activity can take place. Using them for anything else would
7672 * be a serious bug, and as a result, they aren't even visible
7673 * under any other configuration.
7674 */
7675
7676/**
7677 * curr_task - return the current task for a given cpu.
7678 * @cpu: the processor in question.
7679 *
7680 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7681 */
36c8b586 7682struct task_struct *curr_task(int cpu)
1df5c10a
LT
7683{
7684 return cpu_curr(cpu);
7685}
7686
67fc4e0c
JW
7687#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7688
7689#ifdef CONFIG_IA64
1df5c10a
LT
7690/**
7691 * set_curr_task - set the current task for a given cpu.
7692 * @cpu: the processor in question.
7693 * @p: the task pointer to set.
7694 *
7695 * Description: This function must only be used when non-maskable interrupts
41a2d6cf
IM
7696 * are serviced on a separate stack. It allows the architecture to switch the
7697 * notion of the current task on a cpu in a non-blocking manner. This function
1df5c10a
LT
7698 * must be called with all CPU's synchronized, and interrupts disabled, the
7699 * and caller must save the original value of the current task (see
7700 * curr_task() above) and restore that value before reenabling interrupts and
7701 * re-starting the system.
7702 *
7703 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7704 */
36c8b586 7705void set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
7706{
7707 cpu_curr(cpu) = p;
7708}
7709
7710#endif
29f59db3 7711
7c941438 7712#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
7713/* task_group_lock serializes the addition/removal of task groups */
7714static DEFINE_SPINLOCK(task_group_lock);
7715
bccbe08a
PZ
7716static void free_sched_group(struct task_group *tg)
7717{
7718 free_fair_sched_group(tg);
7719 free_rt_sched_group(tg);
e9aa1dd1 7720 autogroup_free(tg);
bccbe08a
PZ
7721 kfree(tg);
7722}
7723
7724/* allocate runqueue etc for a new task group */
ec7dc8ac 7725struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
7726{
7727 struct task_group *tg;
bccbe08a
PZ
7728
7729 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7730 if (!tg)
7731 return ERR_PTR(-ENOMEM);
7732
ec7dc8ac 7733 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
7734 goto err;
7735
ec7dc8ac 7736 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
7737 goto err;
7738
ace783b9
LZ
7739 return tg;
7740
7741err:
7742 free_sched_group(tg);
7743 return ERR_PTR(-ENOMEM);
7744}
7745
7746void sched_online_group(struct task_group *tg, struct task_group *parent)
7747{
7748 unsigned long flags;
7749
8ed36996 7750 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 7751 list_add_rcu(&tg->list, &task_groups);
f473aa5e
PZ
7752
7753 WARN_ON(!parent); /* root should already exist */
7754
7755 tg->parent = parent;
f473aa5e 7756 INIT_LIST_HEAD(&tg->children);
09f2724a 7757 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 7758 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
7759}
7760
9b5b7751 7761/* rcu callback to free various structures associated with a task group */
6f505b16 7762static void free_sched_group_rcu(struct rcu_head *rhp)
29f59db3 7763{
29f59db3 7764 /* now it should be safe to free those cfs_rqs */
6f505b16 7765 free_sched_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
7766}
7767
9b5b7751 7768/* Destroy runqueue etc associated with a task group */
4cf86d77 7769void sched_destroy_group(struct task_group *tg)
ace783b9
LZ
7770{
7771 /* wait for possible concurrent references to cfs_rqs complete */
7772 call_rcu(&tg->rcu, free_sched_group_rcu);
7773}
7774
7775void sched_offline_group(struct task_group *tg)
29f59db3 7776{
8ed36996 7777 unsigned long flags;
9b5b7751 7778 int i;
29f59db3 7779
3d4b47b4
PZ
7780 /* end participation in shares distribution */
7781 for_each_possible_cpu(i)
bccbe08a 7782 unregister_fair_sched_group(tg, i);
3d4b47b4
PZ
7783
7784 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 7785 list_del_rcu(&tg->list);
f473aa5e 7786 list_del_rcu(&tg->siblings);
8ed36996 7787 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
7788}
7789
9b5b7751 7790/* change task's runqueue when it moves between groups.
3a252015
IM
7791 * The caller of this function should have put the task in its new group
7792 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7793 * reflect its new group.
9b5b7751
SV
7794 */
7795void sched_move_task(struct task_struct *tsk)
29f59db3 7796{
8323f26c 7797 struct task_group *tg;
29f59db3
SV
7798 int on_rq, running;
7799 unsigned long flags;
7800 struct rq *rq;
7801
7802 rq = task_rq_lock(tsk, &flags);
7803
051a1d1a 7804 running = task_current(rq, tsk);
fd2f4419 7805 on_rq = tsk->on_rq;
29f59db3 7806
0e1f3483 7807 if (on_rq)
29f59db3 7808 dequeue_task(rq, tsk, 0);
0e1f3483
HS
7809 if (unlikely(running))
7810 tsk->sched_class->put_prev_task(rq, tsk);
29f59db3 7811
8323f26c
PZ
7812 tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id,
7813 lockdep_is_held(&tsk->sighand->siglock)),
7814 struct task_group, css);
7815 tg = autogroup_task_group(tsk, tg);
7816 tsk->sched_task_group = tg;
7817
810b3817 7818#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02
PZ
7819 if (tsk->sched_class->task_move_group)
7820 tsk->sched_class->task_move_group(tsk, on_rq);
7821 else
810b3817 7822#endif
b2b5ce02 7823 set_task_rq(tsk, task_cpu(tsk));
810b3817 7824
0e1f3483
HS
7825 if (unlikely(running))
7826 tsk->sched_class->set_curr_task(rq);
7827 if (on_rq)
371fd7e7 7828 enqueue_task(rq, tsk, 0);
29f59db3 7829
0122ec5b 7830 task_rq_unlock(rq, tsk, &flags);
29f59db3 7831}
7c941438 7832#endif /* CONFIG_CGROUP_SCHED */
29f59db3 7833
a790de99 7834#if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH)
9f0c1e56
PZ
7835static unsigned long to_ratio(u64 period, u64 runtime)
7836{
7837 if (runtime == RUNTIME_INF)
9a7e0b18 7838 return 1ULL << 20;
9f0c1e56 7839
9a7e0b18 7840 return div64_u64(runtime << 20, period);
9f0c1e56 7841}
a790de99
PT
7842#endif
7843
7844#ifdef CONFIG_RT_GROUP_SCHED
7845/*
7846 * Ensure that the real time constraints are schedulable.
7847 */
7848static DEFINE_MUTEX(rt_constraints_mutex);
9f0c1e56 7849
9a7e0b18
PZ
7850/* Must be called with tasklist_lock held */
7851static inline int tg_has_rt_tasks(struct task_group *tg)
b40b2e8e 7852{
9a7e0b18 7853 struct task_struct *g, *p;
b40b2e8e 7854
9a7e0b18 7855 do_each_thread(g, p) {
029632fb 7856 if (rt_task(p) && task_rq(p)->rt.tg == tg)
9a7e0b18
PZ
7857 return 1;
7858 } while_each_thread(g, p);
b40b2e8e 7859
9a7e0b18
PZ
7860 return 0;
7861}
b40b2e8e 7862
9a7e0b18
PZ
7863struct rt_schedulable_data {
7864 struct task_group *tg;
7865 u64 rt_period;
7866 u64 rt_runtime;
7867};
b40b2e8e 7868
a790de99 7869static int tg_rt_schedulable(struct task_group *tg, void *data)
9a7e0b18
PZ
7870{
7871 struct rt_schedulable_data *d = data;
7872 struct task_group *child;
7873 unsigned long total, sum = 0;
7874 u64 period, runtime;
b40b2e8e 7875
9a7e0b18
PZ
7876 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7877 runtime = tg->rt_bandwidth.rt_runtime;
b40b2e8e 7878
9a7e0b18
PZ
7879 if (tg == d->tg) {
7880 period = d->rt_period;
7881 runtime = d->rt_runtime;
b40b2e8e 7882 }
b40b2e8e 7883
4653f803
PZ
7884 /*
7885 * Cannot have more runtime than the period.
7886 */
7887 if (runtime > period && runtime != RUNTIME_INF)
7888 return -EINVAL;
6f505b16 7889
4653f803
PZ
7890 /*
7891 * Ensure we don't starve existing RT tasks.
7892 */
9a7e0b18
PZ
7893 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7894 return -EBUSY;
6f505b16 7895
9a7e0b18 7896 total = to_ratio(period, runtime);
6f505b16 7897
4653f803
PZ
7898 /*
7899 * Nobody can have more than the global setting allows.
7900 */
7901 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7902 return -EINVAL;
6f505b16 7903
4653f803
PZ
7904 /*
7905 * The sum of our children's runtime should not exceed our own.
7906 */
9a7e0b18
PZ
7907 list_for_each_entry_rcu(child, &tg->children, siblings) {
7908 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7909 runtime = child->rt_bandwidth.rt_runtime;
6f505b16 7910
9a7e0b18
PZ
7911 if (child == d->tg) {
7912 period = d->rt_period;
7913 runtime = d->rt_runtime;
7914 }
6f505b16 7915
9a7e0b18 7916 sum += to_ratio(period, runtime);
9f0c1e56 7917 }
6f505b16 7918
9a7e0b18
PZ
7919 if (sum > total)
7920 return -EINVAL;
7921
7922 return 0;
6f505b16
PZ
7923}
7924
9a7e0b18 7925static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
521f1a24 7926{
8277434e
PT
7927 int ret;
7928
9a7e0b18
PZ
7929 struct rt_schedulable_data data = {
7930 .tg = tg,
7931 .rt_period = period,
7932 .rt_runtime = runtime,
7933 };
7934
8277434e
PT
7935 rcu_read_lock();
7936 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7937 rcu_read_unlock();
7938
7939 return ret;
521f1a24
DG
7940}
7941
ab84d31e 7942static int tg_set_rt_bandwidth(struct task_group *tg,
d0b27fa7 7943 u64 rt_period, u64 rt_runtime)
6f505b16 7944{
ac086bc2 7945 int i, err = 0;
9f0c1e56 7946
9f0c1e56 7947 mutex_lock(&rt_constraints_mutex);
521f1a24 7948 read_lock(&tasklist_lock);
9a7e0b18
PZ
7949 err = __rt_schedulable(tg, rt_period, rt_runtime);
7950 if (err)
9f0c1e56 7951 goto unlock;
ac086bc2 7952
0986b11b 7953 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
d0b27fa7
PZ
7954 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7955 tg->rt_bandwidth.rt_runtime = rt_runtime;
ac086bc2
PZ
7956
7957 for_each_possible_cpu(i) {
7958 struct rt_rq *rt_rq = tg->rt_rq[i];
7959
0986b11b 7960 raw_spin_lock(&rt_rq->rt_runtime_lock);
ac086bc2 7961 rt_rq->rt_runtime = rt_runtime;
0986b11b 7962 raw_spin_unlock(&rt_rq->rt_runtime_lock);
ac086bc2 7963 }
0986b11b 7964 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
49246274 7965unlock:
521f1a24 7966 read_unlock(&tasklist_lock);
9f0c1e56
PZ
7967 mutex_unlock(&rt_constraints_mutex);
7968
7969 return err;
6f505b16
PZ
7970}
7971
25cc7da7 7972static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
d0b27fa7
PZ
7973{
7974 u64 rt_runtime, rt_period;
7975
7976 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7977 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7978 if (rt_runtime_us < 0)
7979 rt_runtime = RUNTIME_INF;
7980
ab84d31e 7981 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
d0b27fa7
PZ
7982}
7983
25cc7da7 7984static long sched_group_rt_runtime(struct task_group *tg)
9f0c1e56
PZ
7985{
7986 u64 rt_runtime_us;
7987
d0b27fa7 7988 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
9f0c1e56
PZ
7989 return -1;
7990
d0b27fa7 7991 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9f0c1e56
PZ
7992 do_div(rt_runtime_us, NSEC_PER_USEC);
7993 return rt_runtime_us;
7994}
d0b27fa7 7995
25cc7da7 7996static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
d0b27fa7
PZ
7997{
7998 u64 rt_runtime, rt_period;
7999
8000 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8001 rt_runtime = tg->rt_bandwidth.rt_runtime;
8002
619b0488
R
8003 if (rt_period == 0)
8004 return -EINVAL;
8005
ab84d31e 8006 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
d0b27fa7
PZ
8007}
8008
25cc7da7 8009static long sched_group_rt_period(struct task_group *tg)
d0b27fa7
PZ
8010{
8011 u64 rt_period_us;
8012
8013 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8014 do_div(rt_period_us, NSEC_PER_USEC);
8015 return rt_period_us;
8016}
8017
8018static int sched_rt_global_constraints(void)
8019{
4653f803 8020 u64 runtime, period;
d0b27fa7
PZ
8021 int ret = 0;
8022
ec5d4989
HS
8023 if (sysctl_sched_rt_period <= 0)
8024 return -EINVAL;
8025
4653f803
PZ
8026 runtime = global_rt_runtime();
8027 period = global_rt_period();
8028
8029 /*
8030 * Sanity check on the sysctl variables.
8031 */
8032 if (runtime > period && runtime != RUNTIME_INF)
8033 return -EINVAL;
10b612f4 8034
d0b27fa7 8035 mutex_lock(&rt_constraints_mutex);
9a7e0b18 8036 read_lock(&tasklist_lock);
4653f803 8037 ret = __rt_schedulable(NULL, 0, 0);
9a7e0b18 8038 read_unlock(&tasklist_lock);
d0b27fa7
PZ
8039 mutex_unlock(&rt_constraints_mutex);
8040
8041 return ret;
8042}
54e99124 8043
25cc7da7 8044static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
54e99124
DG
8045{
8046 /* Don't accept realtime tasks when there is no way for them to run */
8047 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8048 return 0;
8049
8050 return 1;
8051}
8052
6d6bc0ad 8053#else /* !CONFIG_RT_GROUP_SCHED */
d0b27fa7
PZ
8054static int sched_rt_global_constraints(void)
8055{
ac086bc2
PZ
8056 unsigned long flags;
8057 int i;
8058
ec5d4989
HS
8059 if (sysctl_sched_rt_period <= 0)
8060 return -EINVAL;
8061
60aa605d
PZ
8062 /*
8063 * There's always some RT tasks in the root group
8064 * -- migration, kstopmachine etc..
8065 */
8066 if (sysctl_sched_rt_runtime == 0)
8067 return -EBUSY;
8068
0986b11b 8069 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
ac086bc2
PZ
8070 for_each_possible_cpu(i) {
8071 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8072
0986b11b 8073 raw_spin_lock(&rt_rq->rt_runtime_lock);
ac086bc2 8074 rt_rq->rt_runtime = global_rt_runtime();
0986b11b 8075 raw_spin_unlock(&rt_rq->rt_runtime_lock);
ac086bc2 8076 }
0986b11b 8077 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
ac086bc2 8078
d0b27fa7
PZ
8079 return 0;
8080}
6d6bc0ad 8081#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 8082
ce0dbbbb
CW
8083int sched_rr_handler(struct ctl_table *table, int write,
8084 void __user *buffer, size_t *lenp,
8085 loff_t *ppos)
8086{
8087 int ret;
8088 static DEFINE_MUTEX(mutex);
8089
8090 mutex_lock(&mutex);
8091 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8092 /* make sure that internally we keep jiffies */
8093 /* also, writing zero resets timeslice to default */
8094 if (!ret && write) {
8095 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8096 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8097 }
8098 mutex_unlock(&mutex);
8099 return ret;
8100}
8101
d0b27fa7 8102int sched_rt_handler(struct ctl_table *table, int write,
8d65af78 8103 void __user *buffer, size_t *lenp,
d0b27fa7
PZ
8104 loff_t *ppos)
8105{
8106 int ret;
8107 int old_period, old_runtime;
8108 static DEFINE_MUTEX(mutex);
8109
8110 mutex_lock(&mutex);
8111 old_period = sysctl_sched_rt_period;
8112 old_runtime = sysctl_sched_rt_runtime;
8113
8d65af78 8114 ret = proc_dointvec(table, write, buffer, lenp, ppos);
d0b27fa7
PZ
8115
8116 if (!ret && write) {
8117 ret = sched_rt_global_constraints();
8118 if (ret) {
8119 sysctl_sched_rt_period = old_period;
8120 sysctl_sched_rt_runtime = old_runtime;
8121 } else {
8122 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8123 def_rt_bandwidth.rt_period =
8124 ns_to_ktime(global_rt_period());
8125 }
8126 }
8127 mutex_unlock(&mutex);
8128
8129 return ret;
8130}
68318b8e 8131
052f1dc7 8132#ifdef CONFIG_CGROUP_SCHED
68318b8e
SV
8133
8134/* return corresponding task_group object of a cgroup */
2b01dfe3 8135static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
68318b8e 8136{
2b01dfe3
PM
8137 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8138 struct task_group, css);
68318b8e
SV
8139}
8140
92fb9748 8141static struct cgroup_subsys_state *cpu_cgroup_css_alloc(struct cgroup *cgrp)
68318b8e 8142{
ec7dc8ac 8143 struct task_group *tg, *parent;
68318b8e 8144
2b01dfe3 8145 if (!cgrp->parent) {
68318b8e 8146 /* This is early initialization for the top cgroup */
07e06b01 8147 return &root_task_group.css;
68318b8e
SV
8148 }
8149
ec7dc8ac
DG
8150 parent = cgroup_tg(cgrp->parent);
8151 tg = sched_create_group(parent);
68318b8e
SV
8152 if (IS_ERR(tg))
8153 return ERR_PTR(-ENOMEM);
8154
68318b8e
SV
8155 return &tg->css;
8156}
8157
ace783b9
LZ
8158static int cpu_cgroup_css_online(struct cgroup *cgrp)
8159{
8160 struct task_group *tg = cgroup_tg(cgrp);
8161 struct task_group *parent;
8162
8163 if (!cgrp->parent)
8164 return 0;
8165
8166 parent = cgroup_tg(cgrp->parent);
8167 sched_online_group(tg, parent);
8168 return 0;
8169}
8170
92fb9748 8171static void cpu_cgroup_css_free(struct cgroup *cgrp)
68318b8e 8172{
2b01dfe3 8173 struct task_group *tg = cgroup_tg(cgrp);
68318b8e
SV
8174
8175 sched_destroy_group(tg);
8176}
8177
ace783b9
LZ
8178static void cpu_cgroup_css_offline(struct cgroup *cgrp)
8179{
8180 struct task_group *tg = cgroup_tg(cgrp);
8181
8182 sched_offline_group(tg);
8183}
8184
6fa3eb70
S
8185static int
8186cpu_cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
8187{
8188 const struct cred *cred = current_cred(), *tcred;
8189 struct task_struct *task;
8190
8191 cgroup_taskset_for_each(task, cgrp, tset) {
8192 tcred = __task_cred(task);
8193
8194 if ((current != task) && !capable(CAP_SYS_NICE) &&
8195 cred->euid != tcred->uid && cred->euid != tcred->suid)
8196 return -EACCES;
8197 }
8198
8199 return 0;
8200}
8201
761b3ef5 8202static int cpu_cgroup_can_attach(struct cgroup *cgrp,
bb9d97b6 8203 struct cgroup_taskset *tset)
68318b8e 8204{
bb9d97b6
TH
8205 struct task_struct *task;
8206
8207 cgroup_taskset_for_each(task, cgrp, tset) {
b68aa230 8208#ifdef CONFIG_RT_GROUP_SCHED
bb9d97b6 8209 if (!sched_rt_can_attach(cgroup_tg(cgrp), task))
6fa3eb70 8210 return -ERTGROUP;
b68aa230 8211#else
bb9d97b6
TH
8212 /* We don't support RT-tasks being in separate groups */
8213 if (task->sched_class != &fair_sched_class)
8214 return -EINVAL;
b68aa230 8215#endif
bb9d97b6 8216 }
be367d09
BB
8217 return 0;
8218}
68318b8e 8219
761b3ef5 8220static void cpu_cgroup_attach(struct cgroup *cgrp,
bb9d97b6 8221 struct cgroup_taskset *tset)
68318b8e 8222{
bb9d97b6
TH
8223 struct task_struct *task;
8224
8225 cgroup_taskset_for_each(task, cgrp, tset)
8226 sched_move_task(task);
68318b8e
SV
8227}
8228
068c5cc5 8229static void
761b3ef5
LZ
8230cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
8231 struct task_struct *task)
068c5cc5
PZ
8232{
8233 /*
8234 * cgroup_exit() is called in the copy_process() failure path.
8235 * Ignore this case since the task hasn't ran yet, this avoids
8236 * trying to poke a half freed task state from generic code.
8237 */
8238 if (!(task->flags & PF_EXITING))
8239 return;
8240
8241 sched_move_task(task);
8242}
8243
052f1dc7 8244#ifdef CONFIG_FAIR_GROUP_SCHED
f4c753b7 8245static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
2b01dfe3 8246 u64 shareval)
68318b8e 8247{
c8b28116 8248 return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
68318b8e
SV
8249}
8250
f4c753b7 8251static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
68318b8e 8252{
2b01dfe3 8253 struct task_group *tg = cgroup_tg(cgrp);
68318b8e 8254
c8b28116 8255 return (u64) scale_load_down(tg->shares);
68318b8e 8256}
ab84d31e
PT
8257
8258#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
8259static DEFINE_MUTEX(cfs_constraints_mutex);
8260
ab84d31e
PT
8261const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8262const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8263
a790de99
PT
8264static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8265
ab84d31e
PT
8266static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8267{
56f570e5 8268 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 8269 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
8270
8271 if (tg == &root_task_group)
8272 return -EINVAL;
8273
8274 /*
8275 * Ensure we have at some amount of bandwidth every period. This is
8276 * to prevent reaching a state of large arrears when throttled via
8277 * entity_tick() resulting in prolonged exit starvation.
8278 */
8279 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8280 return -EINVAL;
8281
8282 /*
8283 * Likewise, bound things on the otherside by preventing insane quota
8284 * periods. This also allows us to normalize in computing quota
8285 * feasibility.
8286 */
8287 if (period > max_cfs_quota_period)
8288 return -EINVAL;
8289
a790de99
PT
8290 mutex_lock(&cfs_constraints_mutex);
8291 ret = __cfs_schedulable(tg, period, quota);
8292 if (ret)
8293 goto out_unlock;
8294
58088ad0 8295 runtime_enabled = quota != RUNTIME_INF;
56f570e5 8296 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
9d80092f
BS
8297 /*
8298 * If we need to toggle cfs_bandwidth_used, off->on must occur
8299 * before making related changes, and on->off must occur afterwards
8300 */
8301 if (runtime_enabled && !runtime_was_enabled)
8302 cfs_bandwidth_usage_inc();
ab84d31e
PT
8303 raw_spin_lock_irq(&cfs_b->lock);
8304 cfs_b->period = ns_to_ktime(period);
8305 cfs_b->quota = quota;
58088ad0 8306
a9cf55b2 8307 __refill_cfs_bandwidth_runtime(cfs_b);
58088ad0
PT
8308 /* restart the period timer (if active) to handle new period expiry */
8309 if (runtime_enabled && cfs_b->timer_active) {
8310 /* force a reprogram */
8311 cfs_b->timer_active = 0;
8312 __start_cfs_bandwidth(cfs_b);
8313 }
ab84d31e
PT
8314 raw_spin_unlock_irq(&cfs_b->lock);
8315
8316 for_each_possible_cpu(i) {
8317 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 8318 struct rq *rq = cfs_rq->rq;
ab84d31e
PT
8319
8320 raw_spin_lock_irq(&rq->lock);
58088ad0 8321 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 8322 cfs_rq->runtime_remaining = 0;
671fd9da 8323
029632fb 8324 if (cfs_rq->throttled)
671fd9da 8325 unthrottle_cfs_rq(cfs_rq);
ab84d31e
PT
8326 raw_spin_unlock_irq(&rq->lock);
8327 }
9d80092f
BS
8328 if (runtime_was_enabled && !runtime_enabled)
8329 cfs_bandwidth_usage_dec();
a790de99
PT
8330out_unlock:
8331 mutex_unlock(&cfs_constraints_mutex);
ab84d31e 8332
a790de99 8333 return ret;
ab84d31e
PT
8334}
8335
8336int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8337{
8338 u64 quota, period;
8339
029632fb 8340 period = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
8341 if (cfs_quota_us < 0)
8342 quota = RUNTIME_INF;
8343 else
8344 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8345
8346 return tg_set_cfs_bandwidth(tg, period, quota);
8347}
8348
8349long tg_get_cfs_quota(struct task_group *tg)
8350{
8351 u64 quota_us;
8352
029632fb 8353 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
8354 return -1;
8355
029632fb 8356 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
8357 do_div(quota_us, NSEC_PER_USEC);
8358
8359 return quota_us;
8360}
8361
8362int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8363{
8364 u64 quota, period;
8365
8366 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 8367 quota = tg->cfs_bandwidth.quota;
ab84d31e 8368
ab84d31e
PT
8369 return tg_set_cfs_bandwidth(tg, period, quota);
8370}
8371
8372long tg_get_cfs_period(struct task_group *tg)
8373{
8374 u64 cfs_period_us;
8375
029632fb 8376 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
8377 do_div(cfs_period_us, NSEC_PER_USEC);
8378
8379 return cfs_period_us;
8380}
8381
8382static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft)
8383{
8384 return tg_get_cfs_quota(cgroup_tg(cgrp));
8385}
8386
8387static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype,
8388 s64 cfs_quota_us)
8389{
8390 return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us);
8391}
8392
8393static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft)
8394{
8395 return tg_get_cfs_period(cgroup_tg(cgrp));
8396}
8397
8398static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8399 u64 cfs_period_us)
8400{
8401 return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us);
8402}
8403
a790de99
PT
8404struct cfs_schedulable_data {
8405 struct task_group *tg;
8406 u64 period, quota;
8407};
8408
8409/*
8410 * normalize group quota/period to be quota/max_period
8411 * note: units are usecs
8412 */
8413static u64 normalize_cfs_quota(struct task_group *tg,
8414 struct cfs_schedulable_data *d)
8415{
8416 u64 quota, period;
8417
8418 if (tg == d->tg) {
8419 period = d->period;
8420 quota = d->quota;
8421 } else {
8422 period = tg_get_cfs_period(tg);
8423 quota = tg_get_cfs_quota(tg);
8424 }
8425
8426 /* note: these should typically be equivalent */
8427 if (quota == RUNTIME_INF || quota == -1)
8428 return RUNTIME_INF;
8429
8430 return to_ratio(period, quota);
8431}
8432
8433static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8434{
8435 struct cfs_schedulable_data *d = data;
029632fb 8436 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
8437 s64 quota = 0, parent_quota = -1;
8438
8439 if (!tg->parent) {
8440 quota = RUNTIME_INF;
8441 } else {
029632fb 8442 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
8443
8444 quota = normalize_cfs_quota(tg, d);
8445 parent_quota = parent_b->hierarchal_quota;
8446
8447 /*
8448 * ensure max(child_quota) <= parent_quota, inherit when no
8449 * limit is set
8450 */
8451 if (quota == RUNTIME_INF)
8452 quota = parent_quota;
8453 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8454 return -EINVAL;
8455 }
8456 cfs_b->hierarchal_quota = quota;
8457
8458 return 0;
8459}
8460
8461static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8462{
8277434e 8463 int ret;
a790de99
PT
8464 struct cfs_schedulable_data data = {
8465 .tg = tg,
8466 .period = period,
8467 .quota = quota,
8468 };
8469
8470 if (quota != RUNTIME_INF) {
8471 do_div(data.period, NSEC_PER_USEC);
8472 do_div(data.quota, NSEC_PER_USEC);
8473 }
8474
8277434e
PT
8475 rcu_read_lock();
8476 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8477 rcu_read_unlock();
8478
8479 return ret;
a790de99 8480}
e8da1b18
NR
8481
8482static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft,
8483 struct cgroup_map_cb *cb)
8484{
8485 struct task_group *tg = cgroup_tg(cgrp);
029632fb 8486 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18
NR
8487
8488 cb->fill(cb, "nr_periods", cfs_b->nr_periods);
8489 cb->fill(cb, "nr_throttled", cfs_b->nr_throttled);
8490 cb->fill(cb, "throttled_time", cfs_b->throttled_time);
8491
8492 return 0;
8493}
ab84d31e 8494#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 8495#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 8496
052f1dc7 8497#ifdef CONFIG_RT_GROUP_SCHED
0c70814c 8498static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
06ecb27c 8499 s64 val)
6f505b16 8500{
06ecb27c 8501 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
6f505b16
PZ
8502}
8503
06ecb27c 8504static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
6f505b16 8505{
06ecb27c 8506 return sched_group_rt_runtime(cgroup_tg(cgrp));
6f505b16 8507}
d0b27fa7
PZ
8508
8509static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8510 u64 rt_period_us)
8511{
8512 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8513}
8514
8515static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8516{
8517 return sched_group_rt_period(cgroup_tg(cgrp));
8518}
6d6bc0ad 8519#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 8520
fe5c7cc2 8521static struct cftype cpu_files[] = {
052f1dc7 8522#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
8523 {
8524 .name = "shares",
f4c753b7
PM
8525 .read_u64 = cpu_shares_read_u64,
8526 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 8527 },
052f1dc7 8528#endif
ab84d31e
PT
8529#ifdef CONFIG_CFS_BANDWIDTH
8530 {
8531 .name = "cfs_quota_us",
8532 .read_s64 = cpu_cfs_quota_read_s64,
8533 .write_s64 = cpu_cfs_quota_write_s64,
8534 },
8535 {
8536 .name = "cfs_period_us",
8537 .read_u64 = cpu_cfs_period_read_u64,
8538 .write_u64 = cpu_cfs_period_write_u64,
8539 },
e8da1b18
NR
8540 {
8541 .name = "stat",
8542 .read_map = cpu_stats_show,
8543 },
ab84d31e 8544#endif
052f1dc7 8545#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 8546 {
9f0c1e56 8547 .name = "rt_runtime_us",
06ecb27c
PM
8548 .read_s64 = cpu_rt_runtime_read,
8549 .write_s64 = cpu_rt_runtime_write,
6f505b16 8550 },
d0b27fa7
PZ
8551 {
8552 .name = "rt_period_us",
f4c753b7
PM
8553 .read_u64 = cpu_rt_period_read_uint,
8554 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 8555 },
052f1dc7 8556#endif
4baf6e33 8557 { } /* terminate */
68318b8e
SV
8558};
8559
68318b8e 8560struct cgroup_subsys cpu_cgroup_subsys = {
38605cae 8561 .name = "cpu",
92fb9748
TH
8562 .css_alloc = cpu_cgroup_css_alloc,
8563 .css_free = cpu_cgroup_css_free,
ace783b9
LZ
8564 .css_online = cpu_cgroup_css_online,
8565 .css_offline = cpu_cgroup_css_offline,
bb9d97b6
TH
8566 .can_attach = cpu_cgroup_can_attach,
8567 .attach = cpu_cgroup_attach,
6fa3eb70 8568 .allow_attach = cpu_cgroup_allow_attach,
068c5cc5 8569 .exit = cpu_cgroup_exit,
38605cae 8570 .subsys_id = cpu_cgroup_subsys_id,
4baf6e33 8571 .base_cftypes = cpu_files,
68318b8e
SV
8572 .early_init = 1,
8573};
8574
052f1dc7 8575#endif /* CONFIG_CGROUP_SCHED */
d842de87 8576
b637a328
PM
8577void dump_cpu_task(int cpu)
8578{
8579 pr_info("Task dump for CPU %d:\n", cpu);
8580 sched_show_task(cpu_curr(cpu));
8581}
6fa3eb70
S
8582
8583unsigned long long mt_get_thread_cputime(pid_t pid)
8584{
8585 struct task_struct *p;
8586 p = pid ? find_task_by_vpid(pid) : current;
8587 return task_sched_runtime(p);
8588}
8589unsigned long long mt_get_cpu_idle(int cpu)
8590{
8591 unsigned long long *unused = 0;
8592 return get_cpu_idle_time_us(cpu, unused);
8593}
8594unsigned long long mt_sched_clock(void)
8595{
8596 return sched_clock();
8597}
8598EXPORT_SYMBOL(mt_get_thread_cputime);
8599EXPORT_SYMBOL(mt_get_cpu_idle);
8600EXPORT_SYMBOL(mt_sched_clock);