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