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