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