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