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