]> git.proxmox.com Git - mirror_ubuntu-eoan-kernel.git/blame - kernel/sched/core.c
Merge tag 'iommu-v4.15-rc1' of git://github.com/awilliam/linux-vfio
[mirror_ubuntu-eoan-kernel.git] / kernel / sched / core.c
CommitLineData
1da177e4 1/*
391e43da 2 * kernel/sched/core.c
1da177e4 3 *
d1ccc66d 4 * Core kernel scheduler code and related syscalls
1da177e4
LT
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
1da177e4 7 */
004172bd 8#include <linux/sched.h>
e6017571 9#include <linux/sched/clock.h>
ae7e81c0 10#include <uapi/linux/sched/types.h>
4f17722c 11#include <linux/sched/loadavg.h>
ef8bd77f 12#include <linux/sched/hotplug.h>
5822a454 13#include <linux/wait_bit.h>
1da177e4 14#include <linux/cpuset.h>
0ff92245 15#include <linux/delayacct.h>
f1c6f1a7 16#include <linux/init_task.h>
91d1aa43 17#include <linux/context_tracking.h>
f9411ebe 18#include <linux/rcupdate_wait.h>
004172bd
IM
19
20#include <linux/blkdev.h>
21#include <linux/kprobes.h>
22#include <linux/mmu_context.h>
23#include <linux/module.h>
24#include <linux/nmi.h>
6075620b 25#include <linux/prefetch.h>
004172bd
IM
26#include <linux/profile.h>
27#include <linux/security.h>
28#include <linux/syscalls.h>
78634061 29#include <linux/sched/isolation.h>
1da177e4 30
96f951ed 31#include <asm/switch_to.h>
5517d86b 32#include <asm/tlb.h>
fd4a61e0
MB
33#ifdef CONFIG_PARAVIRT
34#include <asm/paravirt.h>
35#endif
1da177e4 36
029632fb 37#include "sched.h"
ea138446 38#include "../workqueue_internal.h"
29d5e047 39#include "../smpboot.h"
6e0534f2 40
a8d154b0 41#define CREATE_TRACE_POINTS
ad8d75ff 42#include <trace/events/sched.h>
a8d154b0 43
029632fb 44DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 45
765cc3a4 46#if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
bf5c91ba
IM
47/*
48 * Debugging: various feature bits
765cc3a4
PB
49 *
50 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
51 * sysctl_sched_features, defined in sched.h, to allow constants propagation
52 * at compile time and compiler optimization based on features default.
bf5c91ba 53 */
f00b45c1
PZ
54#define SCHED_FEAT(name, enabled) \
55 (1UL << __SCHED_FEAT_##name) * enabled |
bf5c91ba 56const_debug unsigned int sysctl_sched_features =
391e43da 57#include "features.h"
f00b45c1 58 0;
f00b45c1 59#undef SCHED_FEAT
765cc3a4 60#endif
f00b45c1 61
b82d9fdd
PZ
62/*
63 * Number of tasks to iterate in a single balance run.
64 * Limited because this is done with IRQs disabled.
65 */
66const_debug unsigned int sysctl_sched_nr_migrate = 32;
67
e9e9250b
PZ
68/*
69 * period over which we average the RT time consumption, measured
70 * in ms.
71 *
72 * default: 1s
73 */
74const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
75
fa85ae24 76/*
d1ccc66d 77 * period over which we measure -rt task CPU usage in us.
fa85ae24
PZ
78 * default: 1s
79 */
9f0c1e56 80unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 81
029632fb 82__read_mostly int scheduler_running;
6892b75e 83
9f0c1e56
PZ
84/*
85 * part of the period that we allow rt tasks to run in us.
86 * default: 0.95s
87 */
88int sysctl_sched_rt_runtime = 950000;
fa85ae24 89
3e71a462
PZ
90/*
91 * __task_rq_lock - lock the rq @p resides on.
92 */
eb580751 93struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
94 __acquires(rq->lock)
95{
96 struct rq *rq;
97
98 lockdep_assert_held(&p->pi_lock);
99
100 for (;;) {
101 rq = task_rq(p);
102 raw_spin_lock(&rq->lock);
103 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 104 rq_pin_lock(rq, rf);
3e71a462
PZ
105 return rq;
106 }
107 raw_spin_unlock(&rq->lock);
108
109 while (unlikely(task_on_rq_migrating(p)))
110 cpu_relax();
111 }
112}
113
114/*
115 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
116 */
eb580751 117struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
118 __acquires(p->pi_lock)
119 __acquires(rq->lock)
120{
121 struct rq *rq;
122
123 for (;;) {
eb580751 124 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
3e71a462
PZ
125 rq = task_rq(p);
126 raw_spin_lock(&rq->lock);
127 /*
128 * move_queued_task() task_rq_lock()
129 *
130 * ACQUIRE (rq->lock)
131 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
132 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
133 * [S] ->cpu = new_cpu [L] task_rq()
134 * [L] ->on_rq
135 * RELEASE (rq->lock)
136 *
137 * If we observe the old cpu in task_rq_lock, the acquire of
138 * the old rq->lock will fully serialize against the stores.
139 *
d1ccc66d 140 * If we observe the new CPU in task_rq_lock, the acquire will
3e71a462
PZ
141 * pair with the WMB to ensure we must then also see migrating.
142 */
143 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 144 rq_pin_lock(rq, rf);
3e71a462
PZ
145 return rq;
146 }
147 raw_spin_unlock(&rq->lock);
eb580751 148 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
3e71a462
PZ
149
150 while (unlikely(task_on_rq_migrating(p)))
151 cpu_relax();
152 }
153}
154
535b9552
IM
155/*
156 * RQ-clock updating methods:
157 */
158
159static void update_rq_clock_task(struct rq *rq, s64 delta)
160{
161/*
162 * In theory, the compile should just see 0 here, and optimize out the call
163 * to sched_rt_avg_update. But I don't trust it...
164 */
165#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
166 s64 steal = 0, irq_delta = 0;
167#endif
168#ifdef CONFIG_IRQ_TIME_ACCOUNTING
169 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
170
171 /*
172 * Since irq_time is only updated on {soft,}irq_exit, we might run into
173 * this case when a previous update_rq_clock() happened inside a
174 * {soft,}irq region.
175 *
176 * When this happens, we stop ->clock_task and only update the
177 * prev_irq_time stamp to account for the part that fit, so that a next
178 * update will consume the rest. This ensures ->clock_task is
179 * monotonic.
180 *
181 * It does however cause some slight miss-attribution of {soft,}irq
182 * time, a more accurate solution would be to update the irq_time using
183 * the current rq->clock timestamp, except that would require using
184 * atomic ops.
185 */
186 if (irq_delta > delta)
187 irq_delta = delta;
188
189 rq->prev_irq_time += irq_delta;
190 delta -= irq_delta;
191#endif
192#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
193 if (static_key_false((&paravirt_steal_rq_enabled))) {
194 steal = paravirt_steal_clock(cpu_of(rq));
195 steal -= rq->prev_steal_time_rq;
196
197 if (unlikely(steal > delta))
198 steal = delta;
199
200 rq->prev_steal_time_rq += steal;
201 delta -= steal;
202 }
203#endif
204
205 rq->clock_task += delta;
206
207#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
208 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
209 sched_rt_avg_update(rq, irq_delta + steal);
210#endif
211}
212
213void update_rq_clock(struct rq *rq)
214{
215 s64 delta;
216
217 lockdep_assert_held(&rq->lock);
218
219 if (rq->clock_update_flags & RQCF_ACT_SKIP)
220 return;
221
222#ifdef CONFIG_SCHED_DEBUG
26ae58d2
PZ
223 if (sched_feat(WARN_DOUBLE_CLOCK))
224 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
535b9552
IM
225 rq->clock_update_flags |= RQCF_UPDATED;
226#endif
26ae58d2 227
535b9552
IM
228 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
229 if (delta < 0)
230 return;
231 rq->clock += delta;
232 update_rq_clock_task(rq, delta);
233}
234
235
8f4d37ec
PZ
236#ifdef CONFIG_SCHED_HRTICK
237/*
238 * Use HR-timers to deliver accurate preemption points.
8f4d37ec 239 */
8f4d37ec 240
8f4d37ec
PZ
241static void hrtick_clear(struct rq *rq)
242{
243 if (hrtimer_active(&rq->hrtick_timer))
244 hrtimer_cancel(&rq->hrtick_timer);
245}
246
8f4d37ec
PZ
247/*
248 * High-resolution timer tick.
249 * Runs from hardirq context with interrupts disabled.
250 */
251static enum hrtimer_restart hrtick(struct hrtimer *timer)
252{
253 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
8a8c69c3 254 struct rq_flags rf;
8f4d37ec
PZ
255
256 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
257
8a8c69c3 258 rq_lock(rq, &rf);
3e51f33f 259 update_rq_clock(rq);
8f4d37ec 260 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
8a8c69c3 261 rq_unlock(rq, &rf);
8f4d37ec
PZ
262
263 return HRTIMER_NORESTART;
264}
265
95e904c7 266#ifdef CONFIG_SMP
971ee28c 267
4961b6e1 268static void __hrtick_restart(struct rq *rq)
971ee28c
PZ
269{
270 struct hrtimer *timer = &rq->hrtick_timer;
971ee28c 271
4961b6e1 272 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
971ee28c
PZ
273}
274
31656519
PZ
275/*
276 * called from hardirq (IPI) context
277 */
278static void __hrtick_start(void *arg)
b328ca18 279{
31656519 280 struct rq *rq = arg;
8a8c69c3 281 struct rq_flags rf;
b328ca18 282
8a8c69c3 283 rq_lock(rq, &rf);
971ee28c 284 __hrtick_restart(rq);
31656519 285 rq->hrtick_csd_pending = 0;
8a8c69c3 286 rq_unlock(rq, &rf);
b328ca18
PZ
287}
288
31656519
PZ
289/*
290 * Called to set the hrtick timer state.
291 *
292 * called with rq->lock held and irqs disabled
293 */
029632fb 294void hrtick_start(struct rq *rq, u64 delay)
b328ca18 295{
31656519 296 struct hrtimer *timer = &rq->hrtick_timer;
177ef2a6 297 ktime_t time;
298 s64 delta;
299
300 /*
301 * Don't schedule slices shorter than 10000ns, that just
302 * doesn't make sense and can cause timer DoS.
303 */
304 delta = max_t(s64, delay, 10000LL);
305 time = ktime_add_ns(timer->base->get_time(), delta);
b328ca18 306
cc584b21 307 hrtimer_set_expires(timer, time);
31656519
PZ
308
309 if (rq == this_rq()) {
971ee28c 310 __hrtick_restart(rq);
31656519 311 } else if (!rq->hrtick_csd_pending) {
c46fff2a 312 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
31656519
PZ
313 rq->hrtick_csd_pending = 1;
314 }
b328ca18
PZ
315}
316
31656519
PZ
317#else
318/*
319 * Called to set the hrtick timer state.
320 *
321 * called with rq->lock held and irqs disabled
322 */
029632fb 323void hrtick_start(struct rq *rq, u64 delay)
31656519 324{
86893335
WL
325 /*
326 * Don't schedule slices shorter than 10000ns, that just
327 * doesn't make sense. Rely on vruntime for fairness.
328 */
329 delay = max_t(u64, delay, 10000LL);
4961b6e1
TG
330 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
331 HRTIMER_MODE_REL_PINNED);
31656519 332}
31656519 333#endif /* CONFIG_SMP */
8f4d37ec 334
31656519 335static void init_rq_hrtick(struct rq *rq)
8f4d37ec 336{
31656519
PZ
337#ifdef CONFIG_SMP
338 rq->hrtick_csd_pending = 0;
8f4d37ec 339
31656519
PZ
340 rq->hrtick_csd.flags = 0;
341 rq->hrtick_csd.func = __hrtick_start;
342 rq->hrtick_csd.info = rq;
343#endif
8f4d37ec 344
31656519
PZ
345 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
346 rq->hrtick_timer.function = hrtick;
8f4d37ec 347}
006c75f1 348#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
349static inline void hrtick_clear(struct rq *rq)
350{
351}
352
8f4d37ec
PZ
353static inline void init_rq_hrtick(struct rq *rq)
354{
355}
006c75f1 356#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 357
5529578a
FW
358/*
359 * cmpxchg based fetch_or, macro so it works for different integer types
360 */
361#define fetch_or(ptr, mask) \
362 ({ \
363 typeof(ptr) _ptr = (ptr); \
364 typeof(mask) _mask = (mask); \
365 typeof(*_ptr) _old, _val = *_ptr; \
366 \
367 for (;;) { \
368 _old = cmpxchg(_ptr, _val, _val | _mask); \
369 if (_old == _val) \
370 break; \
371 _val = _old; \
372 } \
373 _old; \
374})
375
e3baac47 376#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
fd99f91a
PZ
377/*
378 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
379 * this avoids any races wrt polling state changes and thereby avoids
380 * spurious IPIs.
381 */
382static bool set_nr_and_not_polling(struct task_struct *p)
383{
384 struct thread_info *ti = task_thread_info(p);
385 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
386}
e3baac47
PZ
387
388/*
389 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
390 *
391 * If this returns true, then the idle task promises to call
392 * sched_ttwu_pending() and reschedule soon.
393 */
394static bool set_nr_if_polling(struct task_struct *p)
395{
396 struct thread_info *ti = task_thread_info(p);
316c1608 397 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
e3baac47
PZ
398
399 for (;;) {
400 if (!(val & _TIF_POLLING_NRFLAG))
401 return false;
402 if (val & _TIF_NEED_RESCHED)
403 return true;
404 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
405 if (old == val)
406 break;
407 val = old;
408 }
409 return true;
410}
411
fd99f91a
PZ
412#else
413static bool set_nr_and_not_polling(struct task_struct *p)
414{
415 set_tsk_need_resched(p);
416 return true;
417}
e3baac47
PZ
418
419#ifdef CONFIG_SMP
420static bool set_nr_if_polling(struct task_struct *p)
421{
422 return false;
423}
424#endif
fd99f91a
PZ
425#endif
426
76751049
PZ
427void wake_q_add(struct wake_q_head *head, struct task_struct *task)
428{
429 struct wake_q_node *node = &task->wake_q;
430
431 /*
432 * Atomically grab the task, if ->wake_q is !nil already it means
433 * its already queued (either by us or someone else) and will get the
434 * wakeup due to that.
435 *
436 * This cmpxchg() implies a full barrier, which pairs with the write
58fe9c46 437 * barrier implied by the wakeup in wake_up_q().
76751049
PZ
438 */
439 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
440 return;
441
442 get_task_struct(task);
443
444 /*
445 * The head is context local, there can be no concurrency.
446 */
447 *head->lastp = node;
448 head->lastp = &node->next;
449}
450
451void wake_up_q(struct wake_q_head *head)
452{
453 struct wake_q_node *node = head->first;
454
455 while (node != WAKE_Q_TAIL) {
456 struct task_struct *task;
457
458 task = container_of(node, struct task_struct, wake_q);
459 BUG_ON(!task);
d1ccc66d 460 /* Task can safely be re-inserted now: */
76751049
PZ
461 node = node->next;
462 task->wake_q.next = NULL;
463
464 /*
465 * wake_up_process() implies a wmb() to pair with the queueing
466 * in wake_q_add() so as not to miss wakeups.
467 */
468 wake_up_process(task);
469 put_task_struct(task);
470 }
471}
472
c24d20db 473/*
8875125e 474 * resched_curr - mark rq's current task 'to be rescheduled now'.
c24d20db
IM
475 *
476 * On UP this means the setting of the need_resched flag, on SMP it
477 * might also involve a cross-CPU call to trigger the scheduler on
478 * the target CPU.
479 */
8875125e 480void resched_curr(struct rq *rq)
c24d20db 481{
8875125e 482 struct task_struct *curr = rq->curr;
c24d20db
IM
483 int cpu;
484
8875125e 485 lockdep_assert_held(&rq->lock);
c24d20db 486
8875125e 487 if (test_tsk_need_resched(curr))
c24d20db
IM
488 return;
489
8875125e 490 cpu = cpu_of(rq);
fd99f91a 491
f27dde8d 492 if (cpu == smp_processor_id()) {
8875125e 493 set_tsk_need_resched(curr);
f27dde8d 494 set_preempt_need_resched();
c24d20db 495 return;
f27dde8d 496 }
c24d20db 497
8875125e 498 if (set_nr_and_not_polling(curr))
c24d20db 499 smp_send_reschedule(cpu);
dfc68f29
AL
500 else
501 trace_sched_wake_idle_without_ipi(cpu);
c24d20db
IM
502}
503
029632fb 504void resched_cpu(int cpu)
c24d20db
IM
505{
506 struct rq *rq = cpu_rq(cpu);
507 unsigned long flags;
508
7c2102e5 509 raw_spin_lock_irqsave(&rq->lock, flags);
8875125e 510 resched_curr(rq);
05fa785c 511 raw_spin_unlock_irqrestore(&rq->lock, flags);
c24d20db 512}
06d8308c 513
b021fe3e 514#ifdef CONFIG_SMP
3451d024 515#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2 516/*
d1ccc66d
IM
517 * In the semi idle case, use the nearest busy CPU for migrating timers
518 * from an idle CPU. This is good for power-savings.
83cd4fe2
VP
519 *
520 * We don't do similar optimization for completely idle system, as
d1ccc66d
IM
521 * selecting an idle CPU will add more delays to the timers than intended
522 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
83cd4fe2 523 */
bc7a34b8 524int get_nohz_timer_target(void)
83cd4fe2 525{
bc7a34b8 526 int i, cpu = smp_processor_id();
83cd4fe2
VP
527 struct sched_domain *sd;
528
de201559 529 if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
6201b4d6
VK
530 return cpu;
531
057f3fad 532 rcu_read_lock();
83cd4fe2 533 for_each_domain(cpu, sd) {
057f3fad 534 for_each_cpu(i, sched_domain_span(sd)) {
44496922
WL
535 if (cpu == i)
536 continue;
537
de201559 538 if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
057f3fad
PZ
539 cpu = i;
540 goto unlock;
541 }
542 }
83cd4fe2 543 }
9642d18e 544
de201559
FW
545 if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
546 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
057f3fad
PZ
547unlock:
548 rcu_read_unlock();
83cd4fe2
VP
549 return cpu;
550}
d1ccc66d 551
06d8308c
TG
552/*
553 * When add_timer_on() enqueues a timer into the timer wheel of an
554 * idle CPU then this timer might expire before the next timer event
555 * which is scheduled to wake up that CPU. In case of a completely
556 * idle system the next event might even be infinite time into the
557 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
558 * leaves the inner idle loop so the newly added timer is taken into
559 * account when the CPU goes back to idle and evaluates the timer
560 * wheel for the next timer event.
561 */
1c20091e 562static void wake_up_idle_cpu(int cpu)
06d8308c
TG
563{
564 struct rq *rq = cpu_rq(cpu);
565
566 if (cpu == smp_processor_id())
567 return;
568
67b9ca70 569 if (set_nr_and_not_polling(rq->idle))
06d8308c 570 smp_send_reschedule(cpu);
dfc68f29
AL
571 else
572 trace_sched_wake_idle_without_ipi(cpu);
45bf76df
IM
573}
574
c5bfece2 575static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 576{
53c5fa16
FW
577 /*
578 * We just need the target to call irq_exit() and re-evaluate
579 * the next tick. The nohz full kick at least implies that.
580 * If needed we can still optimize that later with an
581 * empty IRQ.
582 */
379d9ecb
PM
583 if (cpu_is_offline(cpu))
584 return true; /* Don't try to wake offline CPUs. */
c5bfece2 585 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
586 if (cpu != smp_processor_id() ||
587 tick_nohz_tick_stopped())
53c5fa16 588 tick_nohz_full_kick_cpu(cpu);
1c20091e
FW
589 return true;
590 }
591
592 return false;
593}
594
379d9ecb
PM
595/*
596 * Wake up the specified CPU. If the CPU is going offline, it is the
597 * caller's responsibility to deal with the lost wakeup, for example,
598 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
599 */
1c20091e
FW
600void wake_up_nohz_cpu(int cpu)
601{
c5bfece2 602 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
603 wake_up_idle_cpu(cpu);
604}
605
ca38062e 606static inline bool got_nohz_idle_kick(void)
45bf76df 607{
1c792db7 608 int cpu = smp_processor_id();
873b4c65
VG
609
610 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
611 return false;
612
613 if (idle_cpu(cpu) && !need_resched())
614 return true;
615
616 /*
617 * We can't run Idle Load Balance on this CPU for this time so we
618 * cancel it and clear NOHZ_BALANCE_KICK
619 */
620 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
621 return false;
45bf76df
IM
622}
623
3451d024 624#else /* CONFIG_NO_HZ_COMMON */
45bf76df 625
ca38062e 626static inline bool got_nohz_idle_kick(void)
2069dd75 627{
ca38062e 628 return false;
2069dd75
PZ
629}
630
3451d024 631#endif /* CONFIG_NO_HZ_COMMON */
d842de87 632
ce831b38 633#ifdef CONFIG_NO_HZ_FULL
76d92ac3 634bool sched_can_stop_tick(struct rq *rq)
ce831b38 635{
76d92ac3
FW
636 int fifo_nr_running;
637
638 /* Deadline tasks, even if single, need the tick */
639 if (rq->dl.dl_nr_running)
640 return false;
641
1e78cdbd 642 /*
2548d546
PZ
643 * If there are more than one RR tasks, we need the tick to effect the
644 * actual RR behaviour.
1e78cdbd 645 */
76d92ac3
FW
646 if (rq->rt.rr_nr_running) {
647 if (rq->rt.rr_nr_running == 1)
648 return true;
649 else
650 return false;
1e78cdbd
RR
651 }
652
2548d546
PZ
653 /*
654 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
655 * forced preemption between FIFO tasks.
656 */
657 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
658 if (fifo_nr_running)
659 return true;
660
661 /*
662 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
663 * if there's more than one we need the tick for involuntary
664 * preemption.
665 */
666 if (rq->nr_running > 1)
541b8264 667 return false;
ce831b38 668
541b8264 669 return true;
ce831b38
FW
670}
671#endif /* CONFIG_NO_HZ_FULL */
d842de87 672
029632fb 673void sched_avg_update(struct rq *rq)
18d95a28 674{
e9e9250b
PZ
675 s64 period = sched_avg_period();
676
78becc27 677 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
0d98bb26
WD
678 /*
679 * Inline assembly required to prevent the compiler
680 * optimising this loop into a divmod call.
681 * See __iter_div_u64_rem() for another example of this.
682 */
683 asm("" : "+rm" (rq->age_stamp));
e9e9250b
PZ
684 rq->age_stamp += period;
685 rq->rt_avg /= 2;
686 }
18d95a28
PZ
687}
688
6d6bc0ad 689#endif /* CONFIG_SMP */
18d95a28 690
a790de99
PT
691#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
692 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 693/*
8277434e
PT
694 * Iterate task_group tree rooted at *from, calling @down when first entering a
695 * node and @up when leaving it for the final time.
696 *
697 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 698 */
029632fb 699int walk_tg_tree_from(struct task_group *from,
8277434e 700 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
701{
702 struct task_group *parent, *child;
eb755805 703 int ret;
c09595f6 704
8277434e
PT
705 parent = from;
706
c09595f6 707down:
eb755805
PZ
708 ret = (*down)(parent, data);
709 if (ret)
8277434e 710 goto out;
c09595f6
PZ
711 list_for_each_entry_rcu(child, &parent->children, siblings) {
712 parent = child;
713 goto down;
714
715up:
716 continue;
717 }
eb755805 718 ret = (*up)(parent, data);
8277434e
PT
719 if (ret || parent == from)
720 goto out;
c09595f6
PZ
721
722 child = parent;
723 parent = parent->parent;
724 if (parent)
725 goto up;
8277434e 726out:
eb755805 727 return ret;
c09595f6
PZ
728}
729
029632fb 730int tg_nop(struct task_group *tg, void *data)
eb755805 731{
e2b245f8 732 return 0;
eb755805 733}
18d95a28
PZ
734#endif
735
9059393e 736static void set_load_weight(struct task_struct *p, bool update_load)
45bf76df 737{
f05998d4
NR
738 int prio = p->static_prio - MAX_RT_PRIO;
739 struct load_weight *load = &p->se.load;
740
dd41f596
IM
741 /*
742 * SCHED_IDLE tasks get minimal weight:
743 */
20f9cd2a 744 if (idle_policy(p->policy)) {
c8b28116 745 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 746 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
747 return;
748 }
71f8bd46 749
9059393e
VG
750 /*
751 * SCHED_OTHER tasks have to update their load when changing their
752 * weight
753 */
754 if (update_load && p->sched_class == &fair_sched_class) {
755 reweight_task(p, prio);
756 } else {
757 load->weight = scale_load(sched_prio_to_weight[prio]);
758 load->inv_weight = sched_prio_to_wmult[prio];
759 }
71f8bd46
IM
760}
761
1de64443 762static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 763{
0a67d1ee
PZ
764 if (!(flags & ENQUEUE_NOCLOCK))
765 update_rq_clock(rq);
766
1de64443
PZ
767 if (!(flags & ENQUEUE_RESTORE))
768 sched_info_queued(rq, p);
0a67d1ee 769
371fd7e7 770 p->sched_class->enqueue_task(rq, p, flags);
71f8bd46
IM
771}
772
1de64443 773static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 774{
0a67d1ee
PZ
775 if (!(flags & DEQUEUE_NOCLOCK))
776 update_rq_clock(rq);
777
1de64443
PZ
778 if (!(flags & DEQUEUE_SAVE))
779 sched_info_dequeued(rq, p);
0a67d1ee 780
371fd7e7 781 p->sched_class->dequeue_task(rq, p, flags);
71f8bd46
IM
782}
783
029632fb 784void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
785{
786 if (task_contributes_to_load(p))
787 rq->nr_uninterruptible--;
788
371fd7e7 789 enqueue_task(rq, p, flags);
1e3c88bd
PZ
790}
791
029632fb 792void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
793{
794 if (task_contributes_to_load(p))
795 rq->nr_uninterruptible++;
796
371fd7e7 797 dequeue_task(rq, p, flags);
1e3c88bd
PZ
798}
799
14531189 800/*
dd41f596 801 * __normal_prio - return the priority that is based on the static prio
14531189 802 */
14531189
IM
803static inline int __normal_prio(struct task_struct *p)
804{
dd41f596 805 return p->static_prio;
14531189
IM
806}
807
b29739f9
IM
808/*
809 * Calculate the expected normal priority: i.e. priority
810 * without taking RT-inheritance into account. Might be
811 * boosted by interactivity modifiers. Changes upon fork,
812 * setprio syscalls, and whenever the interactivity
813 * estimator recalculates.
814 */
36c8b586 815static inline int normal_prio(struct task_struct *p)
b29739f9
IM
816{
817 int prio;
818
aab03e05
DF
819 if (task_has_dl_policy(p))
820 prio = MAX_DL_PRIO-1;
821 else if (task_has_rt_policy(p))
b29739f9
IM
822 prio = MAX_RT_PRIO-1 - p->rt_priority;
823 else
824 prio = __normal_prio(p);
825 return prio;
826}
827
828/*
829 * Calculate the current priority, i.e. the priority
830 * taken into account by the scheduler. This value might
831 * be boosted by RT tasks, or might be boosted by
832 * interactivity modifiers. Will be RT if the task got
833 * RT-boosted. If not then it returns p->normal_prio.
834 */
36c8b586 835static int effective_prio(struct task_struct *p)
b29739f9
IM
836{
837 p->normal_prio = normal_prio(p);
838 /*
839 * If we are RT tasks or we were boosted to RT priority,
840 * keep the priority unchanged. Otherwise, update priority
841 * to the normal priority:
842 */
843 if (!rt_prio(p->prio))
844 return p->normal_prio;
845 return p->prio;
846}
847
1da177e4
LT
848/**
849 * task_curr - is this task currently executing on a CPU?
850 * @p: the task in question.
e69f6186
YB
851 *
852 * Return: 1 if the task is currently executing. 0 otherwise.
1da177e4 853 */
36c8b586 854inline int task_curr(const struct task_struct *p)
1da177e4
LT
855{
856 return cpu_curr(task_cpu(p)) == p;
857}
858
67dfa1b7 859/*
4c9a4bc8
PZ
860 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
861 * use the balance_callback list if you want balancing.
862 *
863 * this means any call to check_class_changed() must be followed by a call to
864 * balance_callback().
67dfa1b7 865 */
cb469845
SR
866static inline void check_class_changed(struct rq *rq, struct task_struct *p,
867 const struct sched_class *prev_class,
da7a735e 868 int oldprio)
cb469845
SR
869{
870 if (prev_class != p->sched_class) {
871 if (prev_class->switched_from)
da7a735e 872 prev_class->switched_from(rq, p);
4c9a4bc8 873
da7a735e 874 p->sched_class->switched_to(rq, p);
2d3d891d 875 } else if (oldprio != p->prio || dl_task(p))
da7a735e 876 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
877}
878
029632fb 879void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405
PZ
880{
881 const struct sched_class *class;
882
883 if (p->sched_class == rq->curr->sched_class) {
884 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
885 } else {
886 for_each_class(class) {
887 if (class == rq->curr->sched_class)
888 break;
889 if (class == p->sched_class) {
8875125e 890 resched_curr(rq);
1e5a7405
PZ
891 break;
892 }
893 }
894 }
895
896 /*
897 * A queue event has occurred, and we're going to schedule. In
898 * this case, we can save a useless back to back clock update.
899 */
da0c1e65 900 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
9edfbfed 901 rq_clock_skip_update(rq, true);
1e5a7405
PZ
902}
903
1da177e4 904#ifdef CONFIG_SMP
5cc389bc
PZ
905/*
906 * This is how migration works:
907 *
908 * 1) we invoke migration_cpu_stop() on the target CPU using
909 * stop_one_cpu().
910 * 2) stopper starts to run (implicitly forcing the migrated thread
911 * off the CPU)
912 * 3) it checks whether the migrated task is still in the wrong runqueue.
913 * 4) if it's in the wrong runqueue then the migration thread removes
914 * it and puts it into the right queue.
915 * 5) stopper completes and stop_one_cpu() returns and the migration
916 * is done.
917 */
918
919/*
920 * move_queued_task - move a queued task to new rq.
921 *
922 * Returns (locked) new rq. Old rq's lock is released.
923 */
8a8c69c3
PZ
924static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
925 struct task_struct *p, int new_cpu)
5cc389bc 926{
5cc389bc
PZ
927 lockdep_assert_held(&rq->lock);
928
5cc389bc 929 p->on_rq = TASK_ON_RQ_MIGRATING;
15ff991e 930 dequeue_task(rq, p, DEQUEUE_NOCLOCK);
5cc389bc 931 set_task_cpu(p, new_cpu);
8a8c69c3 932 rq_unlock(rq, rf);
5cc389bc
PZ
933
934 rq = cpu_rq(new_cpu);
935
8a8c69c3 936 rq_lock(rq, rf);
5cc389bc 937 BUG_ON(task_cpu(p) != new_cpu);
5cc389bc 938 enqueue_task(rq, p, 0);
3ea94de1 939 p->on_rq = TASK_ON_RQ_QUEUED;
5cc389bc
PZ
940 check_preempt_curr(rq, p, 0);
941
942 return rq;
943}
944
945struct migration_arg {
946 struct task_struct *task;
947 int dest_cpu;
948};
949
950/*
d1ccc66d 951 * Move (not current) task off this CPU, onto the destination CPU. We're doing
5cc389bc
PZ
952 * this because either it can't run here any more (set_cpus_allowed()
953 * away from this CPU, or CPU going down), or because we're
954 * attempting to rebalance this task on exec (sched_exec).
955 *
956 * So we race with normal scheduler movements, but that's OK, as long
957 * as the task is no longer on this CPU.
5cc389bc 958 */
8a8c69c3
PZ
959static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
960 struct task_struct *p, int dest_cpu)
5cc389bc 961{
955dbdf4
TH
962 if (p->flags & PF_KTHREAD) {
963 if (unlikely(!cpu_online(dest_cpu)))
964 return rq;
965 } else {
966 if (unlikely(!cpu_active(dest_cpu)))
967 return rq;
968 }
5cc389bc
PZ
969
970 /* Affinity changed (again). */
0c98d344 971 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5e16bbc2 972 return rq;
5cc389bc 973
15ff991e 974 update_rq_clock(rq);
8a8c69c3 975 rq = move_queued_task(rq, rf, p, dest_cpu);
5e16bbc2
PZ
976
977 return rq;
5cc389bc
PZ
978}
979
980/*
981 * migration_cpu_stop - this will be executed by a highprio stopper thread
982 * and performs thread migration by bumping thread off CPU then
983 * 'pushing' onto another runqueue.
984 */
985static int migration_cpu_stop(void *data)
986{
987 struct migration_arg *arg = data;
5e16bbc2
PZ
988 struct task_struct *p = arg->task;
989 struct rq *rq = this_rq();
8a8c69c3 990 struct rq_flags rf;
5cc389bc
PZ
991
992 /*
d1ccc66d
IM
993 * The original target CPU might have gone down and we might
994 * be on another CPU but it doesn't matter.
5cc389bc
PZ
995 */
996 local_irq_disable();
997 /*
998 * We need to explicitly wake pending tasks before running
999 * __migrate_task() such that we will not miss enforcing cpus_allowed
1000 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1001 */
1002 sched_ttwu_pending();
5e16bbc2
PZ
1003
1004 raw_spin_lock(&p->pi_lock);
8a8c69c3 1005 rq_lock(rq, &rf);
5e16bbc2
PZ
1006 /*
1007 * If task_rq(p) != rq, it cannot be migrated here, because we're
1008 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1009 * we're holding p->pi_lock.
1010 */
bf89a304
CC
1011 if (task_rq(p) == rq) {
1012 if (task_on_rq_queued(p))
8a8c69c3 1013 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
bf89a304
CC
1014 else
1015 p->wake_cpu = arg->dest_cpu;
1016 }
8a8c69c3 1017 rq_unlock(rq, &rf);
5e16bbc2
PZ
1018 raw_spin_unlock(&p->pi_lock);
1019
5cc389bc
PZ
1020 local_irq_enable();
1021 return 0;
1022}
1023
c5b28038
PZ
1024/*
1025 * sched_class::set_cpus_allowed must do the below, but is not required to
1026 * actually call this function.
1027 */
1028void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
5cc389bc 1029{
5cc389bc
PZ
1030 cpumask_copy(&p->cpus_allowed, new_mask);
1031 p->nr_cpus_allowed = cpumask_weight(new_mask);
1032}
1033
c5b28038
PZ
1034void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1035{
6c37067e
PZ
1036 struct rq *rq = task_rq(p);
1037 bool queued, running;
1038
c5b28038 1039 lockdep_assert_held(&p->pi_lock);
6c37067e
PZ
1040
1041 queued = task_on_rq_queued(p);
1042 running = task_current(rq, p);
1043
1044 if (queued) {
1045 /*
1046 * Because __kthread_bind() calls this on blocked tasks without
1047 * holding rq->lock.
1048 */
1049 lockdep_assert_held(&rq->lock);
7a57f32a 1050 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
6c37067e
PZ
1051 }
1052 if (running)
1053 put_prev_task(rq, p);
1054
c5b28038 1055 p->sched_class->set_cpus_allowed(p, new_mask);
6c37067e 1056
6c37067e 1057 if (queued)
7134b3e9 1058 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 1059 if (running)
b2bf6c31 1060 set_curr_task(rq, p);
c5b28038
PZ
1061}
1062
5cc389bc
PZ
1063/*
1064 * Change a given task's CPU affinity. Migrate the thread to a
1065 * proper CPU and schedule it away if the CPU it's executing on
1066 * is removed from the allowed bitmask.
1067 *
1068 * NOTE: the caller must have a valid reference to the task, the
1069 * task must not exit() & deallocate itself prematurely. The
1070 * call is not atomic; no spinlocks may be held.
1071 */
25834c73
PZ
1072static int __set_cpus_allowed_ptr(struct task_struct *p,
1073 const struct cpumask *new_mask, bool check)
5cc389bc 1074{
e9d867a6 1075 const struct cpumask *cpu_valid_mask = cpu_active_mask;
5cc389bc 1076 unsigned int dest_cpu;
eb580751
PZ
1077 struct rq_flags rf;
1078 struct rq *rq;
5cc389bc
PZ
1079 int ret = 0;
1080
eb580751 1081 rq = task_rq_lock(p, &rf);
a499c3ea 1082 update_rq_clock(rq);
5cc389bc 1083
e9d867a6
PZI
1084 if (p->flags & PF_KTHREAD) {
1085 /*
1086 * Kernel threads are allowed on online && !active CPUs
1087 */
1088 cpu_valid_mask = cpu_online_mask;
1089 }
1090
25834c73
PZ
1091 /*
1092 * Must re-check here, to close a race against __kthread_bind(),
1093 * sched_setaffinity() is not guaranteed to observe the flag.
1094 */
1095 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1096 ret = -EINVAL;
1097 goto out;
1098 }
1099
5cc389bc
PZ
1100 if (cpumask_equal(&p->cpus_allowed, new_mask))
1101 goto out;
1102
e9d867a6 1103 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
5cc389bc
PZ
1104 ret = -EINVAL;
1105 goto out;
1106 }
1107
1108 do_set_cpus_allowed(p, new_mask);
1109
e9d867a6
PZI
1110 if (p->flags & PF_KTHREAD) {
1111 /*
1112 * For kernel threads that do indeed end up on online &&
d1ccc66d 1113 * !active we want to ensure they are strict per-CPU threads.
e9d867a6
PZI
1114 */
1115 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1116 !cpumask_intersects(new_mask, cpu_active_mask) &&
1117 p->nr_cpus_allowed != 1);
1118 }
1119
5cc389bc
PZ
1120 /* Can the task run on the task's current CPU? If so, we're done */
1121 if (cpumask_test_cpu(task_cpu(p), new_mask))
1122 goto out;
1123
e9d867a6 1124 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
5cc389bc
PZ
1125 if (task_running(rq, p) || p->state == TASK_WAKING) {
1126 struct migration_arg arg = { p, dest_cpu };
1127 /* Need help from migration thread: drop lock and wait. */
eb580751 1128 task_rq_unlock(rq, p, &rf);
5cc389bc
PZ
1129 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1130 tlb_migrate_finish(p->mm);
1131 return 0;
cbce1a68
PZ
1132 } else if (task_on_rq_queued(p)) {
1133 /*
1134 * OK, since we're going to drop the lock immediately
1135 * afterwards anyway.
1136 */
8a8c69c3 1137 rq = move_queued_task(rq, &rf, p, dest_cpu);
cbce1a68 1138 }
5cc389bc 1139out:
eb580751 1140 task_rq_unlock(rq, p, &rf);
5cc389bc
PZ
1141
1142 return ret;
1143}
25834c73
PZ
1144
1145int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1146{
1147 return __set_cpus_allowed_ptr(p, new_mask, false);
1148}
5cc389bc
PZ
1149EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1150
dd41f596 1151void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 1152{
e2912009
PZ
1153#ifdef CONFIG_SCHED_DEBUG
1154 /*
1155 * We should never call set_task_cpu() on a blocked task,
1156 * ttwu() will sort out the placement.
1157 */
077614ee 1158 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
e2336f6e 1159 !p->on_rq);
0122ec5b 1160
3ea94de1
JP
1161 /*
1162 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1163 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1164 * time relying on p->on_rq.
1165 */
1166 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1167 p->sched_class == &fair_sched_class &&
1168 (p->on_rq && !task_on_rq_migrating(p)));
1169
0122ec5b 1170#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
1171 /*
1172 * The caller should hold either p->pi_lock or rq->lock, when changing
1173 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1174 *
1175 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 1176 * see task_group().
6c6c54e1
PZ
1177 *
1178 * Furthermore, all task_rq users should acquire both locks, see
1179 * task_rq_lock().
1180 */
0122ec5b
PZ
1181 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1182 lockdep_is_held(&task_rq(p)->lock)));
1183#endif
4ff9083b
PZ
1184 /*
1185 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1186 */
1187 WARN_ON_ONCE(!cpu_online(new_cpu));
e2912009
PZ
1188#endif
1189
de1d7286 1190 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 1191
0c69774e 1192 if (task_cpu(p) != new_cpu) {
0a74bef8 1193 if (p->sched_class->migrate_task_rq)
5a4fd036 1194 p->sched_class->migrate_task_rq(p);
0c69774e 1195 p->se.nr_migrations++;
ff303e66 1196 perf_event_task_migrate(p);
0c69774e 1197 }
dd41f596
IM
1198
1199 __set_task_cpu(p, new_cpu);
c65cc870
IM
1200}
1201
ac66f547
PZ
1202static void __migrate_swap_task(struct task_struct *p, int cpu)
1203{
da0c1e65 1204 if (task_on_rq_queued(p)) {
ac66f547 1205 struct rq *src_rq, *dst_rq;
8a8c69c3 1206 struct rq_flags srf, drf;
ac66f547
PZ
1207
1208 src_rq = task_rq(p);
1209 dst_rq = cpu_rq(cpu);
1210
8a8c69c3
PZ
1211 rq_pin_lock(src_rq, &srf);
1212 rq_pin_lock(dst_rq, &drf);
1213
3ea94de1 1214 p->on_rq = TASK_ON_RQ_MIGRATING;
ac66f547
PZ
1215 deactivate_task(src_rq, p, 0);
1216 set_task_cpu(p, cpu);
1217 activate_task(dst_rq, p, 0);
3ea94de1 1218 p->on_rq = TASK_ON_RQ_QUEUED;
ac66f547 1219 check_preempt_curr(dst_rq, p, 0);
8a8c69c3
PZ
1220
1221 rq_unpin_lock(dst_rq, &drf);
1222 rq_unpin_lock(src_rq, &srf);
1223
ac66f547
PZ
1224 } else {
1225 /*
1226 * Task isn't running anymore; make it appear like we migrated
1227 * it before it went to sleep. This means on wakeup we make the
d1ccc66d 1228 * previous CPU our target instead of where it really is.
ac66f547
PZ
1229 */
1230 p->wake_cpu = cpu;
1231 }
1232}
1233
1234struct migration_swap_arg {
1235 struct task_struct *src_task, *dst_task;
1236 int src_cpu, dst_cpu;
1237};
1238
1239static int migrate_swap_stop(void *data)
1240{
1241 struct migration_swap_arg *arg = data;
1242 struct rq *src_rq, *dst_rq;
1243 int ret = -EAGAIN;
1244
62694cd5
PZ
1245 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1246 return -EAGAIN;
1247
ac66f547
PZ
1248 src_rq = cpu_rq(arg->src_cpu);
1249 dst_rq = cpu_rq(arg->dst_cpu);
1250
74602315
PZ
1251 double_raw_lock(&arg->src_task->pi_lock,
1252 &arg->dst_task->pi_lock);
ac66f547 1253 double_rq_lock(src_rq, dst_rq);
62694cd5 1254
ac66f547
PZ
1255 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1256 goto unlock;
1257
1258 if (task_cpu(arg->src_task) != arg->src_cpu)
1259 goto unlock;
1260
0c98d344 1261 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
ac66f547
PZ
1262 goto unlock;
1263
0c98d344 1264 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
ac66f547
PZ
1265 goto unlock;
1266
1267 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1268 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1269
1270 ret = 0;
1271
1272unlock:
1273 double_rq_unlock(src_rq, dst_rq);
74602315
PZ
1274 raw_spin_unlock(&arg->dst_task->pi_lock);
1275 raw_spin_unlock(&arg->src_task->pi_lock);
ac66f547
PZ
1276
1277 return ret;
1278}
1279
1280/*
1281 * Cross migrate two tasks
1282 */
1283int migrate_swap(struct task_struct *cur, struct task_struct *p)
1284{
1285 struct migration_swap_arg arg;
1286 int ret = -EINVAL;
1287
ac66f547
PZ
1288 arg = (struct migration_swap_arg){
1289 .src_task = cur,
1290 .src_cpu = task_cpu(cur),
1291 .dst_task = p,
1292 .dst_cpu = task_cpu(p),
1293 };
1294
1295 if (arg.src_cpu == arg.dst_cpu)
1296 goto out;
1297
6acce3ef
PZ
1298 /*
1299 * These three tests are all lockless; this is OK since all of them
1300 * will be re-checked with proper locks held further down the line.
1301 */
ac66f547
PZ
1302 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1303 goto out;
1304
0c98d344 1305 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
ac66f547
PZ
1306 goto out;
1307
0c98d344 1308 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
ac66f547
PZ
1309 goto out;
1310
286549dc 1311 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ac66f547
PZ
1312 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1313
1314out:
ac66f547
PZ
1315 return ret;
1316}
1317
1da177e4
LT
1318/*
1319 * wait_task_inactive - wait for a thread to unschedule.
1320 *
85ba2d86
RM
1321 * If @match_state is nonzero, it's the @p->state value just checked and
1322 * not expected to change. If it changes, i.e. @p might have woken up,
1323 * then return zero. When we succeed in waiting for @p to be off its CPU,
1324 * we return a positive number (its total switch count). If a second call
1325 * a short while later returns the same number, the caller can be sure that
1326 * @p has remained unscheduled the whole time.
1327 *
1da177e4
LT
1328 * The caller must ensure that the task *will* unschedule sometime soon,
1329 * else this function might spin for a *long* time. This function can't
1330 * be called with interrupts off, or it may introduce deadlock with
1331 * smp_call_function() if an IPI is sent by the same process we are
1332 * waiting to become inactive.
1333 */
85ba2d86 1334unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1da177e4 1335{
da0c1e65 1336 int running, queued;
eb580751 1337 struct rq_flags rf;
85ba2d86 1338 unsigned long ncsw;
70b97a7f 1339 struct rq *rq;
1da177e4 1340
3a5c359a
AK
1341 for (;;) {
1342 /*
1343 * We do the initial early heuristics without holding
1344 * any task-queue locks at all. We'll only try to get
1345 * the runqueue lock when things look like they will
1346 * work out!
1347 */
1348 rq = task_rq(p);
fa490cfd 1349
3a5c359a
AK
1350 /*
1351 * If the task is actively running on another CPU
1352 * still, just relax and busy-wait without holding
1353 * any locks.
1354 *
1355 * NOTE! Since we don't hold any locks, it's not
1356 * even sure that "rq" stays as the right runqueue!
1357 * But we don't care, since "task_running()" will
1358 * return false if the runqueue has changed and p
1359 * is actually now running somewhere else!
1360 */
85ba2d86
RM
1361 while (task_running(rq, p)) {
1362 if (match_state && unlikely(p->state != match_state))
1363 return 0;
3a5c359a 1364 cpu_relax();
85ba2d86 1365 }
fa490cfd 1366
3a5c359a
AK
1367 /*
1368 * Ok, time to look more closely! We need the rq
1369 * lock now, to be *sure*. If we're wrong, we'll
1370 * just go back and repeat.
1371 */
eb580751 1372 rq = task_rq_lock(p, &rf);
27a9da65 1373 trace_sched_wait_task(p);
3a5c359a 1374 running = task_running(rq, p);
da0c1e65 1375 queued = task_on_rq_queued(p);
85ba2d86 1376 ncsw = 0;
f31e11d8 1377 if (!match_state || p->state == match_state)
93dcf55f 1378 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
eb580751 1379 task_rq_unlock(rq, p, &rf);
fa490cfd 1380
85ba2d86
RM
1381 /*
1382 * If it changed from the expected state, bail out now.
1383 */
1384 if (unlikely(!ncsw))
1385 break;
1386
3a5c359a
AK
1387 /*
1388 * Was it really running after all now that we
1389 * checked with the proper locks actually held?
1390 *
1391 * Oops. Go back and try again..
1392 */
1393 if (unlikely(running)) {
1394 cpu_relax();
1395 continue;
1396 }
fa490cfd 1397
3a5c359a
AK
1398 /*
1399 * It's not enough that it's not actively running,
1400 * it must be off the runqueue _entirely_, and not
1401 * preempted!
1402 *
80dd99b3 1403 * So if it was still runnable (but just not actively
3a5c359a
AK
1404 * running right now), it's preempted, and we should
1405 * yield - it could be a while.
1406 */
da0c1e65 1407 if (unlikely(queued)) {
8b0e1953 1408 ktime_t to = NSEC_PER_SEC / HZ;
8eb90c30
TG
1409
1410 set_current_state(TASK_UNINTERRUPTIBLE);
1411 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
3a5c359a
AK
1412 continue;
1413 }
fa490cfd 1414
3a5c359a
AK
1415 /*
1416 * Ahh, all good. It wasn't running, and it wasn't
1417 * runnable, which means that it will never become
1418 * running in the future either. We're all done!
1419 */
1420 break;
1421 }
85ba2d86
RM
1422
1423 return ncsw;
1da177e4
LT
1424}
1425
1426/***
1427 * kick_process - kick a running thread to enter/exit the kernel
1428 * @p: the to-be-kicked thread
1429 *
1430 * Cause a process which is running on another CPU to enter
1431 * kernel-mode, without any delay. (to get signals handled.)
1432 *
25985edc 1433 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
1434 * because all it wants to ensure is that the remote task enters
1435 * the kernel. If the IPI races and the task has been migrated
1436 * to another CPU then no harm is done and the purpose has been
1437 * achieved as well.
1438 */
36c8b586 1439void kick_process(struct task_struct *p)
1da177e4
LT
1440{
1441 int cpu;
1442
1443 preempt_disable();
1444 cpu = task_cpu(p);
1445 if ((cpu != smp_processor_id()) && task_curr(p))
1446 smp_send_reschedule(cpu);
1447 preempt_enable();
1448}
b43e3521 1449EXPORT_SYMBOL_GPL(kick_process);
1da177e4 1450
30da688e 1451/*
013fdb80 1452 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
e9d867a6
PZI
1453 *
1454 * A few notes on cpu_active vs cpu_online:
1455 *
1456 * - cpu_active must be a subset of cpu_online
1457 *
1458 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1459 * see __set_cpus_allowed_ptr(). At this point the newly online
d1ccc66d 1460 * CPU isn't yet part of the sched domains, and balancing will not
e9d867a6
PZI
1461 * see it.
1462 *
d1ccc66d 1463 * - on CPU-down we clear cpu_active() to mask the sched domains and
e9d867a6 1464 * avoid the load balancer to place new tasks on the to be removed
d1ccc66d 1465 * CPU. Existing tasks will remain running there and will be taken
e9d867a6
PZI
1466 * off.
1467 *
1468 * This means that fallback selection must not select !active CPUs.
1469 * And can assume that any active CPU must be online. Conversely
1470 * select_task_rq() below may allow selection of !active CPUs in order
1471 * to satisfy the above rules.
30da688e 1472 */
5da9a0fb
PZ
1473static int select_fallback_rq(int cpu, struct task_struct *p)
1474{
aa00d89c
TC
1475 int nid = cpu_to_node(cpu);
1476 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
1477 enum { cpuset, possible, fail } state = cpuset;
1478 int dest_cpu;
5da9a0fb 1479
aa00d89c 1480 /*
d1ccc66d
IM
1481 * If the node that the CPU is on has been offlined, cpu_to_node()
1482 * will return -1. There is no CPU on the node, and we should
1483 * select the CPU on the other node.
aa00d89c
TC
1484 */
1485 if (nid != -1) {
1486 nodemask = cpumask_of_node(nid);
1487
1488 /* Look for allowed, online CPU in same node. */
1489 for_each_cpu(dest_cpu, nodemask) {
aa00d89c
TC
1490 if (!cpu_active(dest_cpu))
1491 continue;
0c98d344 1492 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
aa00d89c
TC
1493 return dest_cpu;
1494 }
2baab4e9 1495 }
5da9a0fb 1496
2baab4e9
PZ
1497 for (;;) {
1498 /* Any allowed, online CPU? */
0c98d344 1499 for_each_cpu(dest_cpu, &p->cpus_allowed) {
feb245e3
TH
1500 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1501 continue;
1502 if (!cpu_online(dest_cpu))
2baab4e9
PZ
1503 continue;
1504 goto out;
1505 }
5da9a0fb 1506
e73e85f0 1507 /* No more Mr. Nice Guy. */
2baab4e9
PZ
1508 switch (state) {
1509 case cpuset:
e73e85f0
ON
1510 if (IS_ENABLED(CONFIG_CPUSETS)) {
1511 cpuset_cpus_allowed_fallback(p);
1512 state = possible;
1513 break;
1514 }
d1ccc66d 1515 /* Fall-through */
2baab4e9
PZ
1516 case possible:
1517 do_set_cpus_allowed(p, cpu_possible_mask);
1518 state = fail;
1519 break;
1520
1521 case fail:
1522 BUG();
1523 break;
1524 }
1525 }
1526
1527out:
1528 if (state != cpuset) {
1529 /*
1530 * Don't tell them about moving exiting tasks or
1531 * kernel threads (both mm NULL), since they never
1532 * leave kernel.
1533 */
1534 if (p->mm && printk_ratelimit()) {
aac74dc4 1535 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2baab4e9
PZ
1536 task_pid_nr(p), p->comm, cpu);
1537 }
5da9a0fb
PZ
1538 }
1539
1540 return dest_cpu;
1541}
1542
e2912009 1543/*
013fdb80 1544 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
e2912009 1545 */
970b13ba 1546static inline
ac66f547 1547int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
970b13ba 1548{
cbce1a68
PZ
1549 lockdep_assert_held(&p->pi_lock);
1550
4b53a341 1551 if (p->nr_cpus_allowed > 1)
6c1d9410 1552 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
e9d867a6 1553 else
0c98d344 1554 cpu = cpumask_any(&p->cpus_allowed);
e2912009
PZ
1555
1556 /*
1557 * In order not to call set_task_cpu() on a blocking task we need
1558 * to rely on ttwu() to place the task on a valid ->cpus_allowed
d1ccc66d 1559 * CPU.
e2912009
PZ
1560 *
1561 * Since this is common to all placement strategies, this lives here.
1562 *
1563 * [ this allows ->select_task() to simply return task_cpu(p) and
1564 * not worry about this generic constraint ]
1565 */
0c98d344 1566 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
70f11205 1567 !cpu_online(cpu)))
5da9a0fb 1568 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
1569
1570 return cpu;
970b13ba 1571}
09a40af5
MG
1572
1573static void update_avg(u64 *avg, u64 sample)
1574{
1575 s64 diff = sample - *avg;
1576 *avg += diff >> 3;
1577}
25834c73 1578
f5832c19
NP
1579void sched_set_stop_task(int cpu, struct task_struct *stop)
1580{
1581 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1582 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1583
1584 if (stop) {
1585 /*
1586 * Make it appear like a SCHED_FIFO task, its something
1587 * userspace knows about and won't get confused about.
1588 *
1589 * Also, it will make PI more or less work without too
1590 * much confusion -- but then, stop work should not
1591 * rely on PI working anyway.
1592 */
1593 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1594
1595 stop->sched_class = &stop_sched_class;
1596 }
1597
1598 cpu_rq(cpu)->stop = stop;
1599
1600 if (old_stop) {
1601 /*
1602 * Reset it back to a normal scheduling class so that
1603 * it can die in pieces.
1604 */
1605 old_stop->sched_class = &rt_sched_class;
1606 }
1607}
1608
25834c73
PZ
1609#else
1610
1611static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1612 const struct cpumask *new_mask, bool check)
1613{
1614 return set_cpus_allowed_ptr(p, new_mask);
1615}
1616
5cc389bc 1617#endif /* CONFIG_SMP */
970b13ba 1618
d7c01d27 1619static void
b84cb5df 1620ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 1621{
4fa8d299 1622 struct rq *rq;
b84cb5df 1623
4fa8d299
JP
1624 if (!schedstat_enabled())
1625 return;
1626
1627 rq = this_rq();
d7c01d27 1628
4fa8d299
JP
1629#ifdef CONFIG_SMP
1630 if (cpu == rq->cpu) {
ae92882e
JP
1631 schedstat_inc(rq->ttwu_local);
1632 schedstat_inc(p->se.statistics.nr_wakeups_local);
d7c01d27
PZ
1633 } else {
1634 struct sched_domain *sd;
1635
ae92882e 1636 schedstat_inc(p->se.statistics.nr_wakeups_remote);
057f3fad 1637 rcu_read_lock();
4fa8d299 1638 for_each_domain(rq->cpu, sd) {
d7c01d27 1639 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
ae92882e 1640 schedstat_inc(sd->ttwu_wake_remote);
d7c01d27
PZ
1641 break;
1642 }
1643 }
057f3fad 1644 rcu_read_unlock();
d7c01d27 1645 }
f339b9dc
PZ
1646
1647 if (wake_flags & WF_MIGRATED)
ae92882e 1648 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
d7c01d27
PZ
1649#endif /* CONFIG_SMP */
1650
ae92882e
JP
1651 schedstat_inc(rq->ttwu_count);
1652 schedstat_inc(p->se.statistics.nr_wakeups);
d7c01d27
PZ
1653
1654 if (wake_flags & WF_SYNC)
ae92882e 1655 schedstat_inc(p->se.statistics.nr_wakeups_sync);
d7c01d27
PZ
1656}
1657
1de64443 1658static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
d7c01d27 1659{
9ed3811a 1660 activate_task(rq, p, en_flags);
da0c1e65 1661 p->on_rq = TASK_ON_RQ_QUEUED;
c2f7115e 1662
d1ccc66d 1663 /* If a worker is waking up, notify the workqueue: */
c2f7115e
PZ
1664 if (p->flags & PF_WQ_WORKER)
1665 wq_worker_waking_up(p, cpu_of(rq));
9ed3811a
TH
1666}
1667
23f41eeb
PZ
1668/*
1669 * Mark the task runnable and perform wakeup-preemption.
1670 */
e7904a28 1671static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 1672 struct rq_flags *rf)
9ed3811a 1673{
9ed3811a 1674 check_preempt_curr(rq, p, wake_flags);
9ed3811a 1675 p->state = TASK_RUNNING;
fbd705a0
PZ
1676 trace_sched_wakeup(p);
1677
9ed3811a 1678#ifdef CONFIG_SMP
4c9a4bc8
PZ
1679 if (p->sched_class->task_woken) {
1680 /*
cbce1a68
PZ
1681 * Our task @p is fully woken up and running; so its safe to
1682 * drop the rq->lock, hereafter rq is only used for statistics.
4c9a4bc8 1683 */
d8ac8971 1684 rq_unpin_lock(rq, rf);
9ed3811a 1685 p->sched_class->task_woken(rq, p);
d8ac8971 1686 rq_repin_lock(rq, rf);
4c9a4bc8 1687 }
9ed3811a 1688
e69c6341 1689 if (rq->idle_stamp) {
78becc27 1690 u64 delta = rq_clock(rq) - rq->idle_stamp;
9bd721c5 1691 u64 max = 2*rq->max_idle_balance_cost;
9ed3811a 1692
abfafa54
JL
1693 update_avg(&rq->avg_idle, delta);
1694
1695 if (rq->avg_idle > max)
9ed3811a 1696 rq->avg_idle = max;
abfafa54 1697
9ed3811a
TH
1698 rq->idle_stamp = 0;
1699 }
1700#endif
1701}
1702
c05fbafb 1703static void
e7904a28 1704ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 1705 struct rq_flags *rf)
c05fbafb 1706{
77558e4d 1707 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
b5179ac7 1708
cbce1a68
PZ
1709 lockdep_assert_held(&rq->lock);
1710
c05fbafb
PZ
1711#ifdef CONFIG_SMP
1712 if (p->sched_contributes_to_load)
1713 rq->nr_uninterruptible--;
b5179ac7 1714
b5179ac7 1715 if (wake_flags & WF_MIGRATED)
59efa0ba 1716 en_flags |= ENQUEUE_MIGRATED;
c05fbafb
PZ
1717#endif
1718
b5179ac7 1719 ttwu_activate(rq, p, en_flags);
d8ac8971 1720 ttwu_do_wakeup(rq, p, wake_flags, rf);
c05fbafb
PZ
1721}
1722
1723/*
1724 * Called in case the task @p isn't fully descheduled from its runqueue,
1725 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1726 * since all we need to do is flip p->state to TASK_RUNNING, since
1727 * the task is still ->on_rq.
1728 */
1729static int ttwu_remote(struct task_struct *p, int wake_flags)
1730{
eb580751 1731 struct rq_flags rf;
c05fbafb
PZ
1732 struct rq *rq;
1733 int ret = 0;
1734
eb580751 1735 rq = __task_rq_lock(p, &rf);
da0c1e65 1736 if (task_on_rq_queued(p)) {
1ad4ec0d
FW
1737 /* check_preempt_curr() may use rq clock */
1738 update_rq_clock(rq);
d8ac8971 1739 ttwu_do_wakeup(rq, p, wake_flags, &rf);
c05fbafb
PZ
1740 ret = 1;
1741 }
eb580751 1742 __task_rq_unlock(rq, &rf);
c05fbafb
PZ
1743
1744 return ret;
1745}
1746
317f3941 1747#ifdef CONFIG_SMP
e3baac47 1748void sched_ttwu_pending(void)
317f3941
PZ
1749{
1750 struct rq *rq = this_rq();
fa14ff4a 1751 struct llist_node *llist = llist_del_all(&rq->wake_list);
73215849 1752 struct task_struct *p, *t;
d8ac8971 1753 struct rq_flags rf;
317f3941 1754
e3baac47
PZ
1755 if (!llist)
1756 return;
1757
8a8c69c3 1758 rq_lock_irqsave(rq, &rf);
77558e4d 1759 update_rq_clock(rq);
317f3941 1760
73215849
BP
1761 llist_for_each_entry_safe(p, t, llist, wake_entry)
1762 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
317f3941 1763
8a8c69c3 1764 rq_unlock_irqrestore(rq, &rf);
317f3941
PZ
1765}
1766
1767void scheduler_ipi(void)
1768{
f27dde8d
PZ
1769 /*
1770 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1771 * TIF_NEED_RESCHED remotely (for the first time) will also send
1772 * this IPI.
1773 */
8cb75e0c 1774 preempt_fold_need_resched();
f27dde8d 1775
fd2ac4f4 1776 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
c5d753a5
PZ
1777 return;
1778
1779 /*
1780 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1781 * traditionally all their work was done from the interrupt return
1782 * path. Now that we actually do some work, we need to make sure
1783 * we do call them.
1784 *
1785 * Some archs already do call them, luckily irq_enter/exit nest
1786 * properly.
1787 *
1788 * Arguably we should visit all archs and update all handlers,
1789 * however a fair share of IPIs are still resched only so this would
1790 * somewhat pessimize the simple resched case.
1791 */
1792 irq_enter();
fa14ff4a 1793 sched_ttwu_pending();
ca38062e
SS
1794
1795 /*
1796 * Check if someone kicked us for doing the nohz idle load balance.
1797 */
873b4c65 1798 if (unlikely(got_nohz_idle_kick())) {
6eb57e0d 1799 this_rq()->idle_balance = 1;
ca38062e 1800 raise_softirq_irqoff(SCHED_SOFTIRQ);
6eb57e0d 1801 }
c5d753a5 1802 irq_exit();
317f3941
PZ
1803}
1804
b7e7ade3 1805static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
317f3941 1806{
e3baac47
PZ
1807 struct rq *rq = cpu_rq(cpu);
1808
b7e7ade3
PZ
1809 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1810
e3baac47
PZ
1811 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1812 if (!set_nr_if_polling(rq->idle))
1813 smp_send_reschedule(cpu);
1814 else
1815 trace_sched_wake_idle_without_ipi(cpu);
1816 }
317f3941 1817}
d6aa8f85 1818
f6be8af1
CL
1819void wake_up_if_idle(int cpu)
1820{
1821 struct rq *rq = cpu_rq(cpu);
8a8c69c3 1822 struct rq_flags rf;
f6be8af1 1823
fd7de1e8
AL
1824 rcu_read_lock();
1825
1826 if (!is_idle_task(rcu_dereference(rq->curr)))
1827 goto out;
f6be8af1
CL
1828
1829 if (set_nr_if_polling(rq->idle)) {
1830 trace_sched_wake_idle_without_ipi(cpu);
1831 } else {
8a8c69c3 1832 rq_lock_irqsave(rq, &rf);
f6be8af1
CL
1833 if (is_idle_task(rq->curr))
1834 smp_send_reschedule(cpu);
d1ccc66d 1835 /* Else CPU is not idle, do nothing here: */
8a8c69c3 1836 rq_unlock_irqrestore(rq, &rf);
f6be8af1 1837 }
fd7de1e8
AL
1838
1839out:
1840 rcu_read_unlock();
f6be8af1
CL
1841}
1842
39be3501 1843bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623
PZ
1844{
1845 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1846}
d6aa8f85 1847#endif /* CONFIG_SMP */
317f3941 1848
b5179ac7 1849static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
c05fbafb
PZ
1850{
1851 struct rq *rq = cpu_rq(cpu);
d8ac8971 1852 struct rq_flags rf;
c05fbafb 1853
17d9f311 1854#if defined(CONFIG_SMP)
39be3501 1855 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
d1ccc66d 1856 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
b7e7ade3 1857 ttwu_queue_remote(p, cpu, wake_flags);
317f3941
PZ
1858 return;
1859 }
1860#endif
1861
8a8c69c3 1862 rq_lock(rq, &rf);
77558e4d 1863 update_rq_clock(rq);
d8ac8971 1864 ttwu_do_activate(rq, p, wake_flags, &rf);
8a8c69c3 1865 rq_unlock(rq, &rf);
9ed3811a
TH
1866}
1867
8643cda5
PZ
1868/*
1869 * Notes on Program-Order guarantees on SMP systems.
1870 *
1871 * MIGRATION
1872 *
1873 * The basic program-order guarantee on SMP systems is that when a task [t]
d1ccc66d
IM
1874 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1875 * execution on its new CPU [c1].
8643cda5
PZ
1876 *
1877 * For migration (of runnable tasks) this is provided by the following means:
1878 *
1879 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1880 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1881 * rq(c1)->lock (if not at the same time, then in that order).
1882 * C) LOCK of the rq(c1)->lock scheduling in task
1883 *
1884 * Transitivity guarantees that B happens after A and C after B.
1885 * Note: we only require RCpc transitivity.
d1ccc66d 1886 * Note: the CPU doing B need not be c0 or c1
8643cda5
PZ
1887 *
1888 * Example:
1889 *
1890 * CPU0 CPU1 CPU2
1891 *
1892 * LOCK rq(0)->lock
1893 * sched-out X
1894 * sched-in Y
1895 * UNLOCK rq(0)->lock
1896 *
1897 * LOCK rq(0)->lock // orders against CPU0
1898 * dequeue X
1899 * UNLOCK rq(0)->lock
1900 *
1901 * LOCK rq(1)->lock
1902 * enqueue X
1903 * UNLOCK rq(1)->lock
1904 *
1905 * LOCK rq(1)->lock // orders against CPU2
1906 * sched-out Z
1907 * sched-in X
1908 * UNLOCK rq(1)->lock
1909 *
1910 *
1911 * BLOCKING -- aka. SLEEP + WAKEUP
1912 *
1913 * For blocking we (obviously) need to provide the same guarantee as for
1914 * migration. However the means are completely different as there is no lock
1915 * chain to provide order. Instead we do:
1916 *
1917 * 1) smp_store_release(X->on_cpu, 0)
1f03e8d2 1918 * 2) smp_cond_load_acquire(!X->on_cpu)
8643cda5
PZ
1919 *
1920 * Example:
1921 *
1922 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1923 *
1924 * LOCK rq(0)->lock LOCK X->pi_lock
1925 * dequeue X
1926 * sched-out X
1927 * smp_store_release(X->on_cpu, 0);
1928 *
1f03e8d2 1929 * smp_cond_load_acquire(&X->on_cpu, !VAL);
8643cda5
PZ
1930 * X->state = WAKING
1931 * set_task_cpu(X,2)
1932 *
1933 * LOCK rq(2)->lock
1934 * enqueue X
1935 * X->state = RUNNING
1936 * UNLOCK rq(2)->lock
1937 *
1938 * LOCK rq(2)->lock // orders against CPU1
1939 * sched-out Z
1940 * sched-in X
1941 * UNLOCK rq(2)->lock
1942 *
1943 * UNLOCK X->pi_lock
1944 * UNLOCK rq(0)->lock
1945 *
1946 *
1947 * However; for wakeups there is a second guarantee we must provide, namely we
1948 * must observe the state that lead to our wakeup. That is, not only must our
1949 * task observe its own prior state, it must also observe the stores prior to
1950 * its wakeup.
1951 *
1952 * This means that any means of doing remote wakeups must order the CPU doing
1953 * the wakeup against the CPU the task is going to end up running on. This,
1954 * however, is already required for the regular Program-Order guarantee above,
1f03e8d2 1955 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
8643cda5
PZ
1956 *
1957 */
1958
9ed3811a 1959/**
1da177e4 1960 * try_to_wake_up - wake up a thread
9ed3811a 1961 * @p: the thread to be awakened
1da177e4 1962 * @state: the mask of task states that can be woken
9ed3811a 1963 * @wake_flags: wake modifier flags (WF_*)
1da177e4 1964 *
a2250238 1965 * If (@state & @p->state) @p->state = TASK_RUNNING.
1da177e4 1966 *
a2250238
PZ
1967 * If the task was not queued/runnable, also place it back on a runqueue.
1968 *
1969 * Atomic against schedule() which would dequeue a task, also see
1970 * set_current_state().
1971 *
1972 * Return: %true if @p->state changes (an actual wakeup was done),
1973 * %false otherwise.
1da177e4 1974 */
e4a52bcb
PZ
1975static int
1976try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 1977{
1da177e4 1978 unsigned long flags;
c05fbafb 1979 int cpu, success = 0;
2398f2c6 1980
e0acd0a6
ON
1981 /*
1982 * If we are going to wake up a thread waiting for CONDITION we
1983 * need to ensure that CONDITION=1 done by the caller can not be
1984 * reordered with p->state check below. This pairs with mb() in
1985 * set_current_state() the waiting thread does.
1986 */
013fdb80 1987 raw_spin_lock_irqsave(&p->pi_lock, flags);
d89e588c 1988 smp_mb__after_spinlock();
e9c84311 1989 if (!(p->state & state))
1da177e4
LT
1990 goto out;
1991
fbd705a0
PZ
1992 trace_sched_waking(p);
1993
d1ccc66d
IM
1994 /* We're going to change ->state: */
1995 success = 1;
1da177e4 1996 cpu = task_cpu(p);
1da177e4 1997
135e8c92
BS
1998 /*
1999 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2000 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2001 * in smp_cond_load_acquire() below.
2002 *
2003 * sched_ttwu_pending() try_to_wake_up()
2004 * [S] p->on_rq = 1; [L] P->state
2005 * UNLOCK rq->lock -----.
2006 * \
2007 * +--- RMB
2008 * schedule() /
2009 * LOCK rq->lock -----'
2010 * UNLOCK rq->lock
2011 *
2012 * [task p]
2013 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2014 *
2015 * Pairs with the UNLOCK+LOCK on rq->lock from the
2016 * last wakeup of our task and the schedule that got our task
2017 * current.
2018 */
2019 smp_rmb();
c05fbafb
PZ
2020 if (p->on_rq && ttwu_remote(p, wake_flags))
2021 goto stat;
1da177e4 2022
1da177e4 2023#ifdef CONFIG_SMP
ecf7d01c
PZ
2024 /*
2025 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2026 * possible to, falsely, observe p->on_cpu == 0.
2027 *
2028 * One must be running (->on_cpu == 1) in order to remove oneself
2029 * from the runqueue.
2030 *
2031 * [S] ->on_cpu = 1; [L] ->on_rq
2032 * UNLOCK rq->lock
2033 * RMB
2034 * LOCK rq->lock
2035 * [S] ->on_rq = 0; [L] ->on_cpu
2036 *
2037 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2038 * from the consecutive calls to schedule(); the first switching to our
2039 * task, the second putting it to sleep.
2040 */
2041 smp_rmb();
2042
e9c84311 2043 /*
d1ccc66d 2044 * If the owning (remote) CPU is still in the middle of schedule() with
c05fbafb 2045 * this task as prev, wait until its done referencing the task.
b75a2253
PZ
2046 *
2047 * Pairs with the smp_store_release() in finish_lock_switch().
2048 *
2049 * This ensures that tasks getting woken will be fully ordered against
2050 * their previous state and preserve Program Order.
0970d299 2051 */
1f03e8d2 2052 smp_cond_load_acquire(&p->on_cpu, !VAL);
1da177e4 2053
a8e4f2ea 2054 p->sched_contributes_to_load = !!task_contributes_to_load(p);
e9c84311 2055 p->state = TASK_WAKING;
e7693a36 2056
e33a9bba
TH
2057 if (p->in_iowait) {
2058 delayacct_blkio_end();
2059 atomic_dec(&task_rq(p)->nr_iowait);
2060 }
2061
ac66f547 2062 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
f339b9dc
PZ
2063 if (task_cpu(p) != cpu) {
2064 wake_flags |= WF_MIGRATED;
e4a52bcb 2065 set_task_cpu(p, cpu);
f339b9dc 2066 }
e33a9bba
TH
2067
2068#else /* CONFIG_SMP */
2069
2070 if (p->in_iowait) {
2071 delayacct_blkio_end();
2072 atomic_dec(&task_rq(p)->nr_iowait);
2073 }
2074
1da177e4 2075#endif /* CONFIG_SMP */
1da177e4 2076
b5179ac7 2077 ttwu_queue(p, cpu, wake_flags);
c05fbafb 2078stat:
4fa8d299 2079 ttwu_stat(p, cpu, wake_flags);
1da177e4 2080out:
013fdb80 2081 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
2082
2083 return success;
2084}
2085
21aa9af0
TH
2086/**
2087 * try_to_wake_up_local - try to wake up a local task with rq lock held
2088 * @p: the thread to be awakened
bf50f0e8 2089 * @rf: request-queue flags for pinning
21aa9af0 2090 *
2acca55e 2091 * Put @p on the run-queue if it's not already there. The caller must
21aa9af0 2092 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2acca55e 2093 * the current task.
21aa9af0 2094 */
d8ac8971 2095static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
21aa9af0
TH
2096{
2097 struct rq *rq = task_rq(p);
21aa9af0 2098
383efcd0
TH
2099 if (WARN_ON_ONCE(rq != this_rq()) ||
2100 WARN_ON_ONCE(p == current))
2101 return;
2102
21aa9af0
TH
2103 lockdep_assert_held(&rq->lock);
2104
2acca55e 2105 if (!raw_spin_trylock(&p->pi_lock)) {
cbce1a68
PZ
2106 /*
2107 * This is OK, because current is on_cpu, which avoids it being
2108 * picked for load-balance and preemption/IRQs are still
2109 * disabled avoiding further scheduler activity on it and we've
2110 * not yet picked a replacement task.
2111 */
8a8c69c3 2112 rq_unlock(rq, rf);
2acca55e 2113 raw_spin_lock(&p->pi_lock);
8a8c69c3 2114 rq_relock(rq, rf);
2acca55e
PZ
2115 }
2116
21aa9af0 2117 if (!(p->state & TASK_NORMAL))
2acca55e 2118 goto out;
21aa9af0 2119
fbd705a0
PZ
2120 trace_sched_waking(p);
2121
e33a9bba
TH
2122 if (!task_on_rq_queued(p)) {
2123 if (p->in_iowait) {
2124 delayacct_blkio_end();
2125 atomic_dec(&rq->nr_iowait);
2126 }
bce4dc80 2127 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
e33a9bba 2128 }
d7c01d27 2129
d8ac8971 2130 ttwu_do_wakeup(rq, p, 0, rf);
4fa8d299 2131 ttwu_stat(p, smp_processor_id(), 0);
2acca55e
PZ
2132out:
2133 raw_spin_unlock(&p->pi_lock);
21aa9af0
TH
2134}
2135
50fa610a
DH
2136/**
2137 * wake_up_process - Wake up a specific process
2138 * @p: The process to be woken up.
2139 *
2140 * Attempt to wake up the nominated process and move it to the set of runnable
e69f6186
YB
2141 * processes.
2142 *
2143 * Return: 1 if the process was woken up, 0 if it was already running.
50fa610a
DH
2144 *
2145 * It may be assumed that this function implies a write memory barrier before
2146 * changing the task state if and only if any tasks are woken up.
2147 */
7ad5b3a5 2148int wake_up_process(struct task_struct *p)
1da177e4 2149{
9067ac85 2150 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 2151}
1da177e4
LT
2152EXPORT_SYMBOL(wake_up_process);
2153
7ad5b3a5 2154int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
2155{
2156 return try_to_wake_up(p, state, 0);
2157}
2158
1da177e4
LT
2159/*
2160 * Perform scheduler related setup for a newly forked process p.
2161 * p is forked by current.
dd41f596
IM
2162 *
2163 * __sched_fork() is basic setup used by init_idle() too:
2164 */
5e1576ed 2165static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 2166{
fd2f4419
PZ
2167 p->on_rq = 0;
2168
2169 p->se.on_rq = 0;
dd41f596
IM
2170 p->se.exec_start = 0;
2171 p->se.sum_exec_runtime = 0;
f6cf891c 2172 p->se.prev_sum_exec_runtime = 0;
6c594c21 2173 p->se.nr_migrations = 0;
da7a735e 2174 p->se.vruntime = 0;
fd2f4419 2175 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 2176
ad936d86
BP
2177#ifdef CONFIG_FAIR_GROUP_SCHED
2178 p->se.cfs_rq = NULL;
2179#endif
2180
6cfb0d5d 2181#ifdef CONFIG_SCHEDSTATS
cb251765 2182 /* Even if schedstat is disabled, there should not be garbage */
41acab88 2183 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
6cfb0d5d 2184#endif
476d139c 2185
aab03e05 2186 RB_CLEAR_NODE(&p->dl.rb_node);
40767b0d 2187 init_dl_task_timer(&p->dl);
209a0cbd 2188 init_dl_inactive_task_timer(&p->dl);
a5e7be3b 2189 __dl_clear_params(p);
aab03e05 2190
fa717060 2191 INIT_LIST_HEAD(&p->rt.run_list);
ff77e468
PZ
2192 p->rt.timeout = 0;
2193 p->rt.time_slice = sched_rr_timeslice;
2194 p->rt.on_rq = 0;
2195 p->rt.on_list = 0;
476d139c 2196
e107be36
AK
2197#ifdef CONFIG_PREEMPT_NOTIFIERS
2198 INIT_HLIST_HEAD(&p->preempt_notifiers);
2199#endif
cbee9f88
PZ
2200
2201#ifdef CONFIG_NUMA_BALANCING
2202 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
7e8d16b6 2203 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
cbee9f88
PZ
2204 p->mm->numa_scan_seq = 0;
2205 }
2206
5e1576ed
RR
2207 if (clone_flags & CLONE_VM)
2208 p->numa_preferred_nid = current->numa_preferred_nid;
2209 else
2210 p->numa_preferred_nid = -1;
2211
cbee9f88
PZ
2212 p->node_stamp = 0ULL;
2213 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
4b96a29b 2214 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
cbee9f88 2215 p->numa_work.next = &p->numa_work;
44dba3d5 2216 p->numa_faults = NULL;
7e2703e6
RR
2217 p->last_task_numa_placement = 0;
2218 p->last_sum_exec_runtime = 0;
8c8a743c 2219
8c8a743c 2220 p->numa_group = NULL;
cbee9f88 2221#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
2222}
2223
2a595721
SD
2224DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2225
1a687c2e 2226#ifdef CONFIG_NUMA_BALANCING
c3b9bc5b 2227
1a687c2e
MG
2228void set_numabalancing_state(bool enabled)
2229{
2230 if (enabled)
2a595721 2231 static_branch_enable(&sched_numa_balancing);
1a687c2e 2232 else
2a595721 2233 static_branch_disable(&sched_numa_balancing);
1a687c2e 2234}
54a43d54
AK
2235
2236#ifdef CONFIG_PROC_SYSCTL
2237int sysctl_numa_balancing(struct ctl_table *table, int write,
2238 void __user *buffer, size_t *lenp, loff_t *ppos)
2239{
2240 struct ctl_table t;
2241 int err;
2a595721 2242 int state = static_branch_likely(&sched_numa_balancing);
54a43d54
AK
2243
2244 if (write && !capable(CAP_SYS_ADMIN))
2245 return -EPERM;
2246
2247 t = *table;
2248 t.data = &state;
2249 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2250 if (err < 0)
2251 return err;
2252 if (write)
2253 set_numabalancing_state(state);
2254 return err;
2255}
2256#endif
2257#endif
dd41f596 2258
4698f88c
JP
2259#ifdef CONFIG_SCHEDSTATS
2260
cb251765 2261DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4698f88c 2262static bool __initdata __sched_schedstats = false;
cb251765 2263
cb251765
MG
2264static void set_schedstats(bool enabled)
2265{
2266 if (enabled)
2267 static_branch_enable(&sched_schedstats);
2268 else
2269 static_branch_disable(&sched_schedstats);
2270}
2271
2272void force_schedstat_enabled(void)
2273{
2274 if (!schedstat_enabled()) {
2275 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2276 static_branch_enable(&sched_schedstats);
2277 }
2278}
2279
2280static int __init setup_schedstats(char *str)
2281{
2282 int ret = 0;
2283 if (!str)
2284 goto out;
2285
4698f88c
JP
2286 /*
2287 * This code is called before jump labels have been set up, so we can't
2288 * change the static branch directly just yet. Instead set a temporary
2289 * variable so init_schedstats() can do it later.
2290 */
cb251765 2291 if (!strcmp(str, "enable")) {
4698f88c 2292 __sched_schedstats = true;
cb251765
MG
2293 ret = 1;
2294 } else if (!strcmp(str, "disable")) {
4698f88c 2295 __sched_schedstats = false;
cb251765
MG
2296 ret = 1;
2297 }
2298out:
2299 if (!ret)
2300 pr_warn("Unable to parse schedstats=\n");
2301
2302 return ret;
2303}
2304__setup("schedstats=", setup_schedstats);
2305
4698f88c
JP
2306static void __init init_schedstats(void)
2307{
2308 set_schedstats(__sched_schedstats);
2309}
2310
cb251765
MG
2311#ifdef CONFIG_PROC_SYSCTL
2312int sysctl_schedstats(struct ctl_table *table, int write,
2313 void __user *buffer, size_t *lenp, loff_t *ppos)
2314{
2315 struct ctl_table t;
2316 int err;
2317 int state = static_branch_likely(&sched_schedstats);
2318
2319 if (write && !capable(CAP_SYS_ADMIN))
2320 return -EPERM;
2321
2322 t = *table;
2323 t.data = &state;
2324 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2325 if (err < 0)
2326 return err;
2327 if (write)
2328 set_schedstats(state);
2329 return err;
2330}
4698f88c
JP
2331#endif /* CONFIG_PROC_SYSCTL */
2332#else /* !CONFIG_SCHEDSTATS */
2333static inline void init_schedstats(void) {}
2334#endif /* CONFIG_SCHEDSTATS */
dd41f596
IM
2335
2336/*
2337 * fork()/clone()-time setup:
2338 */
aab03e05 2339int sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 2340{
0122ec5b 2341 unsigned long flags;
dd41f596
IM
2342 int cpu = get_cpu();
2343
5e1576ed 2344 __sched_fork(clone_flags, p);
06b83b5f 2345 /*
7dc603c9 2346 * We mark the process as NEW here. This guarantees that
06b83b5f
PZ
2347 * nobody will actually run it, and a signal or other external
2348 * event cannot wake it up and insert it on the runqueue either.
2349 */
7dc603c9 2350 p->state = TASK_NEW;
dd41f596 2351
c350a04e
MG
2352 /*
2353 * Make sure we do not leak PI boosting priority to the child.
2354 */
2355 p->prio = current->normal_prio;
2356
b9dc29e7
MG
2357 /*
2358 * Revert to default priority/policy on fork if requested.
2359 */
2360 if (unlikely(p->sched_reset_on_fork)) {
aab03e05 2361 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
b9dc29e7 2362 p->policy = SCHED_NORMAL;
6c697bdf 2363 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
2364 p->rt_priority = 0;
2365 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2366 p->static_prio = NICE_TO_PRIO(0);
2367
2368 p->prio = p->normal_prio = __normal_prio(p);
9059393e 2369 set_load_weight(p, false);
6c697bdf 2370
b9dc29e7
MG
2371 /*
2372 * We don't need the reset flag anymore after the fork. It has
2373 * fulfilled its duty:
2374 */
2375 p->sched_reset_on_fork = 0;
2376 }
ca94c442 2377
aab03e05
DF
2378 if (dl_prio(p->prio)) {
2379 put_cpu();
2380 return -EAGAIN;
2381 } else if (rt_prio(p->prio)) {
2382 p->sched_class = &rt_sched_class;
2383 } else {
2ddbf952 2384 p->sched_class = &fair_sched_class;
aab03e05 2385 }
b29739f9 2386
7dc603c9 2387 init_entity_runnable_average(&p->se);
cd29fe6f 2388
86951599
PZ
2389 /*
2390 * The child is not yet in the pid-hash so no cgroup attach races,
2391 * and the cgroup is pinned to this child due to cgroup_fork()
2392 * is ran before sched_fork().
2393 *
2394 * Silence PROVE_RCU.
2395 */
0122ec5b 2396 raw_spin_lock_irqsave(&p->pi_lock, flags);
e210bffd 2397 /*
d1ccc66d 2398 * We're setting the CPU for the first time, we don't migrate,
e210bffd
PZ
2399 * so use __set_task_cpu().
2400 */
2401 __set_task_cpu(p, cpu);
2402 if (p->sched_class->task_fork)
2403 p->sched_class->task_fork(p);
0122ec5b 2404 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5f3edc1b 2405
f6db8347 2406#ifdef CONFIG_SCHED_INFO
dd41f596 2407 if (likely(sched_info_on()))
52f17b6c 2408 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 2409#endif
3ca7a440
PZ
2410#if defined(CONFIG_SMP)
2411 p->on_cpu = 0;
4866cde0 2412#endif
01028747 2413 init_task_preempt_count(p);
806c09a7 2414#ifdef CONFIG_SMP
917b627d 2415 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1baca4ce 2416 RB_CLEAR_NODE(&p->pushable_dl_tasks);
806c09a7 2417#endif
917b627d 2418
476d139c 2419 put_cpu();
aab03e05 2420 return 0;
1da177e4
LT
2421}
2422
332ac17e
DF
2423unsigned long to_ratio(u64 period, u64 runtime)
2424{
2425 if (runtime == RUNTIME_INF)
c52f14d3 2426 return BW_UNIT;
332ac17e
DF
2427
2428 /*
2429 * Doing this here saves a lot of checks in all
2430 * the calling paths, and returning zero seems
2431 * safe for them anyway.
2432 */
2433 if (period == 0)
2434 return 0;
2435
c52f14d3 2436 return div64_u64(runtime << BW_SHIFT, period);
332ac17e
DF
2437}
2438
1da177e4
LT
2439/*
2440 * wake_up_new_task - wake up a newly created task for the first time.
2441 *
2442 * This function will do some initial scheduler statistics housekeeping
2443 * that must be done for every newly created context, then puts the task
2444 * on the runqueue and wakes it.
2445 */
3e51e3ed 2446void wake_up_new_task(struct task_struct *p)
1da177e4 2447{
eb580751 2448 struct rq_flags rf;
dd41f596 2449 struct rq *rq;
fabf318e 2450
eb580751 2451 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
7dc603c9 2452 p->state = TASK_RUNNING;
fabf318e
PZ
2453#ifdef CONFIG_SMP
2454 /*
2455 * Fork balancing, do it here and not earlier because:
2456 * - cpus_allowed can change in the fork path
d1ccc66d 2457 * - any previously selected CPU might disappear through hotplug
e210bffd
PZ
2458 *
2459 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2460 * as we're not fully set-up yet.
fabf318e 2461 */
e210bffd 2462 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
0017d735 2463#endif
b7fa30c9 2464 rq = __task_rq_lock(p, &rf);
4126bad6 2465 update_rq_clock(rq);
2b8c41da 2466 post_init_entity_util_avg(&p->se);
0017d735 2467
7a57f32a 2468 activate_task(rq, p, ENQUEUE_NOCLOCK);
da0c1e65 2469 p->on_rq = TASK_ON_RQ_QUEUED;
fbd705a0 2470 trace_sched_wakeup_new(p);
a7558e01 2471 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 2472#ifdef CONFIG_SMP
0aaafaab
PZ
2473 if (p->sched_class->task_woken) {
2474 /*
2475 * Nothing relies on rq->lock after this, so its fine to
2476 * drop it.
2477 */
d8ac8971 2478 rq_unpin_lock(rq, &rf);
efbbd05a 2479 p->sched_class->task_woken(rq, p);
d8ac8971 2480 rq_repin_lock(rq, &rf);
0aaafaab 2481 }
9a897c5a 2482#endif
eb580751 2483 task_rq_unlock(rq, p, &rf);
1da177e4
LT
2484}
2485
e107be36
AK
2486#ifdef CONFIG_PREEMPT_NOTIFIERS
2487
1cde2930
PZ
2488static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2489
2ecd9d29
PZ
2490void preempt_notifier_inc(void)
2491{
2492 static_key_slow_inc(&preempt_notifier_key);
2493}
2494EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2495
2496void preempt_notifier_dec(void)
2497{
2498 static_key_slow_dec(&preempt_notifier_key);
2499}
2500EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2501
e107be36 2502/**
80dd99b3 2503 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 2504 * @notifier: notifier struct to register
e107be36
AK
2505 */
2506void preempt_notifier_register(struct preempt_notifier *notifier)
2507{
2ecd9d29
PZ
2508 if (!static_key_false(&preempt_notifier_key))
2509 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2510
e107be36
AK
2511 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2512}
2513EXPORT_SYMBOL_GPL(preempt_notifier_register);
2514
2515/**
2516 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 2517 * @notifier: notifier struct to unregister
e107be36 2518 *
d84525a8 2519 * This is *not* safe to call from within a preemption notifier.
e107be36
AK
2520 */
2521void preempt_notifier_unregister(struct preempt_notifier *notifier)
2522{
2523 hlist_del(&notifier->link);
2524}
2525EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2526
1cde2930 2527static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
2528{
2529 struct preempt_notifier *notifier;
e107be36 2530
b67bfe0d 2531 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2532 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2533}
2534
1cde2930
PZ
2535static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2536{
2537 if (static_key_false(&preempt_notifier_key))
2538 __fire_sched_in_preempt_notifiers(curr);
2539}
2540
e107be36 2541static void
1cde2930
PZ
2542__fire_sched_out_preempt_notifiers(struct task_struct *curr,
2543 struct task_struct *next)
e107be36
AK
2544{
2545 struct preempt_notifier *notifier;
e107be36 2546
b67bfe0d 2547 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2548 notifier->ops->sched_out(notifier, next);
2549}
2550
1cde2930
PZ
2551static __always_inline void
2552fire_sched_out_preempt_notifiers(struct task_struct *curr,
2553 struct task_struct *next)
2554{
2555 if (static_key_false(&preempt_notifier_key))
2556 __fire_sched_out_preempt_notifiers(curr, next);
2557}
2558
6d6bc0ad 2559#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36 2560
1cde2930 2561static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
2562{
2563}
2564
1cde2930 2565static inline void
e107be36
AK
2566fire_sched_out_preempt_notifiers(struct task_struct *curr,
2567 struct task_struct *next)
2568{
2569}
2570
6d6bc0ad 2571#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 2572
4866cde0
NP
2573/**
2574 * prepare_task_switch - prepare to switch tasks
2575 * @rq: the runqueue preparing to switch
421cee29 2576 * @prev: the current task that is being switched out
4866cde0
NP
2577 * @next: the task we are going to switch to.
2578 *
2579 * This is called with the rq lock held and interrupts off. It must
2580 * be paired with a subsequent finish_task_switch after the context
2581 * switch.
2582 *
2583 * prepare_task_switch sets up locking and calls architecture specific
2584 * hooks.
2585 */
e107be36
AK
2586static inline void
2587prepare_task_switch(struct rq *rq, struct task_struct *prev,
2588 struct task_struct *next)
4866cde0 2589{
43148951 2590 sched_info_switch(rq, prev, next);
fe4b04fa 2591 perf_event_task_sched_out(prev, next);
e107be36 2592 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
2593 prepare_lock_switch(rq, next);
2594 prepare_arch_switch(next);
2595}
2596
1da177e4
LT
2597/**
2598 * finish_task_switch - clean up after a task-switch
2599 * @prev: the thread we just switched away from.
2600 *
4866cde0
NP
2601 * finish_task_switch must be called after the context switch, paired
2602 * with a prepare_task_switch call before the context switch.
2603 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2604 * and do any other architecture-specific cleanup actions.
1da177e4
LT
2605 *
2606 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 2607 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
2608 * with the lock held can cause deadlocks; see schedule() for
2609 * details.)
dfa50b60
ON
2610 *
2611 * The context switch have flipped the stack from under us and restored the
2612 * local variables which were saved when this task called schedule() in the
2613 * past. prev == current is still correct but we need to recalculate this_rq
2614 * because prev may have moved to another CPU.
1da177e4 2615 */
dfa50b60 2616static struct rq *finish_task_switch(struct task_struct *prev)
1da177e4
LT
2617 __releases(rq->lock)
2618{
dfa50b60 2619 struct rq *rq = this_rq();
1da177e4 2620 struct mm_struct *mm = rq->prev_mm;
55a101f8 2621 long prev_state;
1da177e4 2622
609ca066
PZ
2623 /*
2624 * The previous task will have left us with a preempt_count of 2
2625 * because it left us after:
2626 *
2627 * schedule()
2628 * preempt_disable(); // 1
2629 * __schedule()
2630 * raw_spin_lock_irq(&rq->lock) // 2
2631 *
2632 * Also, see FORK_PREEMPT_COUNT.
2633 */
e2bf1c4b
PZ
2634 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2635 "corrupted preempt_count: %s/%d/0x%x\n",
2636 current->comm, current->pid, preempt_count()))
2637 preempt_count_set(FORK_PREEMPT_COUNT);
609ca066 2638
1da177e4
LT
2639 rq->prev_mm = NULL;
2640
2641 /*
2642 * A task struct has one reference for the use as "current".
c394cc9f 2643 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
2644 * schedule one last time. The schedule call will never return, and
2645 * the scheduled task must drop that reference.
95913d97
PZ
2646 *
2647 * We must observe prev->state before clearing prev->on_cpu (in
2648 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2649 * running on another CPU and we could rave with its RUNNING -> DEAD
2650 * transition, resulting in a double drop.
1da177e4 2651 */
55a101f8 2652 prev_state = prev->state;
bf9fae9f 2653 vtime_task_switch(prev);
a8d757ef 2654 perf_event_task_sched_in(prev, current);
22e4ebb9
MD
2655 /*
2656 * The membarrier system call requires a full memory barrier
2657 * after storing to rq->curr, before going back to user-space.
2658 *
2659 * TODO: This smp_mb__after_unlock_lock can go away if PPC end
2660 * up adding a full barrier to switch_mm(), or we should figure
2661 * out if a smp_mb__after_unlock_lock is really the proper API
2662 * to use.
2663 */
2664 smp_mb__after_unlock_lock();
4866cde0 2665 finish_lock_switch(rq, prev);
01f23e16 2666 finish_arch_post_lock_switch();
e8fa1362 2667
e107be36 2668 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
2669 if (mm)
2670 mmdrop(mm);
c394cc9f 2671 if (unlikely(prev_state == TASK_DEAD)) {
e6c390f2
DF
2672 if (prev->sched_class->task_dead)
2673 prev->sched_class->task_dead(prev);
2674
c6fd91f0 2675 /*
2676 * Remove function-return probe instances associated with this
2677 * task and put them back on the free list.
9761eea8 2678 */
c6fd91f0 2679 kprobe_flush_task(prev);
68f24b08
AL
2680
2681 /* Task is done with its stack. */
2682 put_task_stack(prev);
2683
1da177e4 2684 put_task_struct(prev);
c6fd91f0 2685 }
99e5ada9 2686
de734f89 2687 tick_nohz_task_switch();
dfa50b60 2688 return rq;
1da177e4
LT
2689}
2690
3f029d3c
GH
2691#ifdef CONFIG_SMP
2692
3f029d3c 2693/* rq->lock is NOT held, but preemption is disabled */
e3fca9e7 2694static void __balance_callback(struct rq *rq)
3f029d3c 2695{
e3fca9e7
PZ
2696 struct callback_head *head, *next;
2697 void (*func)(struct rq *rq);
2698 unsigned long flags;
3f029d3c 2699
e3fca9e7
PZ
2700 raw_spin_lock_irqsave(&rq->lock, flags);
2701 head = rq->balance_callback;
2702 rq->balance_callback = NULL;
2703 while (head) {
2704 func = (void (*)(struct rq *))head->func;
2705 next = head->next;
2706 head->next = NULL;
2707 head = next;
3f029d3c 2708
e3fca9e7 2709 func(rq);
3f029d3c 2710 }
e3fca9e7
PZ
2711 raw_spin_unlock_irqrestore(&rq->lock, flags);
2712}
2713
2714static inline void balance_callback(struct rq *rq)
2715{
2716 if (unlikely(rq->balance_callback))
2717 __balance_callback(rq);
3f029d3c
GH
2718}
2719
2720#else
da19ab51 2721
e3fca9e7 2722static inline void balance_callback(struct rq *rq)
3f029d3c 2723{
1da177e4
LT
2724}
2725
3f029d3c
GH
2726#endif
2727
1da177e4
LT
2728/**
2729 * schedule_tail - first thing a freshly forked thread must call.
2730 * @prev: the thread we just switched away from.
2731 */
722a9f92 2732asmlinkage __visible void schedule_tail(struct task_struct *prev)
1da177e4
LT
2733 __releases(rq->lock)
2734{
1a43a14a 2735 struct rq *rq;
da19ab51 2736
609ca066
PZ
2737 /*
2738 * New tasks start with FORK_PREEMPT_COUNT, see there and
2739 * finish_task_switch() for details.
2740 *
2741 * finish_task_switch() will drop rq->lock() and lower preempt_count
2742 * and the preempt_enable() will end up enabling preemption (on
2743 * PREEMPT_COUNT kernels).
2744 */
2745
dfa50b60 2746 rq = finish_task_switch(prev);
e3fca9e7 2747 balance_callback(rq);
1a43a14a 2748 preempt_enable();
70b97a7f 2749
1da177e4 2750 if (current->set_child_tid)
b488893a 2751 put_user(task_pid_vnr(current), current->set_child_tid);
1da177e4
LT
2752}
2753
2754/*
dfa50b60 2755 * context_switch - switch to the new MM and the new thread's register state.
1da177e4 2756 */
04936948 2757static __always_inline struct rq *
70b97a7f 2758context_switch(struct rq *rq, struct task_struct *prev,
d8ac8971 2759 struct task_struct *next, struct rq_flags *rf)
1da177e4 2760{
dd41f596 2761 struct mm_struct *mm, *oldmm;
1da177e4 2762
e107be36 2763 prepare_task_switch(rq, prev, next);
fe4b04fa 2764
dd41f596
IM
2765 mm = next->mm;
2766 oldmm = prev->active_mm;
9226d125
ZA
2767 /*
2768 * For paravirt, this is coupled with an exit in switch_to to
2769 * combine the page table reload and the switch backend into
2770 * one hypercall.
2771 */
224101ed 2772 arch_start_context_switch(prev);
9226d125 2773
31915ab4 2774 if (!mm) {
1da177e4 2775 next->active_mm = oldmm;
f1f10076 2776 mmgrab(oldmm);
1da177e4
LT
2777 enter_lazy_tlb(oldmm, next);
2778 } else
f98db601 2779 switch_mm_irqs_off(oldmm, mm, next);
1da177e4 2780
31915ab4 2781 if (!prev->mm) {
1da177e4 2782 prev->active_mm = NULL;
1da177e4
LT
2783 rq->prev_mm = oldmm;
2784 }
92509b73 2785
cb42c9a3 2786 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
92509b73 2787
3a5f5e48
IM
2788 /*
2789 * Since the runqueue lock will be released by the next
2790 * task (which is an invalid locking op but in the case
2791 * of the scheduler it's an obvious special-case), so we
2792 * do an early lockdep release here:
2793 */
d8ac8971 2794 rq_unpin_lock(rq, rf);
8a25d5de 2795 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1da177e4
LT
2796
2797 /* Here we just switch the register state and the stack. */
2798 switch_to(prev, next, prev);
dd41f596 2799 barrier();
dfa50b60
ON
2800
2801 return finish_task_switch(prev);
1da177e4
LT
2802}
2803
2804/*
1c3e8264 2805 * nr_running and nr_context_switches:
1da177e4
LT
2806 *
2807 * externally visible scheduler statistics: current number of runnable
1c3e8264 2808 * threads, total number of context switches performed since bootup.
1da177e4
LT
2809 */
2810unsigned long nr_running(void)
2811{
2812 unsigned long i, sum = 0;
2813
2814 for_each_online_cpu(i)
2815 sum += cpu_rq(i)->nr_running;
2816
2817 return sum;
f711f609 2818}
1da177e4 2819
2ee507c4 2820/*
d1ccc66d 2821 * Check if only the current task is running on the CPU.
00cc1633
DD
2822 *
2823 * Caution: this function does not check that the caller has disabled
2824 * preemption, thus the result might have a time-of-check-to-time-of-use
2825 * race. The caller is responsible to use it correctly, for example:
2826 *
2827 * - from a non-preemptable section (of course)
2828 *
2829 * - from a thread that is bound to a single CPU
2830 *
2831 * - in a loop with very short iterations (e.g. a polling loop)
2ee507c4
TC
2832 */
2833bool single_task_running(void)
2834{
00cc1633 2835 return raw_rq()->nr_running == 1;
2ee507c4
TC
2836}
2837EXPORT_SYMBOL(single_task_running);
2838
1da177e4 2839unsigned long long nr_context_switches(void)
46cb4b7c 2840{
cc94abfc
SR
2841 int i;
2842 unsigned long long sum = 0;
46cb4b7c 2843
0a945022 2844 for_each_possible_cpu(i)
1da177e4 2845 sum += cpu_rq(i)->nr_switches;
46cb4b7c 2846
1da177e4
LT
2847 return sum;
2848}
483b4ee6 2849
e33a9bba
TH
2850/*
2851 * IO-wait accounting, and how its mostly bollocks (on SMP).
2852 *
2853 * The idea behind IO-wait account is to account the idle time that we could
2854 * have spend running if it were not for IO. That is, if we were to improve the
2855 * storage performance, we'd have a proportional reduction in IO-wait time.
2856 *
2857 * This all works nicely on UP, where, when a task blocks on IO, we account
2858 * idle time as IO-wait, because if the storage were faster, it could've been
2859 * running and we'd not be idle.
2860 *
2861 * This has been extended to SMP, by doing the same for each CPU. This however
2862 * is broken.
2863 *
2864 * Imagine for instance the case where two tasks block on one CPU, only the one
2865 * CPU will have IO-wait accounted, while the other has regular idle. Even
2866 * though, if the storage were faster, both could've ran at the same time,
2867 * utilising both CPUs.
2868 *
2869 * This means, that when looking globally, the current IO-wait accounting on
2870 * SMP is a lower bound, by reason of under accounting.
2871 *
2872 * Worse, since the numbers are provided per CPU, they are sometimes
2873 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2874 * associated with any one particular CPU, it can wake to another CPU than it
2875 * blocked on. This means the per CPU IO-wait number is meaningless.
2876 *
2877 * Task CPU affinities can make all that even more 'interesting'.
2878 */
2879
1da177e4
LT
2880unsigned long nr_iowait(void)
2881{
2882 unsigned long i, sum = 0;
483b4ee6 2883
0a945022 2884 for_each_possible_cpu(i)
1da177e4 2885 sum += atomic_read(&cpu_rq(i)->nr_iowait);
46cb4b7c 2886
1da177e4
LT
2887 return sum;
2888}
483b4ee6 2889
e33a9bba
TH
2890/*
2891 * Consumers of these two interfaces, like for example the cpufreq menu
2892 * governor are using nonsensical data. Boosting frequency for a CPU that has
2893 * IO-wait which might not even end up running the task when it does become
2894 * runnable.
2895 */
2896
8c215bd3 2897unsigned long nr_iowait_cpu(int cpu)
69d25870 2898{
8c215bd3 2899 struct rq *this = cpu_rq(cpu);
69d25870
AV
2900 return atomic_read(&this->nr_iowait);
2901}
46cb4b7c 2902
372ba8cb
MG
2903void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2904{
3289bdb4
PZ
2905 struct rq *rq = this_rq();
2906 *nr_waiters = atomic_read(&rq->nr_iowait);
2907 *load = rq->load.weight;
372ba8cb
MG
2908}
2909
dd41f596 2910#ifdef CONFIG_SMP
8a0be9ef 2911
46cb4b7c 2912/*
38022906
PZ
2913 * sched_exec - execve() is a valuable balancing opportunity, because at
2914 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 2915 */
38022906 2916void sched_exec(void)
46cb4b7c 2917{
38022906 2918 struct task_struct *p = current;
1da177e4 2919 unsigned long flags;
0017d735 2920 int dest_cpu;
46cb4b7c 2921
8f42ced9 2922 raw_spin_lock_irqsave(&p->pi_lock, flags);
ac66f547 2923 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
0017d735
PZ
2924 if (dest_cpu == smp_processor_id())
2925 goto unlock;
38022906 2926
8f42ced9 2927 if (likely(cpu_active(dest_cpu))) {
969c7921 2928 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 2929
8f42ced9
PZ
2930 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2931 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
2932 return;
2933 }
0017d735 2934unlock:
8f42ced9 2935 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 2936}
dd41f596 2937
1da177e4
LT
2938#endif
2939
1da177e4 2940DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 2941DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
2942
2943EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 2944EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4 2945
6075620b
GG
2946/*
2947 * The function fair_sched_class.update_curr accesses the struct curr
2948 * and its field curr->exec_start; when called from task_sched_runtime(),
2949 * we observe a high rate of cache misses in practice.
2950 * Prefetching this data results in improved performance.
2951 */
2952static inline void prefetch_curr_exec_start(struct task_struct *p)
2953{
2954#ifdef CONFIG_FAIR_GROUP_SCHED
2955 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
2956#else
2957 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
2958#endif
2959 prefetch(curr);
2960 prefetch(&curr->exec_start);
2961}
2962
c5f8d995
HS
2963/*
2964 * Return accounted runtime for the task.
2965 * In case the task is currently running, return the runtime plus current's
2966 * pending runtime that have not been accounted yet.
2967 */
2968unsigned long long task_sched_runtime(struct task_struct *p)
2969{
eb580751 2970 struct rq_flags rf;
c5f8d995 2971 struct rq *rq;
6e998916 2972 u64 ns;
c5f8d995 2973
911b2898
PZ
2974#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2975 /*
2976 * 64-bit doesn't need locks to atomically read a 64bit value.
2977 * So we have a optimization chance when the task's delta_exec is 0.
2978 * Reading ->on_cpu is racy, but this is ok.
2979 *
d1ccc66d
IM
2980 * If we race with it leaving CPU, we'll take a lock. So we're correct.
2981 * If we race with it entering CPU, unaccounted time is 0. This is
911b2898 2982 * indistinguishable from the read occurring a few cycles earlier.
4036ac15
MG
2983 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2984 * been accounted, so we're correct here as well.
911b2898 2985 */
da0c1e65 2986 if (!p->on_cpu || !task_on_rq_queued(p))
911b2898
PZ
2987 return p->se.sum_exec_runtime;
2988#endif
2989
eb580751 2990 rq = task_rq_lock(p, &rf);
6e998916
SG
2991 /*
2992 * Must be ->curr _and_ ->on_rq. If dequeued, we would
2993 * project cycles that may never be accounted to this
2994 * thread, breaking clock_gettime().
2995 */
2996 if (task_current(rq, p) && task_on_rq_queued(p)) {
6075620b 2997 prefetch_curr_exec_start(p);
6e998916
SG
2998 update_rq_clock(rq);
2999 p->sched_class->update_curr(rq);
3000 }
3001 ns = p->se.sum_exec_runtime;
eb580751 3002 task_rq_unlock(rq, p, &rf);
c5f8d995
HS
3003
3004 return ns;
3005}
48f24c4d 3006
7835b98b
CL
3007/*
3008 * This function gets called by the timer code, with HZ frequency.
3009 * We call it with interrupts disabled.
7835b98b
CL
3010 */
3011void scheduler_tick(void)
3012{
7835b98b
CL
3013 int cpu = smp_processor_id();
3014 struct rq *rq = cpu_rq(cpu);
dd41f596 3015 struct task_struct *curr = rq->curr;
8a8c69c3 3016 struct rq_flags rf;
3e51f33f
PZ
3017
3018 sched_clock_tick();
dd41f596 3019
8a8c69c3
PZ
3020 rq_lock(rq, &rf);
3021
3e51f33f 3022 update_rq_clock(rq);
fa85ae24 3023 curr->sched_class->task_tick(rq, curr, 0);
cee1afce 3024 cpu_load_update_active(rq);
3289bdb4 3025 calc_global_load_tick(rq);
8a8c69c3
PZ
3026
3027 rq_unlock(rq, &rf);
7835b98b 3028
e9d2b064 3029 perf_event_task_tick();
e220d2dc 3030
e418e1c2 3031#ifdef CONFIG_SMP
6eb57e0d 3032 rq->idle_balance = idle_cpu(cpu);
7caff66f 3033 trigger_load_balance(rq);
e418e1c2 3034#endif
265f22a9 3035 rq_last_tick_reset(rq);
1da177e4
LT
3036}
3037
265f22a9
FW
3038#ifdef CONFIG_NO_HZ_FULL
3039/**
3040 * scheduler_tick_max_deferment
3041 *
3042 * Keep at least one tick per second when a single
3043 * active task is running because the scheduler doesn't
3044 * yet completely support full dynticks environment.
3045 *
3046 * This makes sure that uptime, CFS vruntime, load
3047 * balancing, etc... continue to move forward, even
3048 * with a very low granularity.
e69f6186
YB
3049 *
3050 * Return: Maximum deferment in nanoseconds.
265f22a9
FW
3051 */
3052u64 scheduler_tick_max_deferment(void)
3053{
3054 struct rq *rq = this_rq();
316c1608 3055 unsigned long next, now = READ_ONCE(jiffies);
265f22a9
FW
3056
3057 next = rq->last_sched_tick + HZ;
3058
3059 if (time_before_eq(next, now))
3060 return 0;
3061
8fe8ff09 3062 return jiffies_to_nsecs(next - now);
1da177e4 3063}
265f22a9 3064#endif
1da177e4 3065
7e49fcce
SR
3066#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3067 defined(CONFIG_PREEMPT_TRACER))
47252cfb
SR
3068/*
3069 * If the value passed in is equal to the current preempt count
3070 * then we just disabled preemption. Start timing the latency.
3071 */
3072static inline void preempt_latency_start(int val)
3073{
3074 if (preempt_count() == val) {
3075 unsigned long ip = get_lock_parent_ip();
3076#ifdef CONFIG_DEBUG_PREEMPT
3077 current->preempt_disable_ip = ip;
3078#endif
3079 trace_preempt_off(CALLER_ADDR0, ip);
3080 }
3081}
7e49fcce 3082
edafe3a5 3083void preempt_count_add(int val)
1da177e4 3084{
6cd8a4bb 3085#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3086 /*
3087 * Underflow?
3088 */
9a11b49a
IM
3089 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3090 return;
6cd8a4bb 3091#endif
bdb43806 3092 __preempt_count_add(val);
6cd8a4bb 3093#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3094 /*
3095 * Spinlock count overflowing soon?
3096 */
33859f7f
MOS
3097 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3098 PREEMPT_MASK - 10);
6cd8a4bb 3099#endif
47252cfb 3100 preempt_latency_start(val);
1da177e4 3101}
bdb43806 3102EXPORT_SYMBOL(preempt_count_add);
edafe3a5 3103NOKPROBE_SYMBOL(preempt_count_add);
1da177e4 3104
47252cfb
SR
3105/*
3106 * If the value passed in equals to the current preempt count
3107 * then we just enabled preemption. Stop timing the latency.
3108 */
3109static inline void preempt_latency_stop(int val)
3110{
3111 if (preempt_count() == val)
3112 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3113}
3114
edafe3a5 3115void preempt_count_sub(int val)
1da177e4 3116{
6cd8a4bb 3117#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3118 /*
3119 * Underflow?
3120 */
01e3eb82 3121 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 3122 return;
1da177e4
LT
3123 /*
3124 * Is the spinlock portion underflowing?
3125 */
9a11b49a
IM
3126 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3127 !(preempt_count() & PREEMPT_MASK)))
3128 return;
6cd8a4bb 3129#endif
9a11b49a 3130
47252cfb 3131 preempt_latency_stop(val);
bdb43806 3132 __preempt_count_sub(val);
1da177e4 3133}
bdb43806 3134EXPORT_SYMBOL(preempt_count_sub);
edafe3a5 3135NOKPROBE_SYMBOL(preempt_count_sub);
1da177e4 3136
47252cfb
SR
3137#else
3138static inline void preempt_latency_start(int val) { }
3139static inline void preempt_latency_stop(int val) { }
1da177e4
LT
3140#endif
3141
59ddbcb2
IM
3142static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3143{
3144#ifdef CONFIG_DEBUG_PREEMPT
3145 return p->preempt_disable_ip;
3146#else
3147 return 0;
3148#endif
3149}
3150
1da177e4 3151/*
dd41f596 3152 * Print scheduling while atomic bug:
1da177e4 3153 */
dd41f596 3154static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 3155{
d1c6d149
VN
3156 /* Save this before calling printk(), since that will clobber it */
3157 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3158
664dfa65
DJ
3159 if (oops_in_progress)
3160 return;
3161
3df0fc5b
PZ
3162 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3163 prev->comm, prev->pid, preempt_count());
838225b4 3164
dd41f596 3165 debug_show_held_locks(prev);
e21f5b15 3166 print_modules();
dd41f596
IM
3167 if (irqs_disabled())
3168 print_irqtrace_events(prev);
d1c6d149
VN
3169 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3170 && in_atomic_preempt_off()) {
8f47b187 3171 pr_err("Preemption disabled at:");
d1c6d149 3172 print_ip_sym(preempt_disable_ip);
8f47b187
TG
3173 pr_cont("\n");
3174 }
748c7201
DBO
3175 if (panic_on_warn)
3176 panic("scheduling while atomic\n");
3177
6135fc1e 3178 dump_stack();
373d4d09 3179 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
dd41f596 3180}
1da177e4 3181
dd41f596
IM
3182/*
3183 * Various schedule()-time debugging checks and statistics:
3184 */
3185static inline void schedule_debug(struct task_struct *prev)
3186{
0d9e2632 3187#ifdef CONFIG_SCHED_STACK_END_CHECK
29d64551
JH
3188 if (task_stack_end_corrupted(prev))
3189 panic("corrupted stack end detected inside scheduler\n");
0d9e2632 3190#endif
b99def8b 3191
1dc0fffc 3192 if (unlikely(in_atomic_preempt_off())) {
dd41f596 3193 __schedule_bug(prev);
1dc0fffc
PZ
3194 preempt_count_set(PREEMPT_DISABLED);
3195 }
b3fbab05 3196 rcu_sleep_check();
dd41f596 3197
1da177e4
LT
3198 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3199
ae92882e 3200 schedstat_inc(this_rq()->sched_count);
dd41f596
IM
3201}
3202
3203/*
3204 * Pick up the highest-prio task:
3205 */
3206static inline struct task_struct *
d8ac8971 3207pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
dd41f596 3208{
49ee5768 3209 const struct sched_class *class;
dd41f596 3210 struct task_struct *p;
1da177e4
LT
3211
3212 /*
0ba87bb2
PZ
3213 * Optimization: we know that if all tasks are in the fair class we can
3214 * call that function directly, but only if the @prev task wasn't of a
3215 * higher scheduling class, because otherwise those loose the
3216 * opportunity to pull in more work from other CPUs.
1da177e4 3217 */
0ba87bb2
PZ
3218 if (likely((prev->sched_class == &idle_sched_class ||
3219 prev->sched_class == &fair_sched_class) &&
3220 rq->nr_running == rq->cfs.h_nr_running)) {
3221
d8ac8971 3222 p = fair_sched_class.pick_next_task(rq, prev, rf);
6ccdc84b
PZ
3223 if (unlikely(p == RETRY_TASK))
3224 goto again;
3225
d1ccc66d 3226 /* Assumes fair_sched_class->next == idle_sched_class */
6ccdc84b 3227 if (unlikely(!p))
d8ac8971 3228 p = idle_sched_class.pick_next_task(rq, prev, rf);
6ccdc84b
PZ
3229
3230 return p;
1da177e4
LT
3231 }
3232
37e117c0 3233again:
34f971f6 3234 for_each_class(class) {
d8ac8971 3235 p = class->pick_next_task(rq, prev, rf);
37e117c0
PZ
3236 if (p) {
3237 if (unlikely(p == RETRY_TASK))
3238 goto again;
dd41f596 3239 return p;
37e117c0 3240 }
dd41f596 3241 }
34f971f6 3242
d1ccc66d
IM
3243 /* The idle class should always have a runnable task: */
3244 BUG();
dd41f596 3245}
1da177e4 3246
dd41f596 3247/*
c259e01a 3248 * __schedule() is the main scheduler function.
edde96ea
PE
3249 *
3250 * The main means of driving the scheduler and thus entering this function are:
3251 *
3252 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3253 *
3254 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3255 * paths. For example, see arch/x86/entry_64.S.
3256 *
3257 * To drive preemption between tasks, the scheduler sets the flag in timer
3258 * interrupt handler scheduler_tick().
3259 *
3260 * 3. Wakeups don't really cause entry into schedule(). They add a
3261 * task to the run-queue and that's it.
3262 *
3263 * Now, if the new task added to the run-queue preempts the current
3264 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3265 * called on the nearest possible occasion:
3266 *
3267 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3268 *
3269 * - in syscall or exception context, at the next outmost
3270 * preempt_enable(). (this might be as soon as the wake_up()'s
3271 * spin_unlock()!)
3272 *
3273 * - in IRQ context, return from interrupt-handler to
3274 * preemptible context
3275 *
3276 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3277 * then at the next:
3278 *
3279 * - cond_resched() call
3280 * - explicit schedule() call
3281 * - return from syscall or exception to user-space
3282 * - return from interrupt-handler to user-space
bfd9b2b5 3283 *
b30f0e3f 3284 * WARNING: must be called with preemption disabled!
dd41f596 3285 */
499d7955 3286static void __sched notrace __schedule(bool preempt)
dd41f596
IM
3287{
3288 struct task_struct *prev, *next;
67ca7bde 3289 unsigned long *switch_count;
d8ac8971 3290 struct rq_flags rf;
dd41f596 3291 struct rq *rq;
31656519 3292 int cpu;
dd41f596 3293
dd41f596
IM
3294 cpu = smp_processor_id();
3295 rq = cpu_rq(cpu);
dd41f596 3296 prev = rq->curr;
dd41f596 3297
dd41f596 3298 schedule_debug(prev);
1da177e4 3299
31656519 3300 if (sched_feat(HRTICK))
f333fdc9 3301 hrtick_clear(rq);
8f4d37ec 3302
46a5d164 3303 local_irq_disable();
bcbfdd01 3304 rcu_note_context_switch(preempt);
46a5d164 3305
e0acd0a6
ON
3306 /*
3307 * Make sure that signal_pending_state()->signal_pending() below
3308 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3309 * done by the caller to avoid the race with signal_wake_up().
3310 */
8a8c69c3 3311 rq_lock(rq, &rf);
d89e588c 3312 smp_mb__after_spinlock();
1da177e4 3313
d1ccc66d
IM
3314 /* Promote REQ to ACT */
3315 rq->clock_update_flags <<= 1;
bce4dc80 3316 update_rq_clock(rq);
9edfbfed 3317
246d86b5 3318 switch_count = &prev->nivcsw;
fc13aeba 3319 if (!preempt && prev->state) {
21aa9af0 3320 if (unlikely(signal_pending_state(prev->state, prev))) {
1da177e4 3321 prev->state = TASK_RUNNING;
21aa9af0 3322 } else {
bce4dc80 3323 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
2acca55e
PZ
3324 prev->on_rq = 0;
3325
e33a9bba
TH
3326 if (prev->in_iowait) {
3327 atomic_inc(&rq->nr_iowait);
3328 delayacct_blkio_start();
3329 }
3330
21aa9af0 3331 /*
2acca55e
PZ
3332 * If a worker went to sleep, notify and ask workqueue
3333 * whether it wants to wake up a task to maintain
3334 * concurrency.
21aa9af0
TH
3335 */
3336 if (prev->flags & PF_WQ_WORKER) {
3337 struct task_struct *to_wakeup;
3338
9b7f6597 3339 to_wakeup = wq_worker_sleeping(prev);
21aa9af0 3340 if (to_wakeup)
d8ac8971 3341 try_to_wake_up_local(to_wakeup, &rf);
21aa9af0 3342 }
21aa9af0 3343 }
dd41f596 3344 switch_count = &prev->nvcsw;
1da177e4
LT
3345 }
3346
d8ac8971 3347 next = pick_next_task(rq, prev, &rf);
f26f9aff 3348 clear_tsk_need_resched(prev);
f27dde8d 3349 clear_preempt_need_resched();
1da177e4 3350
1da177e4 3351 if (likely(prev != next)) {
1da177e4
LT
3352 rq->nr_switches++;
3353 rq->curr = next;
22e4ebb9
MD
3354 /*
3355 * The membarrier system call requires each architecture
3356 * to have a full memory barrier after updating
3357 * rq->curr, before returning to user-space. For TSO
3358 * (e.g. x86), the architecture must provide its own
3359 * barrier in switch_mm(). For weakly ordered machines
3360 * for which spin_unlock() acts as a full memory
3361 * barrier, finish_lock_switch() in common code takes
3362 * care of this barrier. For weakly ordered machines for
3363 * which spin_unlock() acts as a RELEASE barrier (only
3364 * arm64 and PowerPC), arm64 has a full barrier in
3365 * switch_to(), and PowerPC has
3366 * smp_mb__after_unlock_lock() before
3367 * finish_lock_switch().
3368 */
1da177e4
LT
3369 ++*switch_count;
3370
c73464b1 3371 trace_sched_switch(preempt, prev, next);
d1ccc66d
IM
3372
3373 /* Also unlocks the rq: */
3374 rq = context_switch(rq, prev, next, &rf);
cbce1a68 3375 } else {
cb42c9a3 3376 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
8a8c69c3 3377 rq_unlock_irq(rq, &rf);
cbce1a68 3378 }
1da177e4 3379
e3fca9e7 3380 balance_callback(rq);
1da177e4 3381}
c259e01a 3382
9af6528e
PZ
3383void __noreturn do_task_dead(void)
3384{
3385 /*
3386 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3387 * when the following two conditions become true.
3388 * - There is race condition of mmap_sem (It is acquired by
3389 * exit_mm()), and
3390 * - SMI occurs before setting TASK_RUNINNG.
3391 * (or hypervisor of virtual machine switches to other guest)
3392 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3393 *
3394 * To avoid it, we have to wait for releasing tsk->pi_lock which
3395 * is held by try_to_wake_up()
3396 */
23a9b748
PM
3397 raw_spin_lock_irq(&current->pi_lock);
3398 raw_spin_unlock_irq(&current->pi_lock);
9af6528e 3399
d1ccc66d 3400 /* Causes final put_task_struct in finish_task_switch(): */
9af6528e 3401 __set_current_state(TASK_DEAD);
d1ccc66d
IM
3402
3403 /* Tell freezer to ignore us: */
3404 current->flags |= PF_NOFREEZE;
3405
9af6528e
PZ
3406 __schedule(false);
3407 BUG();
d1ccc66d
IM
3408
3409 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
9af6528e 3410 for (;;)
d1ccc66d 3411 cpu_relax();
9af6528e
PZ
3412}
3413
9c40cef2
TG
3414static inline void sched_submit_work(struct task_struct *tsk)
3415{
3c7d5184 3416 if (!tsk->state || tsk_is_pi_blocked(tsk))
9c40cef2
TG
3417 return;
3418 /*
3419 * If we are going to sleep and we have plugged IO queued,
3420 * make sure to submit it to avoid deadlocks.
3421 */
3422 if (blk_needs_flush_plug(tsk))
3423 blk_schedule_flush_plug(tsk);
3424}
3425
722a9f92 3426asmlinkage __visible void __sched schedule(void)
c259e01a 3427{
9c40cef2
TG
3428 struct task_struct *tsk = current;
3429
3430 sched_submit_work(tsk);
bfd9b2b5 3431 do {
b30f0e3f 3432 preempt_disable();
fc13aeba 3433 __schedule(false);
b30f0e3f 3434 sched_preempt_enable_no_resched();
bfd9b2b5 3435 } while (need_resched());
c259e01a 3436}
1da177e4
LT
3437EXPORT_SYMBOL(schedule);
3438
8663effb
SRV
3439/*
3440 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3441 * state (have scheduled out non-voluntarily) by making sure that all
3442 * tasks have either left the run queue or have gone into user space.
3443 * As idle tasks do not do either, they must not ever be preempted
3444 * (schedule out non-voluntarily).
3445 *
3446 * schedule_idle() is similar to schedule_preempt_disable() except that it
3447 * never enables preemption because it does not call sched_submit_work().
3448 */
3449void __sched schedule_idle(void)
3450{
3451 /*
3452 * As this skips calling sched_submit_work(), which the idle task does
3453 * regardless because that function is a nop when the task is in a
3454 * TASK_RUNNING state, make sure this isn't used someplace that the
3455 * current task can be in any other state. Note, idle is always in the
3456 * TASK_RUNNING state.
3457 */
3458 WARN_ON_ONCE(current->state);
3459 do {
3460 __schedule(false);
3461 } while (need_resched());
3462}
3463
91d1aa43 3464#ifdef CONFIG_CONTEXT_TRACKING
722a9f92 3465asmlinkage __visible void __sched schedule_user(void)
20ab65e3
FW
3466{
3467 /*
3468 * If we come here after a random call to set_need_resched(),
3469 * or we have been woken up remotely but the IPI has not yet arrived,
3470 * we haven't yet exited the RCU idle mode. Do it here manually until
3471 * we find a better solution.
7cc78f8f
AL
3472 *
3473 * NB: There are buggy callers of this function. Ideally we
c467ea76 3474 * should warn if prev_state != CONTEXT_USER, but that will trigger
7cc78f8f 3475 * too frequently to make sense yet.
20ab65e3 3476 */
7cc78f8f 3477 enum ctx_state prev_state = exception_enter();
20ab65e3 3478 schedule();
7cc78f8f 3479 exception_exit(prev_state);
20ab65e3
FW
3480}
3481#endif
3482
c5491ea7
TG
3483/**
3484 * schedule_preempt_disabled - called with preemption disabled
3485 *
3486 * Returns with preemption disabled. Note: preempt_count must be 1
3487 */
3488void __sched schedule_preempt_disabled(void)
3489{
ba74c144 3490 sched_preempt_enable_no_resched();
c5491ea7
TG
3491 schedule();
3492 preempt_disable();
3493}
3494
06b1f808 3495static void __sched notrace preempt_schedule_common(void)
a18b5d01
FW
3496{
3497 do {
47252cfb
SR
3498 /*
3499 * Because the function tracer can trace preempt_count_sub()
3500 * and it also uses preempt_enable/disable_notrace(), if
3501 * NEED_RESCHED is set, the preempt_enable_notrace() called
3502 * by the function tracer will call this function again and
3503 * cause infinite recursion.
3504 *
3505 * Preemption must be disabled here before the function
3506 * tracer can trace. Break up preempt_disable() into two
3507 * calls. One to disable preemption without fear of being
3508 * traced. The other to still record the preemption latency,
3509 * which can also be traced by the function tracer.
3510 */
499d7955 3511 preempt_disable_notrace();
47252cfb 3512 preempt_latency_start(1);
fc13aeba 3513 __schedule(true);
47252cfb 3514 preempt_latency_stop(1);
499d7955 3515 preempt_enable_no_resched_notrace();
a18b5d01
FW
3516
3517 /*
3518 * Check again in case we missed a preemption opportunity
3519 * between schedule and now.
3520 */
a18b5d01
FW
3521 } while (need_resched());
3522}
3523
1da177e4
LT
3524#ifdef CONFIG_PREEMPT
3525/*
2ed6e34f 3526 * this is the entry point to schedule() from in-kernel preemption
41a2d6cf 3527 * off of preempt_enable. Kernel preemptions off return from interrupt
1da177e4
LT
3528 * occur there and call schedule directly.
3529 */
722a9f92 3530asmlinkage __visible void __sched notrace preempt_schedule(void)
1da177e4 3531{
1da177e4
LT
3532 /*
3533 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 3534 * we do not want to preempt the current task. Just return..
1da177e4 3535 */
fbb00b56 3536 if (likely(!preemptible()))
1da177e4
LT
3537 return;
3538
a18b5d01 3539 preempt_schedule_common();
1da177e4 3540}
376e2424 3541NOKPROBE_SYMBOL(preempt_schedule);
1da177e4 3542EXPORT_SYMBOL(preempt_schedule);
009f60e2 3543
009f60e2 3544/**
4eaca0a8 3545 * preempt_schedule_notrace - preempt_schedule called by tracing
009f60e2
ON
3546 *
3547 * The tracing infrastructure uses preempt_enable_notrace to prevent
3548 * recursion and tracing preempt enabling caused by the tracing
3549 * infrastructure itself. But as tracing can happen in areas coming
3550 * from userspace or just about to enter userspace, a preempt enable
3551 * can occur before user_exit() is called. This will cause the scheduler
3552 * to be called when the system is still in usermode.
3553 *
3554 * To prevent this, the preempt_enable_notrace will use this function
3555 * instead of preempt_schedule() to exit user context if needed before
3556 * calling the scheduler.
3557 */
4eaca0a8 3558asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
009f60e2
ON
3559{
3560 enum ctx_state prev_ctx;
3561
3562 if (likely(!preemptible()))
3563 return;
3564
3565 do {
47252cfb
SR
3566 /*
3567 * Because the function tracer can trace preempt_count_sub()
3568 * and it also uses preempt_enable/disable_notrace(), if
3569 * NEED_RESCHED is set, the preempt_enable_notrace() called
3570 * by the function tracer will call this function again and
3571 * cause infinite recursion.
3572 *
3573 * Preemption must be disabled here before the function
3574 * tracer can trace. Break up preempt_disable() into two
3575 * calls. One to disable preemption without fear of being
3576 * traced. The other to still record the preemption latency,
3577 * which can also be traced by the function tracer.
3578 */
3d8f74dd 3579 preempt_disable_notrace();
47252cfb 3580 preempt_latency_start(1);
009f60e2
ON
3581 /*
3582 * Needs preempt disabled in case user_exit() is traced
3583 * and the tracer calls preempt_enable_notrace() causing
3584 * an infinite recursion.
3585 */
3586 prev_ctx = exception_enter();
fc13aeba 3587 __schedule(true);
009f60e2
ON
3588 exception_exit(prev_ctx);
3589
47252cfb 3590 preempt_latency_stop(1);
3d8f74dd 3591 preempt_enable_no_resched_notrace();
009f60e2
ON
3592 } while (need_resched());
3593}
4eaca0a8 3594EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
009f60e2 3595
32e475d7 3596#endif /* CONFIG_PREEMPT */
1da177e4
LT
3597
3598/*
2ed6e34f 3599 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3600 * off of irq context.
3601 * Note, that this is called and return with irqs disabled. This will
3602 * protect us against recursive calling from irq.
3603 */
722a9f92 3604asmlinkage __visible void __sched preempt_schedule_irq(void)
1da177e4 3605{
b22366cd 3606 enum ctx_state prev_state;
6478d880 3607
2ed6e34f 3608 /* Catch callers which need to be fixed */
f27dde8d 3609 BUG_ON(preempt_count() || !irqs_disabled());
1da177e4 3610
b22366cd
FW
3611 prev_state = exception_enter();
3612
3a5c359a 3613 do {
3d8f74dd 3614 preempt_disable();
3a5c359a 3615 local_irq_enable();
fc13aeba 3616 __schedule(true);
3a5c359a 3617 local_irq_disable();
3d8f74dd 3618 sched_preempt_enable_no_resched();
5ed0cec0 3619 } while (need_resched());
b22366cd
FW
3620
3621 exception_exit(prev_state);
1da177e4
LT
3622}
3623
ac6424b9 3624int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
95cdf3b7 3625 void *key)
1da177e4 3626{
63859d4f 3627 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 3628}
1da177e4
LT
3629EXPORT_SYMBOL(default_wake_function);
3630
b29739f9
IM
3631#ifdef CONFIG_RT_MUTEXES
3632
acd58620
PZ
3633static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3634{
3635 if (pi_task)
3636 prio = min(prio, pi_task->prio);
3637
3638 return prio;
3639}
3640
3641static inline int rt_effective_prio(struct task_struct *p, int prio)
3642{
3643 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3644
3645 return __rt_effective_prio(pi_task, prio);
3646}
3647
b29739f9
IM
3648/*
3649 * rt_mutex_setprio - set the current priority of a task
acd58620
PZ
3650 * @p: task to boost
3651 * @pi_task: donor task
b29739f9
IM
3652 *
3653 * This function changes the 'effective' priority of a task. It does
3654 * not touch ->normal_prio like __setscheduler().
3655 *
c365c292
TG
3656 * Used by the rt_mutex code to implement priority inheritance
3657 * logic. Call site only calls if the priority of the task changed.
b29739f9 3658 */
acd58620 3659void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
b29739f9 3660{
acd58620 3661 int prio, oldprio, queued, running, queue_flag =
7a57f32a 3662 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
83ab0aa0 3663 const struct sched_class *prev_class;
eb580751
PZ
3664 struct rq_flags rf;
3665 struct rq *rq;
b29739f9 3666
acd58620
PZ
3667 /* XXX used to be waiter->prio, not waiter->task->prio */
3668 prio = __rt_effective_prio(pi_task, p->normal_prio);
3669
3670 /*
3671 * If nothing changed; bail early.
3672 */
3673 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3674 return;
b29739f9 3675
eb580751 3676 rq = __task_rq_lock(p, &rf);
80f5c1b8 3677 update_rq_clock(rq);
acd58620
PZ
3678 /*
3679 * Set under pi_lock && rq->lock, such that the value can be used under
3680 * either lock.
3681 *
3682 * Note that there is loads of tricky to make this pointer cache work
3683 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3684 * ensure a task is de-boosted (pi_task is set to NULL) before the
3685 * task is allowed to run again (and can exit). This ensures the pointer
3686 * points to a blocked task -- which guaratees the task is present.
3687 */
3688 p->pi_top_task = pi_task;
3689
3690 /*
3691 * For FIFO/RR we only need to set prio, if that matches we're done.
3692 */
3693 if (prio == p->prio && !dl_prio(prio))
3694 goto out_unlock;
b29739f9 3695
1c4dd99b
TG
3696 /*
3697 * Idle task boosting is a nono in general. There is one
3698 * exception, when PREEMPT_RT and NOHZ is active:
3699 *
3700 * The idle task calls get_next_timer_interrupt() and holds
3701 * the timer wheel base->lock on the CPU and another CPU wants
3702 * to access the timer (probably to cancel it). We can safely
3703 * ignore the boosting request, as the idle CPU runs this code
3704 * with interrupts disabled and will complete the lock
3705 * protected section without being interrupted. So there is no
3706 * real need to boost.
3707 */
3708 if (unlikely(p == rq->idle)) {
3709 WARN_ON(p != rq->curr);
3710 WARN_ON(p->pi_blocked_on);
3711 goto out_unlock;
3712 }
3713
b91473ff 3714 trace_sched_pi_setprio(p, pi_task);
d5f9f942 3715 oldprio = p->prio;
ff77e468
PZ
3716
3717 if (oldprio == prio)
3718 queue_flag &= ~DEQUEUE_MOVE;
3719
83ab0aa0 3720 prev_class = p->sched_class;
da0c1e65 3721 queued = task_on_rq_queued(p);
051a1d1a 3722 running = task_current(rq, p);
da0c1e65 3723 if (queued)
ff77e468 3724 dequeue_task(rq, p, queue_flag);
0e1f3483 3725 if (running)
f3cd1c4e 3726 put_prev_task(rq, p);
dd41f596 3727
2d3d891d
DF
3728 /*
3729 * Boosting condition are:
3730 * 1. -rt task is running and holds mutex A
3731 * --> -dl task blocks on mutex A
3732 *
3733 * 2. -dl task is running and holds mutex A
3734 * --> -dl task blocks on mutex A and could preempt the
3735 * running task
3736 */
3737 if (dl_prio(prio)) {
466af29b
ON
3738 if (!dl_prio(p->normal_prio) ||
3739 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
2d3d891d 3740 p->dl.dl_boosted = 1;
ff77e468 3741 queue_flag |= ENQUEUE_REPLENISH;
2d3d891d
DF
3742 } else
3743 p->dl.dl_boosted = 0;
aab03e05 3744 p->sched_class = &dl_sched_class;
2d3d891d
DF
3745 } else if (rt_prio(prio)) {
3746 if (dl_prio(oldprio))
3747 p->dl.dl_boosted = 0;
3748 if (oldprio < prio)
ff77e468 3749 queue_flag |= ENQUEUE_HEAD;
dd41f596 3750 p->sched_class = &rt_sched_class;
2d3d891d
DF
3751 } else {
3752 if (dl_prio(oldprio))
3753 p->dl.dl_boosted = 0;
746db944
BS
3754 if (rt_prio(oldprio))
3755 p->rt.timeout = 0;
dd41f596 3756 p->sched_class = &fair_sched_class;
2d3d891d 3757 }
dd41f596 3758
b29739f9
IM
3759 p->prio = prio;
3760
da0c1e65 3761 if (queued)
ff77e468 3762 enqueue_task(rq, p, queue_flag);
a399d233 3763 if (running)
b2bf6c31 3764 set_curr_task(rq, p);
cb469845 3765
da7a735e 3766 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 3767out_unlock:
d1ccc66d
IM
3768 /* Avoid rq from going away on us: */
3769 preempt_disable();
eb580751 3770 __task_rq_unlock(rq, &rf);
4c9a4bc8
PZ
3771
3772 balance_callback(rq);
3773 preempt_enable();
b29739f9 3774}
acd58620
PZ
3775#else
3776static inline int rt_effective_prio(struct task_struct *p, int prio)
3777{
3778 return prio;
3779}
b29739f9 3780#endif
d50dde5a 3781
36c8b586 3782void set_user_nice(struct task_struct *p, long nice)
1da177e4 3783{
49bd21ef
PZ
3784 bool queued, running;
3785 int old_prio, delta;
eb580751 3786 struct rq_flags rf;
70b97a7f 3787 struct rq *rq;
1da177e4 3788
75e45d51 3789 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
1da177e4
LT
3790 return;
3791 /*
3792 * We have to be careful, if called from sys_setpriority(),
3793 * the task might be in the middle of scheduling on another CPU.
3794 */
eb580751 3795 rq = task_rq_lock(p, &rf);
2fb8d367
PZ
3796 update_rq_clock(rq);
3797
1da177e4
LT
3798 /*
3799 * The RT priorities are set via sched_setscheduler(), but we still
3800 * allow the 'normal' nice value to be set - but as expected
3801 * it wont have any effect on scheduling until the task is
aab03e05 3802 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
1da177e4 3803 */
aab03e05 3804 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
1da177e4
LT
3805 p->static_prio = NICE_TO_PRIO(nice);
3806 goto out_unlock;
3807 }
da0c1e65 3808 queued = task_on_rq_queued(p);
49bd21ef 3809 running = task_current(rq, p);
da0c1e65 3810 if (queued)
7a57f32a 3811 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
49bd21ef
PZ
3812 if (running)
3813 put_prev_task(rq, p);
1da177e4 3814
1da177e4 3815 p->static_prio = NICE_TO_PRIO(nice);
9059393e 3816 set_load_weight(p, true);
b29739f9
IM
3817 old_prio = p->prio;
3818 p->prio = effective_prio(p);
3819 delta = p->prio - old_prio;
1da177e4 3820
da0c1e65 3821 if (queued) {
7134b3e9 3822 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1da177e4 3823 /*
d5f9f942
AM
3824 * If the task increased its priority or is running and
3825 * lowered its priority, then reschedule its CPU:
1da177e4 3826 */
d5f9f942 3827 if (delta < 0 || (delta > 0 && task_running(rq, p)))
8875125e 3828 resched_curr(rq);
1da177e4 3829 }
49bd21ef
PZ
3830 if (running)
3831 set_curr_task(rq, p);
1da177e4 3832out_unlock:
eb580751 3833 task_rq_unlock(rq, p, &rf);
1da177e4 3834}
1da177e4
LT
3835EXPORT_SYMBOL(set_user_nice);
3836
e43379f1
MM
3837/*
3838 * can_nice - check if a task can reduce its nice value
3839 * @p: task
3840 * @nice: nice value
3841 */
36c8b586 3842int can_nice(const struct task_struct *p, const int nice)
e43379f1 3843{
d1ccc66d 3844 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
7aa2c016 3845 int nice_rlim = nice_to_rlimit(nice);
48f24c4d 3846
78d7d407 3847 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
3848 capable(CAP_SYS_NICE));
3849}
3850
1da177e4
LT
3851#ifdef __ARCH_WANT_SYS_NICE
3852
3853/*
3854 * sys_nice - change the priority of the current process.
3855 * @increment: priority increment
3856 *
3857 * sys_setpriority is a more generic, but much slower function that
3858 * does similar things.
3859 */
5add95d4 3860SYSCALL_DEFINE1(nice, int, increment)
1da177e4 3861{
48f24c4d 3862 long nice, retval;
1da177e4
LT
3863
3864 /*
3865 * Setpriority might change our priority at the same moment.
3866 * We don't have to worry. Conceptually one call occurs first
3867 * and we have a single winner.
3868 */
a9467fa3 3869 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
d0ea0268 3870 nice = task_nice(current) + increment;
1da177e4 3871
a9467fa3 3872 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
e43379f1
MM
3873 if (increment < 0 && !can_nice(current, nice))
3874 return -EPERM;
3875
1da177e4
LT
3876 retval = security_task_setnice(current, nice);
3877 if (retval)
3878 return retval;
3879
3880 set_user_nice(current, nice);
3881 return 0;
3882}
3883
3884#endif
3885
3886/**
3887 * task_prio - return the priority value of a given task.
3888 * @p: the task in question.
3889 *
e69f6186 3890 * Return: The priority value as seen by users in /proc.
1da177e4
LT
3891 * RT tasks are offset by -200. Normal tasks are centered
3892 * around 0, value goes from -16 to +15.
3893 */
36c8b586 3894int task_prio(const struct task_struct *p)
1da177e4
LT
3895{
3896 return p->prio - MAX_RT_PRIO;
3897}
3898
1da177e4 3899/**
d1ccc66d 3900 * idle_cpu - is a given CPU idle currently?
1da177e4 3901 * @cpu: the processor in question.
e69f6186
YB
3902 *
3903 * Return: 1 if the CPU is currently idle. 0 otherwise.
1da177e4
LT
3904 */
3905int idle_cpu(int cpu)
3906{
908a3283
TG
3907 struct rq *rq = cpu_rq(cpu);
3908
3909 if (rq->curr != rq->idle)
3910 return 0;
3911
3912 if (rq->nr_running)
3913 return 0;
3914
3915#ifdef CONFIG_SMP
3916 if (!llist_empty(&rq->wake_list))
3917 return 0;
3918#endif
3919
3920 return 1;
1da177e4
LT
3921}
3922
1da177e4 3923/**
d1ccc66d 3924 * idle_task - return the idle task for a given CPU.
1da177e4 3925 * @cpu: the processor in question.
e69f6186 3926 *
d1ccc66d 3927 * Return: The idle task for the CPU @cpu.
1da177e4 3928 */
36c8b586 3929struct task_struct *idle_task(int cpu)
1da177e4
LT
3930{
3931 return cpu_rq(cpu)->idle;
3932}
3933
3934/**
3935 * find_process_by_pid - find a process with a matching PID value.
3936 * @pid: the pid in question.
e69f6186
YB
3937 *
3938 * The task of @pid, if found. %NULL otherwise.
1da177e4 3939 */
a9957449 3940static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 3941{
228ebcbe 3942 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
3943}
3944
c13db6b1
SR
3945/*
3946 * sched_setparam() passes in -1 for its policy, to let the functions
3947 * it calls know not to change it.
3948 */
3949#define SETPARAM_POLICY -1
3950
c365c292
TG
3951static void __setscheduler_params(struct task_struct *p,
3952 const struct sched_attr *attr)
1da177e4 3953{
d50dde5a
DF
3954 int policy = attr->sched_policy;
3955
c13db6b1 3956 if (policy == SETPARAM_POLICY)
39fd8fd2
PZ
3957 policy = p->policy;
3958
1da177e4 3959 p->policy = policy;
d50dde5a 3960
aab03e05
DF
3961 if (dl_policy(policy))
3962 __setparam_dl(p, attr);
39fd8fd2 3963 else if (fair_policy(policy))
d50dde5a
DF
3964 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3965
39fd8fd2
PZ
3966 /*
3967 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3968 * !rt_policy. Always setting this ensures that things like
3969 * getparam()/getattr() don't report silly values for !rt tasks.
3970 */
3971 p->rt_priority = attr->sched_priority;
383afd09 3972 p->normal_prio = normal_prio(p);
9059393e 3973 set_load_weight(p, true);
c365c292 3974}
39fd8fd2 3975
c365c292
TG
3976/* Actually do priority change: must hold pi & rq lock. */
3977static void __setscheduler(struct rq *rq, struct task_struct *p,
0782e63b 3978 const struct sched_attr *attr, bool keep_boost)
c365c292
TG
3979{
3980 __setscheduler_params(p, attr);
d50dde5a 3981
383afd09 3982 /*
0782e63b
TG
3983 * Keep a potential priority boosting if called from
3984 * sched_setscheduler().
383afd09 3985 */
acd58620 3986 p->prio = normal_prio(p);
0782e63b 3987 if (keep_boost)
acd58620 3988 p->prio = rt_effective_prio(p, p->prio);
383afd09 3989
aab03e05
DF
3990 if (dl_prio(p->prio))
3991 p->sched_class = &dl_sched_class;
3992 else if (rt_prio(p->prio))
ffd44db5
PZ
3993 p->sched_class = &rt_sched_class;
3994 else
3995 p->sched_class = &fair_sched_class;
1da177e4 3996}
aab03e05 3997
c69e8d9c 3998/*
d1ccc66d 3999 * Check the target process has a UID that matches the current process's:
c69e8d9c
DH
4000 */
4001static bool check_same_owner(struct task_struct *p)
4002{
4003 const struct cred *cred = current_cred(), *pcred;
4004 bool match;
4005
4006 rcu_read_lock();
4007 pcred = __task_cred(p);
9c806aa0
EB
4008 match = (uid_eq(cred->euid, pcred->euid) ||
4009 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
4010 rcu_read_unlock();
4011 return match;
4012}
4013
d50dde5a
DF
4014static int __sched_setscheduler(struct task_struct *p,
4015 const struct sched_attr *attr,
dbc7f069 4016 bool user, bool pi)
1da177e4 4017{
383afd09
SR
4018 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4019 MAX_RT_PRIO - 1 - attr->sched_priority;
da0c1e65 4020 int retval, oldprio, oldpolicy = -1, queued, running;
0782e63b 4021 int new_effective_prio, policy = attr->sched_policy;
83ab0aa0 4022 const struct sched_class *prev_class;
eb580751 4023 struct rq_flags rf;
ca94c442 4024 int reset_on_fork;
7a57f32a 4025 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
eb580751 4026 struct rq *rq;
1da177e4 4027
896bbb25
SRV
4028 /* The pi code expects interrupts enabled */
4029 BUG_ON(pi && in_interrupt());
1da177e4 4030recheck:
d1ccc66d 4031 /* Double check policy once rq lock held: */
ca94c442
LP
4032 if (policy < 0) {
4033 reset_on_fork = p->sched_reset_on_fork;
1da177e4 4034 policy = oldpolicy = p->policy;
ca94c442 4035 } else {
7479f3c9 4036 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
ca94c442 4037
20f9cd2a 4038 if (!valid_policy(policy))
ca94c442
LP
4039 return -EINVAL;
4040 }
4041
2d4283e9
LA
4042 if (attr->sched_flags &
4043 ~(SCHED_FLAG_RESET_ON_FORK | SCHED_FLAG_RECLAIM))
7479f3c9
PZ
4044 return -EINVAL;
4045
1da177e4
LT
4046 /*
4047 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
4048 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4049 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4 4050 */
0bb040a4 4051 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
d50dde5a 4052 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
1da177e4 4053 return -EINVAL;
aab03e05
DF
4054 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4055 (rt_policy(policy) != (attr->sched_priority != 0)))
1da177e4
LT
4056 return -EINVAL;
4057
37e4ab3f
OC
4058 /*
4059 * Allow unprivileged RT tasks to decrease priority:
4060 */
961ccddd 4061 if (user && !capable(CAP_SYS_NICE)) {
d50dde5a 4062 if (fair_policy(policy)) {
d0ea0268 4063 if (attr->sched_nice < task_nice(p) &&
eaad4513 4064 !can_nice(p, attr->sched_nice))
d50dde5a
DF
4065 return -EPERM;
4066 }
4067
e05606d3 4068 if (rt_policy(policy)) {
a44702e8
ON
4069 unsigned long rlim_rtprio =
4070 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909 4071
d1ccc66d 4072 /* Can't set/change the rt policy: */
8dc3e909
ON
4073 if (policy != p->policy && !rlim_rtprio)
4074 return -EPERM;
4075
d1ccc66d 4076 /* Can't increase priority: */
d50dde5a
DF
4077 if (attr->sched_priority > p->rt_priority &&
4078 attr->sched_priority > rlim_rtprio)
8dc3e909
ON
4079 return -EPERM;
4080 }
c02aa73b 4081
d44753b8
JL
4082 /*
4083 * Can't set/change SCHED_DEADLINE policy at all for now
4084 * (safest behavior); in the future we would like to allow
4085 * unprivileged DL tasks to increase their relative deadline
4086 * or reduce their runtime (both ways reducing utilization)
4087 */
4088 if (dl_policy(policy))
4089 return -EPERM;
4090
dd41f596 4091 /*
c02aa73b
DH
4092 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4093 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 4094 */
20f9cd2a 4095 if (idle_policy(p->policy) && !idle_policy(policy)) {
d0ea0268 4096 if (!can_nice(p, task_nice(p)))
c02aa73b
DH
4097 return -EPERM;
4098 }
5fe1d75f 4099
d1ccc66d 4100 /* Can't change other user's priorities: */
c69e8d9c 4101 if (!check_same_owner(p))
37e4ab3f 4102 return -EPERM;
ca94c442 4103
d1ccc66d 4104 /* Normal users shall not reset the sched_reset_on_fork flag: */
ca94c442
LP
4105 if (p->sched_reset_on_fork && !reset_on_fork)
4106 return -EPERM;
37e4ab3f 4107 }
1da177e4 4108
725aad24 4109 if (user) {
b0ae1981 4110 retval = security_task_setscheduler(p);
725aad24
JF
4111 if (retval)
4112 return retval;
4113 }
4114
b29739f9 4115 /*
d1ccc66d 4116 * Make sure no PI-waiters arrive (or leave) while we are
b29739f9 4117 * changing the priority of the task:
0122ec5b 4118 *
25985edc 4119 * To be able to change p->policy safely, the appropriate
1da177e4
LT
4120 * runqueue lock must be held.
4121 */
eb580751 4122 rq = task_rq_lock(p, &rf);
80f5c1b8 4123 update_rq_clock(rq);
dc61b1d6 4124
34f971f6 4125 /*
d1ccc66d 4126 * Changing the policy of the stop threads its a very bad idea:
34f971f6
PZ
4127 */
4128 if (p == rq->stop) {
eb580751 4129 task_rq_unlock(rq, p, &rf);
34f971f6
PZ
4130 return -EINVAL;
4131 }
4132
a51e9198 4133 /*
d6b1e911
TG
4134 * If not changing anything there's no need to proceed further,
4135 * but store a possible modification of reset_on_fork.
a51e9198 4136 */
d50dde5a 4137 if (unlikely(policy == p->policy)) {
d0ea0268 4138 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
d50dde5a
DF
4139 goto change;
4140 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4141 goto change;
75381608 4142 if (dl_policy(policy) && dl_param_changed(p, attr))
aab03e05 4143 goto change;
d50dde5a 4144
d6b1e911 4145 p->sched_reset_on_fork = reset_on_fork;
eb580751 4146 task_rq_unlock(rq, p, &rf);
a51e9198
DF
4147 return 0;
4148 }
d50dde5a 4149change:
a51e9198 4150
dc61b1d6 4151 if (user) {
332ac17e 4152#ifdef CONFIG_RT_GROUP_SCHED
dc61b1d6
PZ
4153 /*
4154 * Do not allow realtime tasks into groups that have no runtime
4155 * assigned.
4156 */
4157 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
4158 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4159 !task_group_is_autogroup(task_group(p))) {
eb580751 4160 task_rq_unlock(rq, p, &rf);
dc61b1d6
PZ
4161 return -EPERM;
4162 }
dc61b1d6 4163#endif
332ac17e
DF
4164#ifdef CONFIG_SMP
4165 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4166 cpumask_t *span = rq->rd->span;
332ac17e
DF
4167
4168 /*
4169 * Don't allow tasks with an affinity mask smaller than
4170 * the entire root_domain to become SCHED_DEADLINE. We
4171 * will also fail if there's no bandwidth available.
4172 */
e4099a5e
PZ
4173 if (!cpumask_subset(span, &p->cpus_allowed) ||
4174 rq->rd->dl_bw.bw == 0) {
eb580751 4175 task_rq_unlock(rq, p, &rf);
332ac17e
DF
4176 return -EPERM;
4177 }
4178 }
4179#endif
4180 }
dc61b1d6 4181
d1ccc66d 4182 /* Re-check policy now with rq lock held: */
1da177e4
LT
4183 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4184 policy = oldpolicy = -1;
eb580751 4185 task_rq_unlock(rq, p, &rf);
1da177e4
LT
4186 goto recheck;
4187 }
332ac17e
DF
4188
4189 /*
4190 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4191 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4192 * is available.
4193 */
06a76fe0 4194 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
eb580751 4195 task_rq_unlock(rq, p, &rf);
332ac17e
DF
4196 return -EBUSY;
4197 }
4198
c365c292
TG
4199 p->sched_reset_on_fork = reset_on_fork;
4200 oldprio = p->prio;
4201
dbc7f069
PZ
4202 if (pi) {
4203 /*
4204 * Take priority boosted tasks into account. If the new
4205 * effective priority is unchanged, we just store the new
4206 * normal parameters and do not touch the scheduler class and
4207 * the runqueue. This will be done when the task deboost
4208 * itself.
4209 */
acd58620 4210 new_effective_prio = rt_effective_prio(p, newprio);
ff77e468
PZ
4211 if (new_effective_prio == oldprio)
4212 queue_flags &= ~DEQUEUE_MOVE;
c365c292
TG
4213 }
4214
da0c1e65 4215 queued = task_on_rq_queued(p);
051a1d1a 4216 running = task_current(rq, p);
da0c1e65 4217 if (queued)
ff77e468 4218 dequeue_task(rq, p, queue_flags);
0e1f3483 4219 if (running)
f3cd1c4e 4220 put_prev_task(rq, p);
f6b53205 4221
83ab0aa0 4222 prev_class = p->sched_class;
dbc7f069 4223 __setscheduler(rq, p, attr, pi);
f6b53205 4224
da0c1e65 4225 if (queued) {
81a44c54
TG
4226 /*
4227 * We enqueue to tail when the priority of a task is
4228 * increased (user space view).
4229 */
ff77e468
PZ
4230 if (oldprio < p->prio)
4231 queue_flags |= ENQUEUE_HEAD;
1de64443 4232
ff77e468 4233 enqueue_task(rq, p, queue_flags);
81a44c54 4234 }
a399d233 4235 if (running)
b2bf6c31 4236 set_curr_task(rq, p);
cb469845 4237
da7a735e 4238 check_class_changed(rq, p, prev_class, oldprio);
d1ccc66d
IM
4239
4240 /* Avoid rq from going away on us: */
4241 preempt_disable();
eb580751 4242 task_rq_unlock(rq, p, &rf);
b29739f9 4243
dbc7f069
PZ
4244 if (pi)
4245 rt_mutex_adjust_pi(p);
95e02ca9 4246
d1ccc66d 4247 /* Run balance callbacks after we've adjusted the PI chain: */
4c9a4bc8
PZ
4248 balance_callback(rq);
4249 preempt_enable();
95e02ca9 4250
1da177e4
LT
4251 return 0;
4252}
961ccddd 4253
7479f3c9
PZ
4254static int _sched_setscheduler(struct task_struct *p, int policy,
4255 const struct sched_param *param, bool check)
4256{
4257 struct sched_attr attr = {
4258 .sched_policy = policy,
4259 .sched_priority = param->sched_priority,
4260 .sched_nice = PRIO_TO_NICE(p->static_prio),
4261 };
4262
c13db6b1
SR
4263 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4264 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7479f3c9
PZ
4265 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4266 policy &= ~SCHED_RESET_ON_FORK;
4267 attr.sched_policy = policy;
4268 }
4269
dbc7f069 4270 return __sched_setscheduler(p, &attr, check, true);
7479f3c9 4271}
961ccddd
RR
4272/**
4273 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4274 * @p: the task in question.
4275 * @policy: new policy.
4276 * @param: structure containing the new RT priority.
4277 *
e69f6186
YB
4278 * Return: 0 on success. An error code otherwise.
4279 *
961ccddd
RR
4280 * NOTE that the task may be already dead.
4281 */
4282int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 4283 const struct sched_param *param)
961ccddd 4284{
7479f3c9 4285 return _sched_setscheduler(p, policy, param, true);
961ccddd 4286}
1da177e4
LT
4287EXPORT_SYMBOL_GPL(sched_setscheduler);
4288
d50dde5a
DF
4289int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4290{
dbc7f069 4291 return __sched_setscheduler(p, attr, true, true);
d50dde5a
DF
4292}
4293EXPORT_SYMBOL_GPL(sched_setattr);
4294
961ccddd
RR
4295/**
4296 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4297 * @p: the task in question.
4298 * @policy: new policy.
4299 * @param: structure containing the new RT priority.
4300 *
4301 * Just like sched_setscheduler, only don't bother checking if the
4302 * current context has permission. For example, this is needed in
4303 * stop_machine(): we create temporary high priority worker threads,
4304 * but our caller might not have that capability.
e69f6186
YB
4305 *
4306 * Return: 0 on success. An error code otherwise.
961ccddd
RR
4307 */
4308int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 4309 const struct sched_param *param)
961ccddd 4310{
7479f3c9 4311 return _sched_setscheduler(p, policy, param, false);
961ccddd 4312}
84778472 4313EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
961ccddd 4314
95cdf3b7
IM
4315static int
4316do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4317{
1da177e4
LT
4318 struct sched_param lparam;
4319 struct task_struct *p;
36c8b586 4320 int retval;
1da177e4
LT
4321
4322 if (!param || pid < 0)
4323 return -EINVAL;
4324 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4325 return -EFAULT;
5fe1d75f
ON
4326
4327 rcu_read_lock();
4328 retval = -ESRCH;
1da177e4 4329 p = find_process_by_pid(pid);
5fe1d75f
ON
4330 if (p != NULL)
4331 retval = sched_setscheduler(p, policy, &lparam);
4332 rcu_read_unlock();
36c8b586 4333
1da177e4
LT
4334 return retval;
4335}
4336
d50dde5a
DF
4337/*
4338 * Mimics kernel/events/core.c perf_copy_attr().
4339 */
d1ccc66d 4340static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
d50dde5a
DF
4341{
4342 u32 size;
4343 int ret;
4344
4345 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4346 return -EFAULT;
4347
d1ccc66d 4348 /* Zero the full structure, so that a short copy will be nice: */
d50dde5a
DF
4349 memset(attr, 0, sizeof(*attr));
4350
4351 ret = get_user(size, &uattr->size);
4352 if (ret)
4353 return ret;
4354
d1ccc66d
IM
4355 /* Bail out on silly large: */
4356 if (size > PAGE_SIZE)
d50dde5a
DF
4357 goto err_size;
4358
d1ccc66d
IM
4359 /* ABI compatibility quirk: */
4360 if (!size)
d50dde5a
DF
4361 size = SCHED_ATTR_SIZE_VER0;
4362
4363 if (size < SCHED_ATTR_SIZE_VER0)
4364 goto err_size;
4365
4366 /*
4367 * If we're handed a bigger struct than we know of,
4368 * ensure all the unknown bits are 0 - i.e. new
4369 * user-space does not rely on any kernel feature
4370 * extensions we dont know about yet.
4371 */
4372 if (size > sizeof(*attr)) {
4373 unsigned char __user *addr;
4374 unsigned char __user *end;
4375 unsigned char val;
4376
4377 addr = (void __user *)uattr + sizeof(*attr);
4378 end = (void __user *)uattr + size;
4379
4380 for (; addr < end; addr++) {
4381 ret = get_user(val, addr);
4382 if (ret)
4383 return ret;
4384 if (val)
4385 goto err_size;
4386 }
4387 size = sizeof(*attr);
4388 }
4389
4390 ret = copy_from_user(attr, uattr, size);
4391 if (ret)
4392 return -EFAULT;
4393
4394 /*
d1ccc66d 4395 * XXX: Do we want to be lenient like existing syscalls; or do we want
d50dde5a
DF
4396 * to be strict and return an error on out-of-bounds values?
4397 */
75e45d51 4398 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
d50dde5a 4399
e78c7bca 4400 return 0;
d50dde5a
DF
4401
4402err_size:
4403 put_user(sizeof(*attr), &uattr->size);
e78c7bca 4404 return -E2BIG;
d50dde5a
DF
4405}
4406
1da177e4
LT
4407/**
4408 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4409 * @pid: the pid in question.
4410 * @policy: new policy.
4411 * @param: structure containing the new RT priority.
e69f6186
YB
4412 *
4413 * Return: 0 on success. An error code otherwise.
1da177e4 4414 */
d1ccc66d 4415SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
1da177e4 4416{
c21761f1
JB
4417 if (policy < 0)
4418 return -EINVAL;
4419
1da177e4
LT
4420 return do_sched_setscheduler(pid, policy, param);
4421}
4422
4423/**
4424 * sys_sched_setparam - set/change the RT priority of a thread
4425 * @pid: the pid in question.
4426 * @param: structure containing the new RT priority.
e69f6186
YB
4427 *
4428 * Return: 0 on success. An error code otherwise.
1da177e4 4429 */
5add95d4 4430SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 4431{
c13db6b1 4432 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
1da177e4
LT
4433}
4434
d50dde5a
DF
4435/**
4436 * sys_sched_setattr - same as above, but with extended sched_attr
4437 * @pid: the pid in question.
5778fccf 4438 * @uattr: structure containing the extended parameters.
db66d756 4439 * @flags: for future extension.
d50dde5a 4440 */
6d35ab48
PZ
4441SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4442 unsigned int, flags)
d50dde5a
DF
4443{
4444 struct sched_attr attr;
4445 struct task_struct *p;
4446 int retval;
4447
6d35ab48 4448 if (!uattr || pid < 0 || flags)
d50dde5a
DF
4449 return -EINVAL;
4450
143cf23d
MK
4451 retval = sched_copy_attr(uattr, &attr);
4452 if (retval)
4453 return retval;
d50dde5a 4454
b14ed2c2 4455 if ((int)attr.sched_policy < 0)
dbdb2275 4456 return -EINVAL;
d50dde5a
DF
4457
4458 rcu_read_lock();
4459 retval = -ESRCH;
4460 p = find_process_by_pid(pid);
4461 if (p != NULL)
4462 retval = sched_setattr(p, &attr);
4463 rcu_read_unlock();
4464
4465 return retval;
4466}
4467
1da177e4
LT
4468/**
4469 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4470 * @pid: the pid in question.
e69f6186
YB
4471 *
4472 * Return: On success, the policy of the thread. Otherwise, a negative error
4473 * code.
1da177e4 4474 */
5add95d4 4475SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 4476{
36c8b586 4477 struct task_struct *p;
3a5c359a 4478 int retval;
1da177e4
LT
4479
4480 if (pid < 0)
3a5c359a 4481 return -EINVAL;
1da177e4
LT
4482
4483 retval = -ESRCH;
5fe85be0 4484 rcu_read_lock();
1da177e4
LT
4485 p = find_process_by_pid(pid);
4486 if (p) {
4487 retval = security_task_getscheduler(p);
4488 if (!retval)
ca94c442
LP
4489 retval = p->policy
4490 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 4491 }
5fe85be0 4492 rcu_read_unlock();
1da177e4
LT
4493 return retval;
4494}
4495
4496/**
ca94c442 4497 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
4498 * @pid: the pid in question.
4499 * @param: structure containing the RT priority.
e69f6186
YB
4500 *
4501 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4502 * code.
1da177e4 4503 */
5add95d4 4504SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 4505{
ce5f7f82 4506 struct sched_param lp = { .sched_priority = 0 };
36c8b586 4507 struct task_struct *p;
3a5c359a 4508 int retval;
1da177e4
LT
4509
4510 if (!param || pid < 0)
3a5c359a 4511 return -EINVAL;
1da177e4 4512
5fe85be0 4513 rcu_read_lock();
1da177e4
LT
4514 p = find_process_by_pid(pid);
4515 retval = -ESRCH;
4516 if (!p)
4517 goto out_unlock;
4518
4519 retval = security_task_getscheduler(p);
4520 if (retval)
4521 goto out_unlock;
4522
ce5f7f82
PZ
4523 if (task_has_rt_policy(p))
4524 lp.sched_priority = p->rt_priority;
5fe85be0 4525 rcu_read_unlock();
1da177e4
LT
4526
4527 /*
4528 * This one might sleep, we cannot do it with a spinlock held ...
4529 */
4530 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4531
1da177e4
LT
4532 return retval;
4533
4534out_unlock:
5fe85be0 4535 rcu_read_unlock();
1da177e4
LT
4536 return retval;
4537}
4538
d50dde5a
DF
4539static int sched_read_attr(struct sched_attr __user *uattr,
4540 struct sched_attr *attr,
4541 unsigned int usize)
4542{
4543 int ret;
4544
4545 if (!access_ok(VERIFY_WRITE, uattr, usize))
4546 return -EFAULT;
4547
4548 /*
4549 * If we're handed a smaller struct than we know of,
4550 * ensure all the unknown bits are 0 - i.e. old
4551 * user-space does not get uncomplete information.
4552 */
4553 if (usize < sizeof(*attr)) {
4554 unsigned char *addr;
4555 unsigned char *end;
4556
4557 addr = (void *)attr + usize;
4558 end = (void *)attr + sizeof(*attr);
4559
4560 for (; addr < end; addr++) {
4561 if (*addr)
22400674 4562 return -EFBIG;
d50dde5a
DF
4563 }
4564
4565 attr->size = usize;
4566 }
4567
4efbc454 4568 ret = copy_to_user(uattr, attr, attr->size);
d50dde5a
DF
4569 if (ret)
4570 return -EFAULT;
4571
22400674 4572 return 0;
d50dde5a
DF
4573}
4574
4575/**
aab03e05 4576 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
d50dde5a 4577 * @pid: the pid in question.
5778fccf 4578 * @uattr: structure containing the extended parameters.
d50dde5a 4579 * @size: sizeof(attr) for fwd/bwd comp.
db66d756 4580 * @flags: for future extension.
d50dde5a 4581 */
6d35ab48
PZ
4582SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4583 unsigned int, size, unsigned int, flags)
d50dde5a
DF
4584{
4585 struct sched_attr attr = {
4586 .size = sizeof(struct sched_attr),
4587 };
4588 struct task_struct *p;
4589 int retval;
4590
4591 if (!uattr || pid < 0 || size > PAGE_SIZE ||
6d35ab48 4592 size < SCHED_ATTR_SIZE_VER0 || flags)
d50dde5a
DF
4593 return -EINVAL;
4594
4595 rcu_read_lock();
4596 p = find_process_by_pid(pid);
4597 retval = -ESRCH;
4598 if (!p)
4599 goto out_unlock;
4600
4601 retval = security_task_getscheduler(p);
4602 if (retval)
4603 goto out_unlock;
4604
4605 attr.sched_policy = p->policy;
7479f3c9
PZ
4606 if (p->sched_reset_on_fork)
4607 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
aab03e05
DF
4608 if (task_has_dl_policy(p))
4609 __getparam_dl(p, &attr);
4610 else if (task_has_rt_policy(p))
d50dde5a
DF
4611 attr.sched_priority = p->rt_priority;
4612 else
d0ea0268 4613 attr.sched_nice = task_nice(p);
d50dde5a
DF
4614
4615 rcu_read_unlock();
4616
4617 retval = sched_read_attr(uattr, &attr, size);
4618 return retval;
4619
4620out_unlock:
4621 rcu_read_unlock();
4622 return retval;
4623}
4624
96f874e2 4625long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1da177e4 4626{
5a16f3d3 4627 cpumask_var_t cpus_allowed, new_mask;
36c8b586
IM
4628 struct task_struct *p;
4629 int retval;
1da177e4 4630
23f5d142 4631 rcu_read_lock();
1da177e4
LT
4632
4633 p = find_process_by_pid(pid);
4634 if (!p) {
23f5d142 4635 rcu_read_unlock();
1da177e4
LT
4636 return -ESRCH;
4637 }
4638
23f5d142 4639 /* Prevent p going away */
1da177e4 4640 get_task_struct(p);
23f5d142 4641 rcu_read_unlock();
1da177e4 4642
14a40ffc
TH
4643 if (p->flags & PF_NO_SETAFFINITY) {
4644 retval = -EINVAL;
4645 goto out_put_task;
4646 }
5a16f3d3
RR
4647 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4648 retval = -ENOMEM;
4649 goto out_put_task;
4650 }
4651 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4652 retval = -ENOMEM;
4653 goto out_free_cpus_allowed;
4654 }
1da177e4 4655 retval = -EPERM;
4c44aaaf
EB
4656 if (!check_same_owner(p)) {
4657 rcu_read_lock();
4658 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4659 rcu_read_unlock();
16303ab2 4660 goto out_free_new_mask;
4c44aaaf
EB
4661 }
4662 rcu_read_unlock();
4663 }
1da177e4 4664
b0ae1981 4665 retval = security_task_setscheduler(p);
e7834f8f 4666 if (retval)
16303ab2 4667 goto out_free_new_mask;
e7834f8f 4668
e4099a5e
PZ
4669
4670 cpuset_cpus_allowed(p, cpus_allowed);
4671 cpumask_and(new_mask, in_mask, cpus_allowed);
4672
332ac17e
DF
4673 /*
4674 * Since bandwidth control happens on root_domain basis,
4675 * if admission test is enabled, we only admit -deadline
4676 * tasks allowed to run on all the CPUs in the task's
4677 * root_domain.
4678 */
4679#ifdef CONFIG_SMP
f1e3a093
KT
4680 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4681 rcu_read_lock();
4682 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
332ac17e 4683 retval = -EBUSY;
f1e3a093 4684 rcu_read_unlock();
16303ab2 4685 goto out_free_new_mask;
332ac17e 4686 }
f1e3a093 4687 rcu_read_unlock();
332ac17e
DF
4688 }
4689#endif
49246274 4690again:
25834c73 4691 retval = __set_cpus_allowed_ptr(p, new_mask, true);
1da177e4 4692
8707d8b8 4693 if (!retval) {
5a16f3d3
RR
4694 cpuset_cpus_allowed(p, cpus_allowed);
4695 if (!cpumask_subset(new_mask, cpus_allowed)) {
8707d8b8
PM
4696 /*
4697 * We must have raced with a concurrent cpuset
4698 * update. Just reset the cpus_allowed to the
4699 * cpuset's cpus_allowed
4700 */
5a16f3d3 4701 cpumask_copy(new_mask, cpus_allowed);
8707d8b8
PM
4702 goto again;
4703 }
4704 }
16303ab2 4705out_free_new_mask:
5a16f3d3
RR
4706 free_cpumask_var(new_mask);
4707out_free_cpus_allowed:
4708 free_cpumask_var(cpus_allowed);
4709out_put_task:
1da177e4 4710 put_task_struct(p);
1da177e4
LT
4711 return retval;
4712}
4713
4714static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 4715 struct cpumask *new_mask)
1da177e4 4716{
96f874e2
RR
4717 if (len < cpumask_size())
4718 cpumask_clear(new_mask);
4719 else if (len > cpumask_size())
4720 len = cpumask_size();
4721
1da177e4
LT
4722 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4723}
4724
4725/**
d1ccc66d 4726 * sys_sched_setaffinity - set the CPU affinity of a process
1da177e4
LT
4727 * @pid: pid of the process
4728 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 4729 * @user_mask_ptr: user-space pointer to the new CPU mask
e69f6186
YB
4730 *
4731 * Return: 0 on success. An error code otherwise.
1da177e4 4732 */
5add95d4
HC
4733SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4734 unsigned long __user *, user_mask_ptr)
1da177e4 4735{
5a16f3d3 4736 cpumask_var_t new_mask;
1da177e4
LT
4737 int retval;
4738
5a16f3d3
RR
4739 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4740 return -ENOMEM;
1da177e4 4741
5a16f3d3
RR
4742 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4743 if (retval == 0)
4744 retval = sched_setaffinity(pid, new_mask);
4745 free_cpumask_var(new_mask);
4746 return retval;
1da177e4
LT
4747}
4748
96f874e2 4749long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 4750{
36c8b586 4751 struct task_struct *p;
31605683 4752 unsigned long flags;
1da177e4 4753 int retval;
1da177e4 4754
23f5d142 4755 rcu_read_lock();
1da177e4
LT
4756
4757 retval = -ESRCH;
4758 p = find_process_by_pid(pid);
4759 if (!p)
4760 goto out_unlock;
4761
e7834f8f
DQ
4762 retval = security_task_getscheduler(p);
4763 if (retval)
4764 goto out_unlock;
4765
013fdb80 4766 raw_spin_lock_irqsave(&p->pi_lock, flags);
6acce3ef 4767 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
013fdb80 4768 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4769
4770out_unlock:
23f5d142 4771 rcu_read_unlock();
1da177e4 4772
9531b62f 4773 return retval;
1da177e4
LT
4774}
4775
4776/**
d1ccc66d 4777 * sys_sched_getaffinity - get the CPU affinity of a process
1da177e4
LT
4778 * @pid: pid of the process
4779 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 4780 * @user_mask_ptr: user-space pointer to hold the current CPU mask
e69f6186 4781 *
599b4840
ZW
4782 * Return: size of CPU mask copied to user_mask_ptr on success. An
4783 * error code otherwise.
1da177e4 4784 */
5add95d4
HC
4785SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4786 unsigned long __user *, user_mask_ptr)
1da177e4
LT
4787{
4788 int ret;
f17c8607 4789 cpumask_var_t mask;
1da177e4 4790
84fba5ec 4791 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
4792 return -EINVAL;
4793 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
4794 return -EINVAL;
4795
f17c8607
RR
4796 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4797 return -ENOMEM;
1da177e4 4798
f17c8607
RR
4799 ret = sched_getaffinity(pid, mask);
4800 if (ret == 0) {
8bc037fb 4801 size_t retlen = min_t(size_t, len, cpumask_size());
cd3d8031
KM
4802
4803 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
4804 ret = -EFAULT;
4805 else
cd3d8031 4806 ret = retlen;
f17c8607
RR
4807 }
4808 free_cpumask_var(mask);
1da177e4 4809
f17c8607 4810 return ret;
1da177e4
LT
4811}
4812
4813/**
4814 * sys_sched_yield - yield the current processor to other threads.
4815 *
dd41f596
IM
4816 * This function yields the current CPU to other tasks. If there are no
4817 * other threads running on this CPU then this function will return.
e69f6186
YB
4818 *
4819 * Return: 0.
1da177e4 4820 */
5add95d4 4821SYSCALL_DEFINE0(sched_yield)
1da177e4 4822{
8a8c69c3
PZ
4823 struct rq_flags rf;
4824 struct rq *rq;
4825
4826 local_irq_disable();
4827 rq = this_rq();
4828 rq_lock(rq, &rf);
1da177e4 4829
ae92882e 4830 schedstat_inc(rq->yld_count);
4530d7ab 4831 current->sched_class->yield_task(rq);
1da177e4
LT
4832
4833 /*
4834 * Since we are going to call schedule() anyway, there's
4835 * no need to preempt or enable interrupts:
4836 */
8a8c69c3
PZ
4837 preempt_disable();
4838 rq_unlock(rq, &rf);
ba74c144 4839 sched_preempt_enable_no_resched();
1da177e4
LT
4840
4841 schedule();
4842
4843 return 0;
4844}
4845
35a773a0 4846#ifndef CONFIG_PREEMPT
02b67cc3 4847int __sched _cond_resched(void)
1da177e4 4848{
fe32d3cd 4849 if (should_resched(0)) {
a18b5d01 4850 preempt_schedule_common();
1da177e4
LT
4851 return 1;
4852 }
f79c3ad6 4853 rcu_all_qs();
1da177e4
LT
4854 return 0;
4855}
02b67cc3 4856EXPORT_SYMBOL(_cond_resched);
35a773a0 4857#endif
1da177e4
LT
4858
4859/*
613afbf8 4860 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
4861 * call schedule, and on return reacquire the lock.
4862 *
41a2d6cf 4863 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
1da177e4
LT
4864 * operations here to prevent schedule() from being called twice (once via
4865 * spin_unlock(), once by hand).
4866 */
613afbf8 4867int __cond_resched_lock(spinlock_t *lock)
1da177e4 4868{
fe32d3cd 4869 int resched = should_resched(PREEMPT_LOCK_OFFSET);
6df3cecb
JK
4870 int ret = 0;
4871
f607c668
PZ
4872 lockdep_assert_held(lock);
4873
4a81e832 4874 if (spin_needbreak(lock) || resched) {
1da177e4 4875 spin_unlock(lock);
d86ee480 4876 if (resched)
a18b5d01 4877 preempt_schedule_common();
95c354fe
NP
4878 else
4879 cpu_relax();
6df3cecb 4880 ret = 1;
1da177e4 4881 spin_lock(lock);
1da177e4 4882 }
6df3cecb 4883 return ret;
1da177e4 4884}
613afbf8 4885EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 4886
613afbf8 4887int __sched __cond_resched_softirq(void)
1da177e4
LT
4888{
4889 BUG_ON(!in_softirq());
4890
fe32d3cd 4891 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
98d82567 4892 local_bh_enable();
a18b5d01 4893 preempt_schedule_common();
1da177e4
LT
4894 local_bh_disable();
4895 return 1;
4896 }
4897 return 0;
4898}
613afbf8 4899EXPORT_SYMBOL(__cond_resched_softirq);
1da177e4 4900
1da177e4
LT
4901/**
4902 * yield - yield the current processor to other threads.
4903 *
8e3fabfd
PZ
4904 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4905 *
4906 * The scheduler is at all times free to pick the calling task as the most
4907 * eligible task to run, if removing the yield() call from your code breaks
4908 * it, its already broken.
4909 *
4910 * Typical broken usage is:
4911 *
4912 * while (!event)
d1ccc66d 4913 * yield();
8e3fabfd
PZ
4914 *
4915 * where one assumes that yield() will let 'the other' process run that will
4916 * make event true. If the current task is a SCHED_FIFO task that will never
4917 * happen. Never use yield() as a progress guarantee!!
4918 *
4919 * If you want to use yield() to wait for something, use wait_event().
4920 * If you want to use yield() to be 'nice' for others, use cond_resched().
4921 * If you still want to use yield(), do not!
1da177e4
LT
4922 */
4923void __sched yield(void)
4924{
4925 set_current_state(TASK_RUNNING);
4926 sys_sched_yield();
4927}
1da177e4
LT
4928EXPORT_SYMBOL(yield);
4929
d95f4122
MG
4930/**
4931 * yield_to - yield the current processor to another thread in
4932 * your thread group, or accelerate that thread toward the
4933 * processor it's on.
16addf95
RD
4934 * @p: target task
4935 * @preempt: whether task preemption is allowed or not
d95f4122
MG
4936 *
4937 * It's the caller's job to ensure that the target task struct
4938 * can't go away on us before we can do any checks.
4939 *
e69f6186 4940 * Return:
7b270f60
PZ
4941 * true (>0) if we indeed boosted the target task.
4942 * false (0) if we failed to boost the target.
4943 * -ESRCH if there's no task to yield to.
d95f4122 4944 */
fa93384f 4945int __sched yield_to(struct task_struct *p, bool preempt)
d95f4122
MG
4946{
4947 struct task_struct *curr = current;
4948 struct rq *rq, *p_rq;
4949 unsigned long flags;
c3c18640 4950 int yielded = 0;
d95f4122
MG
4951
4952 local_irq_save(flags);
4953 rq = this_rq();
4954
4955again:
4956 p_rq = task_rq(p);
7b270f60
PZ
4957 /*
4958 * If we're the only runnable task on the rq and target rq also
4959 * has only one task, there's absolutely no point in yielding.
4960 */
4961 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4962 yielded = -ESRCH;
4963 goto out_irq;
4964 }
4965
d95f4122 4966 double_rq_lock(rq, p_rq);
39e24d8f 4967 if (task_rq(p) != p_rq) {
d95f4122
MG
4968 double_rq_unlock(rq, p_rq);
4969 goto again;
4970 }
4971
4972 if (!curr->sched_class->yield_to_task)
7b270f60 4973 goto out_unlock;
d95f4122
MG
4974
4975 if (curr->sched_class != p->sched_class)
7b270f60 4976 goto out_unlock;
d95f4122
MG
4977
4978 if (task_running(p_rq, p) || p->state)
7b270f60 4979 goto out_unlock;
d95f4122
MG
4980
4981 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
6d1cafd8 4982 if (yielded) {
ae92882e 4983 schedstat_inc(rq->yld_count);
6d1cafd8
VP
4984 /*
4985 * Make p's CPU reschedule; pick_next_entity takes care of
4986 * fairness.
4987 */
4988 if (preempt && rq != p_rq)
8875125e 4989 resched_curr(p_rq);
6d1cafd8 4990 }
d95f4122 4991
7b270f60 4992out_unlock:
d95f4122 4993 double_rq_unlock(rq, p_rq);
7b270f60 4994out_irq:
d95f4122
MG
4995 local_irq_restore(flags);
4996
7b270f60 4997 if (yielded > 0)
d95f4122
MG
4998 schedule();
4999
5000 return yielded;
5001}
5002EXPORT_SYMBOL_GPL(yield_to);
5003
10ab5643
TH
5004int io_schedule_prepare(void)
5005{
5006 int old_iowait = current->in_iowait;
5007
5008 current->in_iowait = 1;
5009 blk_schedule_flush_plug(current);
5010
5011 return old_iowait;
5012}
5013
5014void io_schedule_finish(int token)
5015{
5016 current->in_iowait = token;
5017}
5018
1da177e4 5019/*
41a2d6cf 5020 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 5021 * that process accounting knows that this is a task in IO wait state.
1da177e4 5022 */
1da177e4
LT
5023long __sched io_schedule_timeout(long timeout)
5024{
10ab5643 5025 int token;
1da177e4
LT
5026 long ret;
5027
10ab5643 5028 token = io_schedule_prepare();
1da177e4 5029 ret = schedule_timeout(timeout);
10ab5643 5030 io_schedule_finish(token);
9cff8ade 5031
1da177e4
LT
5032 return ret;
5033}
9cff8ade 5034EXPORT_SYMBOL(io_schedule_timeout);
1da177e4 5035
10ab5643
TH
5036void io_schedule(void)
5037{
5038 int token;
5039
5040 token = io_schedule_prepare();
5041 schedule();
5042 io_schedule_finish(token);
5043}
5044EXPORT_SYMBOL(io_schedule);
5045
1da177e4
LT
5046/**
5047 * sys_sched_get_priority_max - return maximum RT priority.
5048 * @policy: scheduling class.
5049 *
e69f6186
YB
5050 * Return: On success, this syscall returns the maximum
5051 * rt_priority that can be used by a given scheduling class.
5052 * On failure, a negative error code is returned.
1da177e4 5053 */
5add95d4 5054SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
5055{
5056 int ret = -EINVAL;
5057
5058 switch (policy) {
5059 case SCHED_FIFO:
5060 case SCHED_RR:
5061 ret = MAX_USER_RT_PRIO-1;
5062 break;
aab03e05 5063 case SCHED_DEADLINE:
1da177e4 5064 case SCHED_NORMAL:
b0a9499c 5065 case SCHED_BATCH:
dd41f596 5066 case SCHED_IDLE:
1da177e4
LT
5067 ret = 0;
5068 break;
5069 }
5070 return ret;
5071}
5072
5073/**
5074 * sys_sched_get_priority_min - return minimum RT priority.
5075 * @policy: scheduling class.
5076 *
e69f6186
YB
5077 * Return: On success, this syscall returns the minimum
5078 * rt_priority that can be used by a given scheduling class.
5079 * On failure, a negative error code is returned.
1da177e4 5080 */
5add95d4 5081SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
5082{
5083 int ret = -EINVAL;
5084
5085 switch (policy) {
5086 case SCHED_FIFO:
5087 case SCHED_RR:
5088 ret = 1;
5089 break;
aab03e05 5090 case SCHED_DEADLINE:
1da177e4 5091 case SCHED_NORMAL:
b0a9499c 5092 case SCHED_BATCH:
dd41f596 5093 case SCHED_IDLE:
1da177e4
LT
5094 ret = 0;
5095 }
5096 return ret;
5097}
5098
5099/**
5100 * sys_sched_rr_get_interval - return the default timeslice of a process.
5101 * @pid: pid of the process.
5102 * @interval: userspace pointer to the timeslice value.
5103 *
5104 * this syscall writes the default timeslice value of a given process
5105 * into the user-space timespec buffer. A value of '0' means infinity.
e69f6186
YB
5106 *
5107 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5108 * an error code.
1da177e4 5109 */
17da2bd9 5110SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
754fe8d2 5111 struct timespec __user *, interval)
1da177e4 5112{
36c8b586 5113 struct task_struct *p;
a4ec24b4 5114 unsigned int time_slice;
eb580751
PZ
5115 struct rq_flags rf;
5116 struct timespec t;
dba091b9 5117 struct rq *rq;
3a5c359a 5118 int retval;
1da177e4
LT
5119
5120 if (pid < 0)
3a5c359a 5121 return -EINVAL;
1da177e4
LT
5122
5123 retval = -ESRCH;
1a551ae7 5124 rcu_read_lock();
1da177e4
LT
5125 p = find_process_by_pid(pid);
5126 if (!p)
5127 goto out_unlock;
5128
5129 retval = security_task_getscheduler(p);
5130 if (retval)
5131 goto out_unlock;
5132
eb580751 5133 rq = task_rq_lock(p, &rf);
a57beec5
PZ
5134 time_slice = 0;
5135 if (p->sched_class->get_rr_interval)
5136 time_slice = p->sched_class->get_rr_interval(rq, p);
eb580751 5137 task_rq_unlock(rq, p, &rf);
a4ec24b4 5138
1a551ae7 5139 rcu_read_unlock();
a4ec24b4 5140 jiffies_to_timespec(time_slice, &t);
1da177e4 5141 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
1da177e4 5142 return retval;
3a5c359a 5143
1da177e4 5144out_unlock:
1a551ae7 5145 rcu_read_unlock();
1da177e4
LT
5146 return retval;
5147}
5148
82a1fcb9 5149void sched_show_task(struct task_struct *p)
1da177e4 5150{
1da177e4 5151 unsigned long free = 0;
4e79752c 5152 int ppid;
c930b2c0 5153
38200502
TH
5154 if (!try_get_task_stack(p))
5155 return;
20435d84
XX
5156
5157 printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5158
5159 if (p->state == TASK_RUNNING)
3df0fc5b 5160 printk(KERN_CONT " running task ");
1da177e4 5161#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 5162 free = stack_not_used(p);
1da177e4 5163#endif
a90e984c 5164 ppid = 0;
4e79752c 5165 rcu_read_lock();
a90e984c
ON
5166 if (pid_alive(p))
5167 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4e79752c 5168 rcu_read_unlock();
3df0fc5b 5169 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4e79752c 5170 task_pid_nr(p), ppid,
aa47b7e0 5171 (unsigned long)task_thread_info(p)->flags);
1da177e4 5172
3d1cb205 5173 print_worker_info(KERN_INFO, p);
5fb5e6de 5174 show_stack(p, NULL);
38200502 5175 put_task_stack(p);
1da177e4 5176}
0032f4e8 5177EXPORT_SYMBOL_GPL(sched_show_task);
1da177e4 5178
5d68cc95
PZ
5179static inline bool
5180state_filter_match(unsigned long state_filter, struct task_struct *p)
5181{
5182 /* no filter, everything matches */
5183 if (!state_filter)
5184 return true;
5185
5186 /* filter, but doesn't match */
5187 if (!(p->state & state_filter))
5188 return false;
5189
5190 /*
5191 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5192 * TASK_KILLABLE).
5193 */
5194 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5195 return false;
5196
5197 return true;
5198}
5199
5200
e59e2ae2 5201void show_state_filter(unsigned long state_filter)
1da177e4 5202{
36c8b586 5203 struct task_struct *g, *p;
1da177e4 5204
4bd77321 5205#if BITS_PER_LONG == 32
3df0fc5b
PZ
5206 printk(KERN_INFO
5207 " task PC stack pid father\n");
1da177e4 5208#else
3df0fc5b
PZ
5209 printk(KERN_INFO
5210 " task PC stack pid father\n");
1da177e4 5211#endif
510f5acc 5212 rcu_read_lock();
5d07f420 5213 for_each_process_thread(g, p) {
1da177e4
LT
5214 /*
5215 * reset the NMI-timeout, listing all files on a slow
25985edc 5216 * console might take a lot of time:
57675cb9
AR
5217 * Also, reset softlockup watchdogs on all CPUs, because
5218 * another CPU might be blocked waiting for us to process
5219 * an IPI.
1da177e4
LT
5220 */
5221 touch_nmi_watchdog();
57675cb9 5222 touch_all_softlockup_watchdogs();
5d68cc95 5223 if (state_filter_match(state_filter, p))
82a1fcb9 5224 sched_show_task(p);
5d07f420 5225 }
1da177e4 5226
dd41f596 5227#ifdef CONFIG_SCHED_DEBUG
fb90a6e9
RV
5228 if (!state_filter)
5229 sysrq_sched_debug_show();
dd41f596 5230#endif
510f5acc 5231 rcu_read_unlock();
e59e2ae2
IM
5232 /*
5233 * Only show locks if all tasks are dumped:
5234 */
93335a21 5235 if (!state_filter)
e59e2ae2 5236 debug_show_all_locks();
1da177e4
LT
5237}
5238
f340c0d1
IM
5239/**
5240 * init_idle - set up an idle thread for a given CPU
5241 * @idle: task in question
d1ccc66d 5242 * @cpu: CPU the idle task belongs to
f340c0d1
IM
5243 *
5244 * NOTE: this function does not set the idle thread's NEED_RESCHED
5245 * flag, to make booting more robust.
5246 */
0db0628d 5247void init_idle(struct task_struct *idle, int cpu)
1da177e4 5248{
70b97a7f 5249 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
5250 unsigned long flags;
5251
25834c73
PZ
5252 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5253 raw_spin_lock(&rq->lock);
5cbd54ef 5254
5e1576ed 5255 __sched_fork(0, idle);
06b83b5f 5256 idle->state = TASK_RUNNING;
dd41f596 5257 idle->se.exec_start = sched_clock();
c1de45ca 5258 idle->flags |= PF_IDLE;
dd41f596 5259
e1b77c92
MR
5260 kasan_unpoison_task_stack(idle);
5261
de9b8f5d
PZ
5262#ifdef CONFIG_SMP
5263 /*
5264 * Its possible that init_idle() gets called multiple times on a task,
5265 * in that case do_set_cpus_allowed() will not do the right thing.
5266 *
5267 * And since this is boot we can forgo the serialization.
5268 */
5269 set_cpus_allowed_common(idle, cpumask_of(cpu));
5270#endif
6506cf6c
PZ
5271 /*
5272 * We're having a chicken and egg problem, even though we are
d1ccc66d 5273 * holding rq->lock, the CPU isn't yet set to this CPU so the
6506cf6c
PZ
5274 * lockdep check in task_group() will fail.
5275 *
5276 * Similar case to sched_fork(). / Alternatively we could
5277 * use task_rq_lock() here and obtain the other rq->lock.
5278 *
5279 * Silence PROVE_RCU
5280 */
5281 rcu_read_lock();
dd41f596 5282 __set_task_cpu(idle, cpu);
6506cf6c 5283 rcu_read_unlock();
1da177e4 5284
1da177e4 5285 rq->curr = rq->idle = idle;
da0c1e65 5286 idle->on_rq = TASK_ON_RQ_QUEUED;
de9b8f5d 5287#ifdef CONFIG_SMP
3ca7a440 5288 idle->on_cpu = 1;
4866cde0 5289#endif
25834c73
PZ
5290 raw_spin_unlock(&rq->lock);
5291 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
1da177e4
LT
5292
5293 /* Set the preempt count _outside_ the spinlocks! */
01028747 5294 init_idle_preempt_count(idle, cpu);
55cd5340 5295
dd41f596
IM
5296 /*
5297 * The idle tasks have their own, simple scheduling class:
5298 */
5299 idle->sched_class = &idle_sched_class;
868baf07 5300 ftrace_graph_init_idle_task(idle, cpu);
45eacc69 5301 vtime_init_idle(idle, cpu);
de9b8f5d 5302#ifdef CONFIG_SMP
f1c6f1a7
CE
5303 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5304#endif
19978ca6
IM
5305}
5306
e1d4eeec
NP
5307#ifdef CONFIG_SMP
5308
f82f8042
JL
5309int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5310 const struct cpumask *trial)
5311{
06a76fe0 5312 int ret = 1;
f82f8042 5313
bb2bc55a
MG
5314 if (!cpumask_weight(cur))
5315 return ret;
5316
06a76fe0 5317 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
f82f8042
JL
5318
5319 return ret;
5320}
5321
7f51412a
JL
5322int task_can_attach(struct task_struct *p,
5323 const struct cpumask *cs_cpus_allowed)
5324{
5325 int ret = 0;
5326
5327 /*
5328 * Kthreads which disallow setaffinity shouldn't be moved
d1ccc66d 5329 * to a new cpuset; we don't want to change their CPU
7f51412a
JL
5330 * affinity and isolating such threads by their set of
5331 * allowed nodes is unnecessary. Thus, cpusets are not
5332 * applicable for such threads. This prevents checking for
5333 * success of set_cpus_allowed_ptr() on all attached tasks
5334 * before cpus_allowed may be changed.
5335 */
5336 if (p->flags & PF_NO_SETAFFINITY) {
5337 ret = -EINVAL;
5338 goto out;
5339 }
5340
7f51412a 5341 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
06a76fe0
NP
5342 cs_cpus_allowed))
5343 ret = dl_task_can_attach(p, cs_cpus_allowed);
7f51412a 5344
7f51412a
JL
5345out:
5346 return ret;
5347}
5348
f2cb1360 5349bool sched_smp_initialized __read_mostly;
e26fbffd 5350
e6628d5b
MG
5351#ifdef CONFIG_NUMA_BALANCING
5352/* Migrate current task p to target_cpu */
5353int migrate_task_to(struct task_struct *p, int target_cpu)
5354{
5355 struct migration_arg arg = { p, target_cpu };
5356 int curr_cpu = task_cpu(p);
5357
5358 if (curr_cpu == target_cpu)
5359 return 0;
5360
0c98d344 5361 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
e6628d5b
MG
5362 return -EINVAL;
5363
5364 /* TODO: This is not properly updating schedstats */
5365
286549dc 5366 trace_sched_move_numa(p, curr_cpu, target_cpu);
e6628d5b
MG
5367 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5368}
0ec8aa00
PZ
5369
5370/*
5371 * Requeue a task on a given node and accurately track the number of NUMA
5372 * tasks on the runqueues
5373 */
5374void sched_setnuma(struct task_struct *p, int nid)
5375{
da0c1e65 5376 bool queued, running;
eb580751
PZ
5377 struct rq_flags rf;
5378 struct rq *rq;
0ec8aa00 5379
eb580751 5380 rq = task_rq_lock(p, &rf);
da0c1e65 5381 queued = task_on_rq_queued(p);
0ec8aa00
PZ
5382 running = task_current(rq, p);
5383
da0c1e65 5384 if (queued)
1de64443 5385 dequeue_task(rq, p, DEQUEUE_SAVE);
0ec8aa00 5386 if (running)
f3cd1c4e 5387 put_prev_task(rq, p);
0ec8aa00
PZ
5388
5389 p->numa_preferred_nid = nid;
0ec8aa00 5390
da0c1e65 5391 if (queued)
7134b3e9 5392 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 5393 if (running)
b2bf6c31 5394 set_curr_task(rq, p);
eb580751 5395 task_rq_unlock(rq, p, &rf);
0ec8aa00 5396}
5cc389bc 5397#endif /* CONFIG_NUMA_BALANCING */
f7b4cddc 5398
1da177e4 5399#ifdef CONFIG_HOTPLUG_CPU
054b9108 5400/*
d1ccc66d 5401 * Ensure that the idle task is using init_mm right before its CPU goes
48c5ccae 5402 * offline.
054b9108 5403 */
48c5ccae 5404void idle_task_exit(void)
1da177e4 5405{
48c5ccae 5406 struct mm_struct *mm = current->active_mm;
e76bd8d9 5407
48c5ccae 5408 BUG_ON(cpu_online(smp_processor_id()));
e76bd8d9 5409
a53efe5f 5410 if (mm != &init_mm) {
252d2a41 5411 switch_mm(mm, &init_mm, current);
a53efe5f
MS
5412 finish_arch_post_lock_switch();
5413 }
48c5ccae 5414 mmdrop(mm);
1da177e4
LT
5415}
5416
5417/*
5d180232
PZ
5418 * Since this CPU is going 'away' for a while, fold any nr_active delta
5419 * we might have. Assumes we're called after migrate_tasks() so that the
d60585c5
TG
5420 * nr_active count is stable. We need to take the teardown thread which
5421 * is calling this into account, so we hand in adjust = 1 to the load
5422 * calculation.
5d180232
PZ
5423 *
5424 * Also see the comment "Global load-average calculations".
1da177e4 5425 */
5d180232 5426static void calc_load_migrate(struct rq *rq)
1da177e4 5427{
d60585c5 5428 long delta = calc_load_fold_active(rq, 1);
5d180232
PZ
5429 if (delta)
5430 atomic_long_add(delta, &calc_load_tasks);
1da177e4
LT
5431}
5432
3f1d2a31
PZ
5433static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5434{
5435}
5436
5437static const struct sched_class fake_sched_class = {
5438 .put_prev_task = put_prev_task_fake,
5439};
5440
5441static struct task_struct fake_task = {
5442 /*
5443 * Avoid pull_{rt,dl}_task()
5444 */
5445 .prio = MAX_PRIO + 1,
5446 .sched_class = &fake_sched_class,
5447};
5448
48f24c4d 5449/*
48c5ccae
PZ
5450 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5451 * try_to_wake_up()->select_task_rq().
5452 *
5453 * Called with rq->lock held even though we'er in stop_machine() and
5454 * there's no concurrency possible, we hold the required locks anyway
5455 * because of lock validation efforts.
1da177e4 5456 */
8a8c69c3 5457static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
1da177e4 5458{
5e16bbc2 5459 struct rq *rq = dead_rq;
48c5ccae 5460 struct task_struct *next, *stop = rq->stop;
8a8c69c3 5461 struct rq_flags orf = *rf;
48c5ccae 5462 int dest_cpu;
1da177e4
LT
5463
5464 /*
48c5ccae
PZ
5465 * Fudge the rq selection such that the below task selection loop
5466 * doesn't get stuck on the currently eligible stop task.
5467 *
5468 * We're currently inside stop_machine() and the rq is either stuck
5469 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5470 * either way we should never end up calling schedule() until we're
5471 * done here.
1da177e4 5472 */
48c5ccae 5473 rq->stop = NULL;
48f24c4d 5474
77bd3970
FW
5475 /*
5476 * put_prev_task() and pick_next_task() sched
5477 * class method both need to have an up-to-date
5478 * value of rq->clock[_task]
5479 */
5480 update_rq_clock(rq);
5481
5e16bbc2 5482 for (;;) {
48c5ccae
PZ
5483 /*
5484 * There's this thread running, bail when that's the only
d1ccc66d 5485 * remaining thread:
48c5ccae
PZ
5486 */
5487 if (rq->nr_running == 1)
dd41f596 5488 break;
48c5ccae 5489
cbce1a68 5490 /*
d1ccc66d 5491 * pick_next_task() assumes pinned rq->lock:
cbce1a68 5492 */
8a8c69c3 5493 next = pick_next_task(rq, &fake_task, rf);
48c5ccae 5494 BUG_ON(!next);
5b713a3d 5495 put_prev_task(rq, next);
e692ab53 5496
5473e0cc
WL
5497 /*
5498 * Rules for changing task_struct::cpus_allowed are holding
5499 * both pi_lock and rq->lock, such that holding either
5500 * stabilizes the mask.
5501 *
5502 * Drop rq->lock is not quite as disastrous as it usually is
5503 * because !cpu_active at this point, which means load-balance
5504 * will not interfere. Also, stop-machine.
5505 */
8a8c69c3 5506 rq_unlock(rq, rf);
5473e0cc 5507 raw_spin_lock(&next->pi_lock);
8a8c69c3 5508 rq_relock(rq, rf);
5473e0cc
WL
5509
5510 /*
5511 * Since we're inside stop-machine, _nothing_ should have
5512 * changed the task, WARN if weird stuff happened, because in
5513 * that case the above rq->lock drop is a fail too.
5514 */
5515 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5516 raw_spin_unlock(&next->pi_lock);
5517 continue;
5518 }
5519
48c5ccae 5520 /* Find suitable destination for @next, with force if needed. */
5e16bbc2 5521 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
8a8c69c3 5522 rq = __migrate_task(rq, rf, next, dest_cpu);
5e16bbc2 5523 if (rq != dead_rq) {
8a8c69c3 5524 rq_unlock(rq, rf);
5e16bbc2 5525 rq = dead_rq;
8a8c69c3
PZ
5526 *rf = orf;
5527 rq_relock(rq, rf);
5e16bbc2 5528 }
5473e0cc 5529 raw_spin_unlock(&next->pi_lock);
1da177e4 5530 }
dce48a84 5531
48c5ccae 5532 rq->stop = stop;
dce48a84 5533}
1da177e4
LT
5534#endif /* CONFIG_HOTPLUG_CPU */
5535
f2cb1360 5536void set_rq_online(struct rq *rq)
1f11eb6a
GH
5537{
5538 if (!rq->online) {
5539 const struct sched_class *class;
5540
c6c4927b 5541 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5542 rq->online = 1;
5543
5544 for_each_class(class) {
5545 if (class->rq_online)
5546 class->rq_online(rq);
5547 }
5548 }
5549}
5550
f2cb1360 5551void set_rq_offline(struct rq *rq)
1f11eb6a
GH
5552{
5553 if (rq->online) {
5554 const struct sched_class *class;
5555
5556 for_each_class(class) {
5557 if (class->rq_offline)
5558 class->rq_offline(rq);
5559 }
5560
c6c4927b 5561 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5562 rq->online = 0;
5563 }
5564}
5565
9cf7243d 5566static void set_cpu_rq_start_time(unsigned int cpu)
1da177e4 5567{
969c7921 5568 struct rq *rq = cpu_rq(cpu);
1da177e4 5569
a803f026
CM
5570 rq->age_stamp = sched_clock_cpu(cpu);
5571}
5572
d1ccc66d
IM
5573/*
5574 * used to mark begin/end of suspend/resume:
5575 */
5576static int num_cpus_frozen;
d35be8ba 5577
1da177e4 5578/*
3a101d05
TH
5579 * Update cpusets according to cpu_active mask. If cpusets are
5580 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5581 * around partition_sched_domains().
d35be8ba
SB
5582 *
5583 * If we come here as part of a suspend/resume, don't touch cpusets because we
5584 * want to restore it back to its original state upon resume anyway.
1da177e4 5585 */
40190a78 5586static void cpuset_cpu_active(void)
e761b772 5587{
40190a78 5588 if (cpuhp_tasks_frozen) {
d35be8ba
SB
5589 /*
5590 * num_cpus_frozen tracks how many CPUs are involved in suspend
5591 * resume sequence. As long as this is not the last online
5592 * operation in the resume sequence, just build a single sched
5593 * domain, ignoring cpusets.
5594 */
50e76632
PZ
5595 partition_sched_domains(1, NULL, NULL);
5596 if (--num_cpus_frozen)
135fb3e1 5597 return;
d35be8ba
SB
5598 /*
5599 * This is the last CPU online operation. So fall through and
5600 * restore the original sched domains by considering the
5601 * cpuset configurations.
5602 */
50e76632 5603 cpuset_force_rebuild();
3a101d05 5604 }
30e03acd 5605 cpuset_update_active_cpus();
3a101d05 5606}
e761b772 5607
40190a78 5608static int cpuset_cpu_inactive(unsigned int cpu)
3a101d05 5609{
40190a78 5610 if (!cpuhp_tasks_frozen) {
06a76fe0 5611 if (dl_cpu_busy(cpu))
135fb3e1 5612 return -EBUSY;
30e03acd 5613 cpuset_update_active_cpus();
135fb3e1 5614 } else {
d35be8ba
SB
5615 num_cpus_frozen++;
5616 partition_sched_domains(1, NULL, NULL);
e761b772 5617 }
135fb3e1 5618 return 0;
e761b772 5619}
e761b772 5620
40190a78 5621int sched_cpu_activate(unsigned int cpu)
135fb3e1 5622{
7d976699 5623 struct rq *rq = cpu_rq(cpu);
8a8c69c3 5624 struct rq_flags rf;
7d976699 5625
40190a78 5626 set_cpu_active(cpu, true);
135fb3e1 5627
40190a78 5628 if (sched_smp_initialized) {
135fb3e1 5629 sched_domains_numa_masks_set(cpu);
40190a78 5630 cpuset_cpu_active();
e761b772 5631 }
7d976699
TG
5632
5633 /*
5634 * Put the rq online, if not already. This happens:
5635 *
5636 * 1) In the early boot process, because we build the real domains
d1ccc66d 5637 * after all CPUs have been brought up.
7d976699
TG
5638 *
5639 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5640 * domains.
5641 */
8a8c69c3 5642 rq_lock_irqsave(rq, &rf);
7d976699
TG
5643 if (rq->rd) {
5644 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5645 set_rq_online(rq);
5646 }
8a8c69c3 5647 rq_unlock_irqrestore(rq, &rf);
7d976699
TG
5648
5649 update_max_interval();
5650
40190a78 5651 return 0;
135fb3e1
TG
5652}
5653
40190a78 5654int sched_cpu_deactivate(unsigned int cpu)
135fb3e1 5655{
135fb3e1
TG
5656 int ret;
5657
40190a78 5658 set_cpu_active(cpu, false);
b2454caa
PZ
5659 /*
5660 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5661 * users of this state to go away such that all new such users will
5662 * observe it.
5663 *
b2454caa
PZ
5664 * Do sync before park smpboot threads to take care the rcu boost case.
5665 */
d7d34d5e 5666 synchronize_rcu_mult(call_rcu, call_rcu_sched);
40190a78
TG
5667
5668 if (!sched_smp_initialized)
5669 return 0;
5670
5671 ret = cpuset_cpu_inactive(cpu);
5672 if (ret) {
5673 set_cpu_active(cpu, true);
5674 return ret;
135fb3e1 5675 }
40190a78
TG
5676 sched_domains_numa_masks_clear(cpu);
5677 return 0;
135fb3e1
TG
5678}
5679
94baf7a5
TG
5680static void sched_rq_cpu_starting(unsigned int cpu)
5681{
5682 struct rq *rq = cpu_rq(cpu);
5683
5684 rq->calc_load_update = calc_load_update;
94baf7a5
TG
5685 update_max_interval();
5686}
5687
135fb3e1
TG
5688int sched_cpu_starting(unsigned int cpu)
5689{
5690 set_cpu_rq_start_time(cpu);
94baf7a5 5691 sched_rq_cpu_starting(cpu);
135fb3e1 5692 return 0;
e761b772 5693}
e761b772 5694
f2785ddb
TG
5695#ifdef CONFIG_HOTPLUG_CPU
5696int sched_cpu_dying(unsigned int cpu)
5697{
5698 struct rq *rq = cpu_rq(cpu);
8a8c69c3 5699 struct rq_flags rf;
f2785ddb
TG
5700
5701 /* Handle pending wakeups and then migrate everything off */
5702 sched_ttwu_pending();
8a8c69c3
PZ
5703
5704 rq_lock_irqsave(rq, &rf);
f2785ddb
TG
5705 if (rq->rd) {
5706 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5707 set_rq_offline(rq);
5708 }
8a8c69c3 5709 migrate_tasks(rq, &rf);
f2785ddb 5710 BUG_ON(rq->nr_running != 1);
8a8c69c3
PZ
5711 rq_unlock_irqrestore(rq, &rf);
5712
f2785ddb
TG
5713 calc_load_migrate(rq);
5714 update_max_interval();
20a5c8cc 5715 nohz_balance_exit_idle(cpu);
e5ef27d0 5716 hrtick_clear(rq);
f2785ddb
TG
5717 return 0;
5718}
5719#endif
5720
1b568f0a
PZ
5721#ifdef CONFIG_SCHED_SMT
5722DEFINE_STATIC_KEY_FALSE(sched_smt_present);
5723
5724static void sched_init_smt(void)
5725{
5726 /*
5727 * We've enumerated all CPUs and will assume that if any CPU
5728 * has SMT siblings, CPU0 will too.
5729 */
5730 if (cpumask_weight(cpu_smt_mask(0)) > 1)
5731 static_branch_enable(&sched_smt_present);
5732}
5733#else
5734static inline void sched_init_smt(void) { }
5735#endif
5736
1da177e4
LT
5737void __init sched_init_smp(void)
5738{
cb83b629
PZ
5739 sched_init_numa();
5740
6acce3ef
PZ
5741 /*
5742 * There's no userspace yet to cause hotplug operations; hence all the
d1ccc66d 5743 * CPU masks are stable and all blatant races in the below code cannot
6acce3ef
PZ
5744 * happen.
5745 */
712555ee 5746 mutex_lock(&sched_domains_mutex);
8d5dc512 5747 sched_init_domains(cpu_active_mask);
712555ee 5748 mutex_unlock(&sched_domains_mutex);
e761b772 5749
5c1e1767 5750 /* Move init over to a non-isolated CPU */
edb93821 5751 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5c1e1767 5752 BUG();
19978ca6 5753 sched_init_granularity();
4212823f 5754
0e3900e6 5755 init_sched_rt_class();
1baca4ce 5756 init_sched_dl_class();
1b568f0a
PZ
5757
5758 sched_init_smt();
5759
e26fbffd 5760 sched_smp_initialized = true;
1da177e4 5761}
e26fbffd
TG
5762
5763static int __init migration_init(void)
5764{
94baf7a5 5765 sched_rq_cpu_starting(smp_processor_id());
e26fbffd 5766 return 0;
1da177e4 5767}
e26fbffd
TG
5768early_initcall(migration_init);
5769
1da177e4
LT
5770#else
5771void __init sched_init_smp(void)
5772{
19978ca6 5773 sched_init_granularity();
1da177e4
LT
5774}
5775#endif /* CONFIG_SMP */
5776
5777int in_sched_functions(unsigned long addr)
5778{
1da177e4
LT
5779 return in_lock_functions(addr) ||
5780 (addr >= (unsigned long)__sched_text_start
5781 && addr < (unsigned long)__sched_text_end);
5782}
5783
029632fb 5784#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
5785/*
5786 * Default task group.
5787 * Every task in system belongs to this group at bootup.
5788 */
029632fb 5789struct task_group root_task_group;
35cf4e50 5790LIST_HEAD(task_groups);
b0367629
WL
5791
5792/* Cacheline aligned slab cache for task_group */
5793static struct kmem_cache *task_group_cache __read_mostly;
052f1dc7 5794#endif
6f505b16 5795
e6252c3e 5796DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
10e2f1ac 5797DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
6f505b16 5798
1da177e4
LT
5799void __init sched_init(void)
5800{
dd41f596 5801 int i, j;
434d53b0
MT
5802 unsigned long alloc_size = 0, ptr;
5803
9881b024 5804 sched_clock_init();
5822a454 5805 wait_bit_init();
9dcb8b68 5806
434d53b0
MT
5807#ifdef CONFIG_FAIR_GROUP_SCHED
5808 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5809#endif
5810#ifdef CONFIG_RT_GROUP_SCHED
5811 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5812#endif
434d53b0 5813 if (alloc_size) {
36b7b6d4 5814 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
434d53b0
MT
5815
5816#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 5817 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
5818 ptr += nr_cpu_ids * sizeof(void **);
5819
07e06b01 5820 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 5821 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 5822
6d6bc0ad 5823#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 5824#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5825 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
5826 ptr += nr_cpu_ids * sizeof(void **);
5827
07e06b01 5828 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
5829 ptr += nr_cpu_ids * sizeof(void **);
5830
6d6bc0ad 5831#endif /* CONFIG_RT_GROUP_SCHED */
b74e6278 5832 }
df7c8e84 5833#ifdef CONFIG_CPUMASK_OFFSTACK
b74e6278
AT
5834 for_each_possible_cpu(i) {
5835 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5836 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
10e2f1ac
PZ
5837 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5838 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
434d53b0 5839 }
b74e6278 5840#endif /* CONFIG_CPUMASK_OFFSTACK */
dd41f596 5841
d1ccc66d
IM
5842 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5843 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
332ac17e 5844
57d885fe
GH
5845#ifdef CONFIG_SMP
5846 init_defrootdomain();
5847#endif
5848
d0b27fa7 5849#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5850 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 5851 global_rt_period(), global_rt_runtime());
6d6bc0ad 5852#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 5853
7c941438 5854#ifdef CONFIG_CGROUP_SCHED
b0367629
WL
5855 task_group_cache = KMEM_CACHE(task_group, 0);
5856
07e06b01
YZ
5857 list_add(&root_task_group.list, &task_groups);
5858 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 5859 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 5860 autogroup_init(&init_task);
7c941438 5861#endif /* CONFIG_CGROUP_SCHED */
6f505b16 5862
0a945022 5863 for_each_possible_cpu(i) {
70b97a7f 5864 struct rq *rq;
1da177e4
LT
5865
5866 rq = cpu_rq(i);
05fa785c 5867 raw_spin_lock_init(&rq->lock);
7897986b 5868 rq->nr_running = 0;
dce48a84
TG
5869 rq->calc_load_active = 0;
5870 rq->calc_load_update = jiffies + LOAD_FREQ;
acb5a9ba 5871 init_cfs_rq(&rq->cfs);
07c54f7a
AV
5872 init_rt_rq(&rq->rt);
5873 init_dl_rq(&rq->dl);
dd41f596 5874#ifdef CONFIG_FAIR_GROUP_SCHED
029632fb 5875 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6f505b16 5876 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9c2791f9 5877 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
354d60c2 5878 /*
d1ccc66d 5879 * How much CPU bandwidth does root_task_group get?
354d60c2
DG
5880 *
5881 * In case of task-groups formed thr' the cgroup filesystem, it
d1ccc66d
IM
5882 * gets 100% of the CPU resources in the system. This overall
5883 * system CPU resource is divided among the tasks of
07e06b01 5884 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
5885 * based on each entity's (task or task-group's) weight
5886 * (se->load.weight).
5887 *
07e06b01 5888 * In other words, if root_task_group has 10 tasks of weight
354d60c2 5889 * 1024) and two child groups A0 and A1 (of weight 1024 each),
d1ccc66d 5890 * then A0's share of the CPU resource is:
354d60c2 5891 *
0d905bca 5892 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 5893 *
07e06b01
YZ
5894 * We achieve this by letting root_task_group's tasks sit
5895 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 5896 */
ab84d31e 5897 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
07e06b01 5898 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
5899#endif /* CONFIG_FAIR_GROUP_SCHED */
5900
5901 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 5902#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5903 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 5904#endif
1da177e4 5905
dd41f596
IM
5906 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
5907 rq->cpu_load[j] = 0;
fdf3e95d 5908
1da177e4 5909#ifdef CONFIG_SMP
41c7ce9a 5910 rq->sd = NULL;
57d885fe 5911 rq->rd = NULL;
ca6d75e6 5912 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
e3fca9e7 5913 rq->balance_callback = NULL;
1da177e4 5914 rq->active_balance = 0;
dd41f596 5915 rq->next_balance = jiffies;
1da177e4 5916 rq->push_cpu = 0;
0a2966b4 5917 rq->cpu = i;
1f11eb6a 5918 rq->online = 0;
eae0c9df
MG
5919 rq->idle_stamp = 0;
5920 rq->avg_idle = 2*sysctl_sched_migration_cost;
9bd721c5 5921 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
367456c7
PZ
5922
5923 INIT_LIST_HEAD(&rq->cfs_tasks);
5924
dc938520 5925 rq_attach_root(rq, &def_root_domain);
3451d024 5926#ifdef CONFIG_NO_HZ_COMMON
9fd81dd5 5927 rq->last_load_update_tick = jiffies;
1c792db7 5928 rq->nohz_flags = 0;
83cd4fe2 5929#endif
265f22a9
FW
5930#ifdef CONFIG_NO_HZ_FULL
5931 rq->last_sched_tick = 0;
5932#endif
9fd81dd5 5933#endif /* CONFIG_SMP */
8f4d37ec 5934 init_rq_hrtick(rq);
1da177e4 5935 atomic_set(&rq->nr_iowait, 0);
1da177e4
LT
5936 }
5937
9059393e 5938 set_load_weight(&init_task, false);
b50f60ce 5939
1da177e4
LT
5940 /*
5941 * The boot idle thread does lazy MMU switching as well:
5942 */
f1f10076 5943 mmgrab(&init_mm);
1da177e4
LT
5944 enter_lazy_tlb(&init_mm, current);
5945
5946 /*
5947 * Make us the idle thread. Technically, schedule() should not be
5948 * called from this thread, however somewhere below it might be,
5949 * but because we are the idle thread, we just pick up running again
5950 * when this runqueue becomes "idle".
5951 */
5952 init_idle(current, smp_processor_id());
dce48a84
TG
5953
5954 calc_load_update = jiffies + LOAD_FREQ;
5955
bf4d83f6 5956#ifdef CONFIG_SMP
29d5e047 5957 idle_thread_set_boot_cpu();
9cf7243d 5958 set_cpu_rq_start_time(smp_processor_id());
029632fb
PZ
5959#endif
5960 init_sched_fair_class();
6a7b3dc3 5961
4698f88c
JP
5962 init_schedstats();
5963
6892b75e 5964 scheduler_running = 1;
1da177e4
LT
5965}
5966
d902db1e 5967#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2
FW
5968static inline int preempt_count_equals(int preempt_offset)
5969{
da7142e2 5970 int nested = preempt_count() + rcu_preempt_depth();
e4aafea2 5971
4ba8216c 5972 return (nested == preempt_offset);
e4aafea2
FW
5973}
5974
d894837f 5975void __might_sleep(const char *file, int line, int preempt_offset)
1da177e4 5976{
8eb23b9f
PZ
5977 /*
5978 * Blocking primitives will set (and therefore destroy) current->state,
5979 * since we will exit with TASK_RUNNING make sure we enter with it,
5980 * otherwise we will destroy state.
5981 */
00845eb9 5982 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
8eb23b9f
PZ
5983 "do not call blocking ops when !TASK_RUNNING; "
5984 "state=%lx set at [<%p>] %pS\n",
5985 current->state,
5986 (void *)current->task_state_change,
00845eb9 5987 (void *)current->task_state_change);
8eb23b9f 5988
3427445a
PZ
5989 ___might_sleep(file, line, preempt_offset);
5990}
5991EXPORT_SYMBOL(__might_sleep);
5992
5993void ___might_sleep(const char *file, int line, int preempt_offset)
1da177e4 5994{
d1ccc66d
IM
5995 /* Ratelimiting timestamp: */
5996 static unsigned long prev_jiffy;
5997
d1c6d149 5998 unsigned long preempt_disable_ip;
1da177e4 5999
d1ccc66d
IM
6000 /* WARN_ON_ONCE() by default, no rate limit required: */
6001 rcu_sleep_check();
6002
db273be2
TG
6003 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6004 !is_idle_task(current)) ||
1c3c5eab
TG
6005 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6006 oops_in_progress)
aef745fc 6007 return;
1c3c5eab 6008
aef745fc
IM
6009 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6010 return;
6011 prev_jiffy = jiffies;
6012
d1ccc66d 6013 /* Save this before calling printk(), since that will clobber it: */
d1c6d149
VN
6014 preempt_disable_ip = get_preempt_disable_ip(current);
6015
3df0fc5b
PZ
6016 printk(KERN_ERR
6017 "BUG: sleeping function called from invalid context at %s:%d\n",
6018 file, line);
6019 printk(KERN_ERR
6020 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6021 in_atomic(), irqs_disabled(),
6022 current->pid, current->comm);
aef745fc 6023
a8b686b3
ES
6024 if (task_stack_end_corrupted(current))
6025 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6026
aef745fc
IM
6027 debug_show_held_locks(current);
6028 if (irqs_disabled())
6029 print_irqtrace_events(current);
d1c6d149
VN
6030 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6031 && !preempt_count_equals(preempt_offset)) {
8f47b187 6032 pr_err("Preemption disabled at:");
d1c6d149 6033 print_ip_sym(preempt_disable_ip);
8f47b187
TG
6034 pr_cont("\n");
6035 }
aef745fc 6036 dump_stack();
f0b22e39 6037 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
1da177e4 6038}
3427445a 6039EXPORT_SYMBOL(___might_sleep);
1da177e4
LT
6040#endif
6041
6042#ifdef CONFIG_MAGIC_SYSRQ
dbc7f069 6043void normalize_rt_tasks(void)
3a5e4dc1 6044{
dbc7f069 6045 struct task_struct *g, *p;
d50dde5a
DF
6046 struct sched_attr attr = {
6047 .sched_policy = SCHED_NORMAL,
6048 };
1da177e4 6049
3472eaa1 6050 read_lock(&tasklist_lock);
5d07f420 6051 for_each_process_thread(g, p) {
178be793
IM
6052 /*
6053 * Only normalize user tasks:
6054 */
3472eaa1 6055 if (p->flags & PF_KTHREAD)
178be793
IM
6056 continue;
6057
4fa8d299
JP
6058 p->se.exec_start = 0;
6059 schedstat_set(p->se.statistics.wait_start, 0);
6060 schedstat_set(p->se.statistics.sleep_start, 0);
6061 schedstat_set(p->se.statistics.block_start, 0);
dd41f596 6062
aab03e05 6063 if (!dl_task(p) && !rt_task(p)) {
dd41f596
IM
6064 /*
6065 * Renice negative nice level userspace
6066 * tasks back to 0:
6067 */
3472eaa1 6068 if (task_nice(p) < 0)
dd41f596 6069 set_user_nice(p, 0);
1da177e4 6070 continue;
dd41f596 6071 }
1da177e4 6072
dbc7f069 6073 __sched_setscheduler(p, &attr, false, false);
5d07f420 6074 }
3472eaa1 6075 read_unlock(&tasklist_lock);
1da177e4
LT
6076}
6077
6078#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 6079
67fc4e0c 6080#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 6081/*
67fc4e0c 6082 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
6083 *
6084 * They can only be called when the whole system has been
6085 * stopped - every CPU needs to be quiescent, and no scheduling
6086 * activity can take place. Using them for anything else would
6087 * be a serious bug, and as a result, they aren't even visible
6088 * under any other configuration.
6089 */
6090
6091/**
d1ccc66d 6092 * curr_task - return the current task for a given CPU.
1df5c10a
LT
6093 * @cpu: the processor in question.
6094 *
6095 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
e69f6186
YB
6096 *
6097 * Return: The current task for @cpu.
1df5c10a 6098 */
36c8b586 6099struct task_struct *curr_task(int cpu)
1df5c10a
LT
6100{
6101 return cpu_curr(cpu);
6102}
6103
67fc4e0c
JW
6104#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6105
6106#ifdef CONFIG_IA64
1df5c10a 6107/**
d1ccc66d 6108 * set_curr_task - set the current task for a given CPU.
1df5c10a
LT
6109 * @cpu: the processor in question.
6110 * @p: the task pointer to set.
6111 *
6112 * Description: This function must only be used when non-maskable interrupts
41a2d6cf 6113 * are serviced on a separate stack. It allows the architecture to switch the
d1ccc66d 6114 * notion of the current task on a CPU in a non-blocking manner. This function
1df5c10a
LT
6115 * must be called with all CPU's synchronized, and interrupts disabled, the
6116 * and caller must save the original value of the current task (see
6117 * curr_task() above) and restore that value before reenabling interrupts and
6118 * re-starting the system.
6119 *
6120 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6121 */
a458ae2e 6122void ia64_set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
6123{
6124 cpu_curr(cpu) = p;
6125}
6126
6127#endif
29f59db3 6128
7c941438 6129#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
6130/* task_group_lock serializes the addition/removal of task groups */
6131static DEFINE_SPINLOCK(task_group_lock);
6132
2f5177f0 6133static void sched_free_group(struct task_group *tg)
bccbe08a
PZ
6134{
6135 free_fair_sched_group(tg);
6136 free_rt_sched_group(tg);
e9aa1dd1 6137 autogroup_free(tg);
b0367629 6138 kmem_cache_free(task_group_cache, tg);
bccbe08a
PZ
6139}
6140
6141/* allocate runqueue etc for a new task group */
ec7dc8ac 6142struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
6143{
6144 struct task_group *tg;
bccbe08a 6145
b0367629 6146 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
bccbe08a
PZ
6147 if (!tg)
6148 return ERR_PTR(-ENOMEM);
6149
ec7dc8ac 6150 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
6151 goto err;
6152
ec7dc8ac 6153 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
6154 goto err;
6155
ace783b9
LZ
6156 return tg;
6157
6158err:
2f5177f0 6159 sched_free_group(tg);
ace783b9
LZ
6160 return ERR_PTR(-ENOMEM);
6161}
6162
6163void sched_online_group(struct task_group *tg, struct task_group *parent)
6164{
6165 unsigned long flags;
6166
8ed36996 6167 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 6168 list_add_rcu(&tg->list, &task_groups);
f473aa5e 6169
d1ccc66d
IM
6170 /* Root should already exist: */
6171 WARN_ON(!parent);
f473aa5e
PZ
6172
6173 tg->parent = parent;
f473aa5e 6174 INIT_LIST_HEAD(&tg->children);
09f2724a 6175 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 6176 spin_unlock_irqrestore(&task_group_lock, flags);
8663e24d
PZ
6177
6178 online_fair_sched_group(tg);
29f59db3
SV
6179}
6180
9b5b7751 6181/* rcu callback to free various structures associated with a task group */
2f5177f0 6182static void sched_free_group_rcu(struct rcu_head *rhp)
29f59db3 6183{
d1ccc66d 6184 /* Now it should be safe to free those cfs_rqs: */
2f5177f0 6185 sched_free_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
6186}
6187
4cf86d77 6188void sched_destroy_group(struct task_group *tg)
ace783b9 6189{
d1ccc66d 6190 /* Wait for possible concurrent references to cfs_rqs complete: */
2f5177f0 6191 call_rcu(&tg->rcu, sched_free_group_rcu);
ace783b9
LZ
6192}
6193
6194void sched_offline_group(struct task_group *tg)
29f59db3 6195{
8ed36996 6196 unsigned long flags;
29f59db3 6197
d1ccc66d 6198 /* End participation in shares distribution: */
6fe1f348 6199 unregister_fair_sched_group(tg);
3d4b47b4
PZ
6200
6201 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 6202 list_del_rcu(&tg->list);
f473aa5e 6203 list_del_rcu(&tg->siblings);
8ed36996 6204 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
6205}
6206
ea86cb4b 6207static void sched_change_group(struct task_struct *tsk, int type)
29f59db3 6208{
8323f26c 6209 struct task_group *tg;
29f59db3 6210
f7b8a47d
KT
6211 /*
6212 * All callers are synchronized by task_rq_lock(); we do not use RCU
6213 * which is pointless here. Thus, we pass "true" to task_css_check()
6214 * to prevent lockdep warnings.
6215 */
6216 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8323f26c
PZ
6217 struct task_group, css);
6218 tg = autogroup_task_group(tsk, tg);
6219 tsk->sched_task_group = tg;
6220
810b3817 6221#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
6222 if (tsk->sched_class->task_change_group)
6223 tsk->sched_class->task_change_group(tsk, type);
b2b5ce02 6224 else
810b3817 6225#endif
b2b5ce02 6226 set_task_rq(tsk, task_cpu(tsk));
ea86cb4b
VG
6227}
6228
6229/*
6230 * Change task's runqueue when it moves between groups.
6231 *
6232 * The caller of this function should have put the task in its new group by
6233 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6234 * its new group.
6235 */
6236void sched_move_task(struct task_struct *tsk)
6237{
7a57f32a
PZ
6238 int queued, running, queue_flags =
6239 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
ea86cb4b
VG
6240 struct rq_flags rf;
6241 struct rq *rq;
6242
6243 rq = task_rq_lock(tsk, &rf);
1b1d6225 6244 update_rq_clock(rq);
ea86cb4b
VG
6245
6246 running = task_current(rq, tsk);
6247 queued = task_on_rq_queued(tsk);
6248
6249 if (queued)
7a57f32a 6250 dequeue_task(rq, tsk, queue_flags);
bb3bac2c 6251 if (running)
ea86cb4b
VG
6252 put_prev_task(rq, tsk);
6253
6254 sched_change_group(tsk, TASK_MOVE_GROUP);
810b3817 6255
da0c1e65 6256 if (queued)
7a57f32a 6257 enqueue_task(rq, tsk, queue_flags);
bb3bac2c 6258 if (running)
b2bf6c31 6259 set_curr_task(rq, tsk);
29f59db3 6260
eb580751 6261 task_rq_unlock(rq, tsk, &rf);
29f59db3 6262}
68318b8e 6263
a7c6d554 6264static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
68318b8e 6265{
a7c6d554 6266 return css ? container_of(css, struct task_group, css) : NULL;
68318b8e
SV
6267}
6268
eb95419b
TH
6269static struct cgroup_subsys_state *
6270cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
68318b8e 6271{
eb95419b
TH
6272 struct task_group *parent = css_tg(parent_css);
6273 struct task_group *tg;
68318b8e 6274
eb95419b 6275 if (!parent) {
68318b8e 6276 /* This is early initialization for the top cgroup */
07e06b01 6277 return &root_task_group.css;
68318b8e
SV
6278 }
6279
ec7dc8ac 6280 tg = sched_create_group(parent);
68318b8e
SV
6281 if (IS_ERR(tg))
6282 return ERR_PTR(-ENOMEM);
6283
68318b8e
SV
6284 return &tg->css;
6285}
6286
96b77745
KK
6287/* Expose task group only after completing cgroup initialization */
6288static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6289{
6290 struct task_group *tg = css_tg(css);
6291 struct task_group *parent = css_tg(css->parent);
6292
6293 if (parent)
6294 sched_online_group(tg, parent);
6295 return 0;
6296}
6297
2f5177f0 6298static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
ace783b9 6299{
eb95419b 6300 struct task_group *tg = css_tg(css);
ace783b9 6301
2f5177f0 6302 sched_offline_group(tg);
ace783b9
LZ
6303}
6304
eb95419b 6305static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
68318b8e 6306{
eb95419b 6307 struct task_group *tg = css_tg(css);
68318b8e 6308
2f5177f0
PZ
6309 /*
6310 * Relies on the RCU grace period between css_released() and this.
6311 */
6312 sched_free_group(tg);
ace783b9
LZ
6313}
6314
ea86cb4b
VG
6315/*
6316 * This is called before wake_up_new_task(), therefore we really only
6317 * have to set its group bits, all the other stuff does not apply.
6318 */
b53202e6 6319static void cpu_cgroup_fork(struct task_struct *task)
eeb61e53 6320{
ea86cb4b
VG
6321 struct rq_flags rf;
6322 struct rq *rq;
6323
6324 rq = task_rq_lock(task, &rf);
6325
80f5c1b8 6326 update_rq_clock(rq);
ea86cb4b
VG
6327 sched_change_group(task, TASK_SET_GROUP);
6328
6329 task_rq_unlock(rq, task, &rf);
eeb61e53
KT
6330}
6331
1f7dd3e5 6332static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
68318b8e 6333{
bb9d97b6 6334 struct task_struct *task;
1f7dd3e5 6335 struct cgroup_subsys_state *css;
7dc603c9 6336 int ret = 0;
bb9d97b6 6337
1f7dd3e5 6338 cgroup_taskset_for_each(task, css, tset) {
b68aa230 6339#ifdef CONFIG_RT_GROUP_SCHED
eb95419b 6340 if (!sched_rt_can_attach(css_tg(css), task))
bb9d97b6 6341 return -EINVAL;
b68aa230 6342#else
bb9d97b6
TH
6343 /* We don't support RT-tasks being in separate groups */
6344 if (task->sched_class != &fair_sched_class)
6345 return -EINVAL;
b68aa230 6346#endif
7dc603c9
PZ
6347 /*
6348 * Serialize against wake_up_new_task() such that if its
6349 * running, we're sure to observe its full state.
6350 */
6351 raw_spin_lock_irq(&task->pi_lock);
6352 /*
6353 * Avoid calling sched_move_task() before wake_up_new_task()
6354 * has happened. This would lead to problems with PELT, due to
6355 * move wanting to detach+attach while we're not attached yet.
6356 */
6357 if (task->state == TASK_NEW)
6358 ret = -EINVAL;
6359 raw_spin_unlock_irq(&task->pi_lock);
6360
6361 if (ret)
6362 break;
bb9d97b6 6363 }
7dc603c9 6364 return ret;
be367d09 6365}
68318b8e 6366
1f7dd3e5 6367static void cpu_cgroup_attach(struct cgroup_taskset *tset)
68318b8e 6368{
bb9d97b6 6369 struct task_struct *task;
1f7dd3e5 6370 struct cgroup_subsys_state *css;
bb9d97b6 6371
1f7dd3e5 6372 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 6373 sched_move_task(task);
68318b8e
SV
6374}
6375
052f1dc7 6376#ifdef CONFIG_FAIR_GROUP_SCHED
182446d0
TH
6377static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6378 struct cftype *cftype, u64 shareval)
68318b8e 6379{
182446d0 6380 return sched_group_set_shares(css_tg(css), scale_load(shareval));
68318b8e
SV
6381}
6382
182446d0
TH
6383static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6384 struct cftype *cft)
68318b8e 6385{
182446d0 6386 struct task_group *tg = css_tg(css);
68318b8e 6387
c8b28116 6388 return (u64) scale_load_down(tg->shares);
68318b8e 6389}
ab84d31e
PT
6390
6391#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
6392static DEFINE_MUTEX(cfs_constraints_mutex);
6393
ab84d31e
PT
6394const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6395const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6396
a790de99
PT
6397static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6398
ab84d31e
PT
6399static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6400{
56f570e5 6401 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 6402 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
6403
6404 if (tg == &root_task_group)
6405 return -EINVAL;
6406
6407 /*
6408 * Ensure we have at some amount of bandwidth every period. This is
6409 * to prevent reaching a state of large arrears when throttled via
6410 * entity_tick() resulting in prolonged exit starvation.
6411 */
6412 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6413 return -EINVAL;
6414
6415 /*
6416 * Likewise, bound things on the otherside by preventing insane quota
6417 * periods. This also allows us to normalize in computing quota
6418 * feasibility.
6419 */
6420 if (period > max_cfs_quota_period)
6421 return -EINVAL;
6422
0e59bdae
KT
6423 /*
6424 * Prevent race between setting of cfs_rq->runtime_enabled and
6425 * unthrottle_offline_cfs_rqs().
6426 */
6427 get_online_cpus();
a790de99
PT
6428 mutex_lock(&cfs_constraints_mutex);
6429 ret = __cfs_schedulable(tg, period, quota);
6430 if (ret)
6431 goto out_unlock;
6432
58088ad0 6433 runtime_enabled = quota != RUNTIME_INF;
56f570e5 6434 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
1ee14e6c
BS
6435 /*
6436 * If we need to toggle cfs_bandwidth_used, off->on must occur
6437 * before making related changes, and on->off must occur afterwards
6438 */
6439 if (runtime_enabled && !runtime_was_enabled)
6440 cfs_bandwidth_usage_inc();
ab84d31e
PT
6441 raw_spin_lock_irq(&cfs_b->lock);
6442 cfs_b->period = ns_to_ktime(period);
6443 cfs_b->quota = quota;
58088ad0 6444
a9cf55b2 6445 __refill_cfs_bandwidth_runtime(cfs_b);
d1ccc66d
IM
6446
6447 /* Restart the period timer (if active) to handle new period expiry: */
77a4d1a1
PZ
6448 if (runtime_enabled)
6449 start_cfs_bandwidth(cfs_b);
d1ccc66d 6450
ab84d31e
PT
6451 raw_spin_unlock_irq(&cfs_b->lock);
6452
0e59bdae 6453 for_each_online_cpu(i) {
ab84d31e 6454 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 6455 struct rq *rq = cfs_rq->rq;
8a8c69c3 6456 struct rq_flags rf;
ab84d31e 6457
8a8c69c3 6458 rq_lock_irq(rq, &rf);
58088ad0 6459 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 6460 cfs_rq->runtime_remaining = 0;
671fd9da 6461
029632fb 6462 if (cfs_rq->throttled)
671fd9da 6463 unthrottle_cfs_rq(cfs_rq);
8a8c69c3 6464 rq_unlock_irq(rq, &rf);
ab84d31e 6465 }
1ee14e6c
BS
6466 if (runtime_was_enabled && !runtime_enabled)
6467 cfs_bandwidth_usage_dec();
a790de99
PT
6468out_unlock:
6469 mutex_unlock(&cfs_constraints_mutex);
0e59bdae 6470 put_online_cpus();
ab84d31e 6471
a790de99 6472 return ret;
ab84d31e
PT
6473}
6474
6475int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6476{
6477 u64 quota, period;
6478
029632fb 6479 period = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
6480 if (cfs_quota_us < 0)
6481 quota = RUNTIME_INF;
6482 else
6483 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6484
6485 return tg_set_cfs_bandwidth(tg, period, quota);
6486}
6487
6488long tg_get_cfs_quota(struct task_group *tg)
6489{
6490 u64 quota_us;
6491
029632fb 6492 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
6493 return -1;
6494
029632fb 6495 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
6496 do_div(quota_us, NSEC_PER_USEC);
6497
6498 return quota_us;
6499}
6500
6501int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6502{
6503 u64 quota, period;
6504
6505 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 6506 quota = tg->cfs_bandwidth.quota;
ab84d31e 6507
ab84d31e
PT
6508 return tg_set_cfs_bandwidth(tg, period, quota);
6509}
6510
6511long tg_get_cfs_period(struct task_group *tg)
6512{
6513 u64 cfs_period_us;
6514
029632fb 6515 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
6516 do_div(cfs_period_us, NSEC_PER_USEC);
6517
6518 return cfs_period_us;
6519}
6520
182446d0
TH
6521static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6522 struct cftype *cft)
ab84d31e 6523{
182446d0 6524 return tg_get_cfs_quota(css_tg(css));
ab84d31e
PT
6525}
6526
182446d0
TH
6527static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6528 struct cftype *cftype, s64 cfs_quota_us)
ab84d31e 6529{
182446d0 6530 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
ab84d31e
PT
6531}
6532
182446d0
TH
6533static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6534 struct cftype *cft)
ab84d31e 6535{
182446d0 6536 return tg_get_cfs_period(css_tg(css));
ab84d31e
PT
6537}
6538
182446d0
TH
6539static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6540 struct cftype *cftype, u64 cfs_period_us)
ab84d31e 6541{
182446d0 6542 return tg_set_cfs_period(css_tg(css), cfs_period_us);
ab84d31e
PT
6543}
6544
a790de99
PT
6545struct cfs_schedulable_data {
6546 struct task_group *tg;
6547 u64 period, quota;
6548};
6549
6550/*
6551 * normalize group quota/period to be quota/max_period
6552 * note: units are usecs
6553 */
6554static u64 normalize_cfs_quota(struct task_group *tg,
6555 struct cfs_schedulable_data *d)
6556{
6557 u64 quota, period;
6558
6559 if (tg == d->tg) {
6560 period = d->period;
6561 quota = d->quota;
6562 } else {
6563 period = tg_get_cfs_period(tg);
6564 quota = tg_get_cfs_quota(tg);
6565 }
6566
6567 /* note: these should typically be equivalent */
6568 if (quota == RUNTIME_INF || quota == -1)
6569 return RUNTIME_INF;
6570
6571 return to_ratio(period, quota);
6572}
6573
6574static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6575{
6576 struct cfs_schedulable_data *d = data;
029632fb 6577 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
6578 s64 quota = 0, parent_quota = -1;
6579
6580 if (!tg->parent) {
6581 quota = RUNTIME_INF;
6582 } else {
029632fb 6583 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
6584
6585 quota = normalize_cfs_quota(tg, d);
9c58c79a 6586 parent_quota = parent_b->hierarchical_quota;
a790de99
PT
6587
6588 /*
d1ccc66d
IM
6589 * Ensure max(child_quota) <= parent_quota, inherit when no
6590 * limit is set:
a790de99
PT
6591 */
6592 if (quota == RUNTIME_INF)
6593 quota = parent_quota;
6594 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6595 return -EINVAL;
6596 }
9c58c79a 6597 cfs_b->hierarchical_quota = quota;
a790de99
PT
6598
6599 return 0;
6600}
6601
6602static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6603{
8277434e 6604 int ret;
a790de99
PT
6605 struct cfs_schedulable_data data = {
6606 .tg = tg,
6607 .period = period,
6608 .quota = quota,
6609 };
6610
6611 if (quota != RUNTIME_INF) {
6612 do_div(data.period, NSEC_PER_USEC);
6613 do_div(data.quota, NSEC_PER_USEC);
6614 }
6615
8277434e
PT
6616 rcu_read_lock();
6617 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6618 rcu_read_unlock();
6619
6620 return ret;
a790de99 6621}
e8da1b18 6622
2da8ca82 6623static int cpu_stats_show(struct seq_file *sf, void *v)
e8da1b18 6624{
2da8ca82 6625 struct task_group *tg = css_tg(seq_css(sf));
029632fb 6626 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18 6627
44ffc75b
TH
6628 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6629 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6630 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
e8da1b18
NR
6631
6632 return 0;
6633}
ab84d31e 6634#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 6635#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 6636
052f1dc7 6637#ifdef CONFIG_RT_GROUP_SCHED
182446d0
TH
6638static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6639 struct cftype *cft, s64 val)
6f505b16 6640{
182446d0 6641 return sched_group_set_rt_runtime(css_tg(css), val);
6f505b16
PZ
6642}
6643
182446d0
TH
6644static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6645 struct cftype *cft)
6f505b16 6646{
182446d0 6647 return sched_group_rt_runtime(css_tg(css));
6f505b16 6648}
d0b27fa7 6649
182446d0
TH
6650static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6651 struct cftype *cftype, u64 rt_period_us)
d0b27fa7 6652{
182446d0 6653 return sched_group_set_rt_period(css_tg(css), rt_period_us);
d0b27fa7
PZ
6654}
6655
182446d0
TH
6656static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6657 struct cftype *cft)
d0b27fa7 6658{
182446d0 6659 return sched_group_rt_period(css_tg(css));
d0b27fa7 6660}
6d6bc0ad 6661#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 6662
fe5c7cc2 6663static struct cftype cpu_files[] = {
052f1dc7 6664#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
6665 {
6666 .name = "shares",
f4c753b7
PM
6667 .read_u64 = cpu_shares_read_u64,
6668 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 6669 },
052f1dc7 6670#endif
ab84d31e
PT
6671#ifdef CONFIG_CFS_BANDWIDTH
6672 {
6673 .name = "cfs_quota_us",
6674 .read_s64 = cpu_cfs_quota_read_s64,
6675 .write_s64 = cpu_cfs_quota_write_s64,
6676 },
6677 {
6678 .name = "cfs_period_us",
6679 .read_u64 = cpu_cfs_period_read_u64,
6680 .write_u64 = cpu_cfs_period_write_u64,
6681 },
e8da1b18
NR
6682 {
6683 .name = "stat",
2da8ca82 6684 .seq_show = cpu_stats_show,
e8da1b18 6685 },
ab84d31e 6686#endif
052f1dc7 6687#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 6688 {
9f0c1e56 6689 .name = "rt_runtime_us",
06ecb27c
PM
6690 .read_s64 = cpu_rt_runtime_read,
6691 .write_s64 = cpu_rt_runtime_write,
6f505b16 6692 },
d0b27fa7
PZ
6693 {
6694 .name = "rt_period_us",
f4c753b7
PM
6695 .read_u64 = cpu_rt_period_read_uint,
6696 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 6697 },
052f1dc7 6698#endif
d1ccc66d 6699 { } /* Terminate */
68318b8e
SV
6700};
6701
073219e9 6702struct cgroup_subsys cpu_cgrp_subsys = {
92fb9748 6703 .css_alloc = cpu_cgroup_css_alloc,
96b77745 6704 .css_online = cpu_cgroup_css_online,
2f5177f0 6705 .css_released = cpu_cgroup_css_released,
92fb9748 6706 .css_free = cpu_cgroup_css_free,
eeb61e53 6707 .fork = cpu_cgroup_fork,
bb9d97b6
TH
6708 .can_attach = cpu_cgroup_can_attach,
6709 .attach = cpu_cgroup_attach,
5577964e 6710 .legacy_cftypes = cpu_files,
b38e42e9 6711 .early_init = true,
68318b8e
SV
6712};
6713
052f1dc7 6714#endif /* CONFIG_CGROUP_SCHED */
d842de87 6715
b637a328
PM
6716void dump_cpu_task(int cpu)
6717{
6718 pr_info("Task dump for CPU %d:\n", cpu);
6719 sched_show_task(cpu_curr(cpu));
6720}
ed82b8a1
AK
6721
6722/*
6723 * Nice levels are multiplicative, with a gentle 10% change for every
6724 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
6725 * nice 1, it will get ~10% less CPU time than another CPU-bound task
6726 * that remained on nice 0.
6727 *
6728 * The "10% effect" is relative and cumulative: from _any_ nice level,
6729 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
6730 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
6731 * If a task goes up by ~10% and another task goes down by ~10% then
6732 * the relative distance between them is ~25%.)
6733 */
6734const int sched_prio_to_weight[40] = {
6735 /* -20 */ 88761, 71755, 56483, 46273, 36291,
6736 /* -15 */ 29154, 23254, 18705, 14949, 11916,
6737 /* -10 */ 9548, 7620, 6100, 4904, 3906,
6738 /* -5 */ 3121, 2501, 1991, 1586, 1277,
6739 /* 0 */ 1024, 820, 655, 526, 423,
6740 /* 5 */ 335, 272, 215, 172, 137,
6741 /* 10 */ 110, 87, 70, 56, 45,
6742 /* 15 */ 36, 29, 23, 18, 15,
6743};
6744
6745/*
6746 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
6747 *
6748 * In cases where the weight does not change often, we can use the
6749 * precalculated inverse to speed up arithmetics by turning divisions
6750 * into multiplications:
6751 */
6752const u32 sched_prio_to_wmult[40] = {
6753 /* -20 */ 48388, 59856, 76040, 92818, 118348,
6754 /* -15 */ 147320, 184698, 229616, 287308, 360437,
6755 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
6756 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
6757 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
6758 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
6759 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
6760 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
6761};