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