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