sched/preempt: Add PREEMPT_DYNAMIC using static keys
[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 */
9d246053
PA
9#define CREATE_TRACE_POINTS
10#include <trace/events/sched.h>
11#undef CREATE_TRACE_POINTS
12
325ea10c 13#include "sched.h"
1da177e4 14
7281c8de 15#include <linux/nospec.h>
6a5850d1 16#include <linux/blkdev.h>
99cf983c 17#include <linux/jump_label.h>
0ed557aa 18#include <linux/kcov.h>
d08b9f0c 19#include <linux/scs.h>
0ed557aa 20
96f951ed 21#include <asm/switch_to.h>
5517d86b 22#include <asm/tlb.h>
1da177e4 23
ea138446 24#include "../workqueue_internal.h"
771b53d0 25#include "../../fs/io-wq.h"
29d5e047 26#include "../smpboot.h"
6e0534f2 27
91c27493 28#include "pelt.h"
1f8db415 29#include "smp.h"
91c27493 30
a056a5be
QY
31/*
32 * Export tracepoints that act as a bare tracehook (ie: have no trace event
33 * associated with them) to allow external modules to probe them.
34 */
35EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
36EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
37EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
38EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
39EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
77cf151b 40EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
51cf18c9 41EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
a056a5be 42EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
4581bea8
VD
43EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
44EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
9d246053 45EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
a056a5be 46
029632fb 47DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 48
a73f863a 49#ifdef CONFIG_SCHED_DEBUG
bf5c91ba
IM
50/*
51 * Debugging: various feature bits
765cc3a4
PB
52 *
53 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
54 * sysctl_sched_features, defined in sched.h, to allow constants propagation
55 * at compile time and compiler optimization based on features default.
bf5c91ba 56 */
f00b45c1
PZ
57#define SCHED_FEAT(name, enabled) \
58 (1UL << __SCHED_FEAT_##name) * enabled |
bf5c91ba 59const_debug unsigned int sysctl_sched_features =
391e43da 60#include "features.h"
f00b45c1 61 0;
f00b45c1 62#undef SCHED_FEAT
c006fac5
PT
63
64/*
65 * Print a warning if need_resched is set for the given duration (if
66 * LATENCY_WARN is enabled).
67 *
68 * If sysctl_resched_latency_warn_once is set, only one warning will be shown
69 * per boot.
70 */
71__read_mostly int sysctl_resched_latency_warn_ms = 100;
72__read_mostly int sysctl_resched_latency_warn_once = 1;
73#endif /* CONFIG_SCHED_DEBUG */
f00b45c1 74
b82d9fdd
PZ
75/*
76 * Number of tasks to iterate in a single balance run.
77 * Limited because this is done with IRQs disabled.
78 */
691925f3
TG
79#ifdef CONFIG_PREEMPT_RT
80const_debug unsigned int sysctl_sched_nr_migrate = 8;
81#else
b82d9fdd 82const_debug unsigned int sysctl_sched_nr_migrate = 32;
691925f3 83#endif
b82d9fdd 84
fa85ae24 85/*
d1ccc66d 86 * period over which we measure -rt task CPU usage in us.
fa85ae24
PZ
87 * default: 1s
88 */
9f0c1e56 89unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 90
029632fb 91__read_mostly int scheduler_running;
6892b75e 92
9edeaea1
PZ
93#ifdef CONFIG_SCHED_CORE
94
95DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
96
8a311c74
PZ
97/* kernel prio, less is more */
98static inline int __task_prio(struct task_struct *p)
99{
100 if (p->sched_class == &stop_sched_class) /* trumps deadline */
101 return -2;
102
103 if (rt_prio(p->prio)) /* includes deadline */
104 return p->prio; /* [-1, 99] */
105
106 if (p->sched_class == &idle_sched_class)
107 return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
108
109 return MAX_RT_PRIO + MAX_NICE; /* 120, squash fair */
110}
111
112/*
113 * l(a,b)
114 * le(a,b) := !l(b,a)
115 * g(a,b) := l(b,a)
116 * ge(a,b) := !l(a,b)
117 */
118
119/* real prio, less is less */
c6047c2e 120static inline bool prio_less(struct task_struct *a, struct task_struct *b, bool in_fi)
8a311c74
PZ
121{
122
123 int pa = __task_prio(a), pb = __task_prio(b);
124
125 if (-pa < -pb)
126 return true;
127
128 if (-pb < -pa)
129 return false;
130
131 if (pa == -1) /* dl_prio() doesn't work because of stop_class above */
132 return !dl_time_before(a->dl.deadline, b->dl.deadline);
133
c6047c2e
JFG
134 if (pa == MAX_RT_PRIO + MAX_NICE) /* fair */
135 return cfs_prio_less(a, b, in_fi);
8a311c74
PZ
136
137 return false;
138}
139
140static inline bool __sched_core_less(struct task_struct *a, struct task_struct *b)
141{
142 if (a->core_cookie < b->core_cookie)
143 return true;
144
145 if (a->core_cookie > b->core_cookie)
146 return false;
147
148 /* flip prio, so high prio is leftmost */
4feee7d1 149 if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
8a311c74
PZ
150 return true;
151
152 return false;
153}
154
155#define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
156
157static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
158{
159 return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
160}
161
162static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
163{
164 const struct task_struct *p = __node_2_sc(node);
165 unsigned long cookie = (unsigned long)key;
166
167 if (cookie < p->core_cookie)
168 return -1;
169
170 if (cookie > p->core_cookie)
171 return 1;
172
173 return 0;
174}
175
6e33cad0 176void sched_core_enqueue(struct rq *rq, struct task_struct *p)
8a311c74
PZ
177{
178 rq->core->core_task_seq++;
179
180 if (!p->core_cookie)
181 return;
182
183 rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
184}
185
4feee7d1 186void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
8a311c74
PZ
187{
188 rq->core->core_task_seq++;
189
4feee7d1
JD
190 if (sched_core_enqueued(p)) {
191 rb_erase(&p->core_node, &rq->core_tree);
192 RB_CLEAR_NODE(&p->core_node);
193 }
8a311c74 194
4feee7d1
JD
195 /*
196 * Migrating the last task off the cpu, with the cpu in forced idle
197 * state. Reschedule to create an accounting edge for forced idle,
198 * and re-examine whether the core is still in forced idle state.
199 */
200 if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
201 rq->core->core_forceidle_count && rq->curr == rq->idle)
202 resched_curr(rq);
8a311c74
PZ
203}
204
205/*
206 * Find left-most (aka, highest priority) task matching @cookie.
207 */
208static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
209{
210 struct rb_node *node;
211
212 node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
213 /*
214 * The idle task always matches any cookie!
215 */
216 if (!node)
217 return idle_sched_class.pick_task(rq);
218
219 return __node_2_sc(node);
220}
221
d2dfa17b
PZ
222static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
223{
224 struct rb_node *node = &p->core_node;
225
226 node = rb_next(node);
227 if (!node)
228 return NULL;
229
230 p = container_of(node, struct task_struct, core_node);
231 if (p->core_cookie != cookie)
232 return NULL;
233
234 return p;
235}
236
9edeaea1
PZ
237/*
238 * Magic required such that:
239 *
240 * raw_spin_rq_lock(rq);
241 * ...
242 * raw_spin_rq_unlock(rq);
243 *
244 * ends up locking and unlocking the _same_ lock, and all CPUs
245 * always agree on what rq has what lock.
246 *
247 * XXX entirely possible to selectively enable cores, don't bother for now.
248 */
249
250static DEFINE_MUTEX(sched_core_mutex);
875feb41 251static atomic_t sched_core_count;
9edeaea1
PZ
252static struct cpumask sched_core_mask;
253
3c474b32
PZ
254static void sched_core_lock(int cpu, unsigned long *flags)
255{
256 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
257 int t, i = 0;
258
259 local_irq_save(*flags);
260 for_each_cpu(t, smt_mask)
261 raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
262}
263
264static void sched_core_unlock(int cpu, unsigned long *flags)
265{
266 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
267 int t;
268
269 for_each_cpu(t, smt_mask)
270 raw_spin_unlock(&cpu_rq(t)->__lock);
271 local_irq_restore(*flags);
272}
273
9edeaea1
PZ
274static void __sched_core_flip(bool enabled)
275{
3c474b32
PZ
276 unsigned long flags;
277 int cpu, t;
9edeaea1
PZ
278
279 cpus_read_lock();
280
281 /*
282 * Toggle the online cores, one by one.
283 */
284 cpumask_copy(&sched_core_mask, cpu_online_mask);
285 for_each_cpu(cpu, &sched_core_mask) {
286 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
287
3c474b32 288 sched_core_lock(cpu, &flags);
9edeaea1
PZ
289
290 for_each_cpu(t, smt_mask)
291 cpu_rq(t)->core_enabled = enabled;
292
4feee7d1
JD
293 cpu_rq(cpu)->core->core_forceidle_start = 0;
294
3c474b32 295 sched_core_unlock(cpu, &flags);
9edeaea1
PZ
296
297 cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
298 }
299
300 /*
301 * Toggle the offline CPUs.
302 */
303 cpumask_copy(&sched_core_mask, cpu_possible_mask);
304 cpumask_andnot(&sched_core_mask, &sched_core_mask, cpu_online_mask);
305
306 for_each_cpu(cpu, &sched_core_mask)
307 cpu_rq(cpu)->core_enabled = enabled;
308
309 cpus_read_unlock();
310}
311
8a311c74 312static void sched_core_assert_empty(void)
9edeaea1 313{
8a311c74 314 int cpu;
9edeaea1 315
8a311c74
PZ
316 for_each_possible_cpu(cpu)
317 WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
318}
319
320static void __sched_core_enable(void)
321{
9edeaea1
PZ
322 static_branch_enable(&__sched_core_enabled);
323 /*
324 * Ensure all previous instances of raw_spin_rq_*lock() have finished
325 * and future ones will observe !sched_core_disabled().
326 */
327 synchronize_rcu();
328 __sched_core_flip(true);
8a311c74 329 sched_core_assert_empty();
9edeaea1
PZ
330}
331
332static void __sched_core_disable(void)
333{
8a311c74 334 sched_core_assert_empty();
9edeaea1
PZ
335 __sched_core_flip(false);
336 static_branch_disable(&__sched_core_enabled);
337}
338
339void sched_core_get(void)
340{
875feb41
PZ
341 if (atomic_inc_not_zero(&sched_core_count))
342 return;
343
9edeaea1 344 mutex_lock(&sched_core_mutex);
875feb41 345 if (!atomic_read(&sched_core_count))
9edeaea1 346 __sched_core_enable();
875feb41
PZ
347
348 smp_mb__before_atomic();
349 atomic_inc(&sched_core_count);
9edeaea1
PZ
350 mutex_unlock(&sched_core_mutex);
351}
352
875feb41 353static void __sched_core_put(struct work_struct *work)
9edeaea1 354{
875feb41 355 if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
9edeaea1 356 __sched_core_disable();
875feb41
PZ
357 mutex_unlock(&sched_core_mutex);
358 }
359}
360
361void sched_core_put(void)
362{
363 static DECLARE_WORK(_work, __sched_core_put);
364
365 /*
366 * "There can be only one"
367 *
368 * Either this is the last one, or we don't actually need to do any
369 * 'work'. If it is the last *again*, we rely on
370 * WORK_STRUCT_PENDING_BIT.
371 */
372 if (!atomic_add_unless(&sched_core_count, -1, 1))
373 schedule_work(&_work);
9edeaea1
PZ
374}
375
8a311c74
PZ
376#else /* !CONFIG_SCHED_CORE */
377
378static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
4feee7d1
JD
379static inline void
380sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
8a311c74 381
9edeaea1
PZ
382#endif /* CONFIG_SCHED_CORE */
383
9f0c1e56
PZ
384/*
385 * part of the period that we allow rt tasks to run in us.
386 * default: 0.95s
387 */
388int sysctl_sched_rt_runtime = 950000;
fa85ae24 389
58877d34
PZ
390
391/*
392 * Serialization rules:
393 *
394 * Lock order:
395 *
396 * p->pi_lock
397 * rq->lock
398 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
399 *
400 * rq1->lock
401 * rq2->lock where: rq1 < rq2
402 *
403 * Regular state:
404 *
405 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
406 * local CPU's rq->lock, it optionally removes the task from the runqueue and
b19a888c 407 * always looks at the local rq data structures to find the most eligible task
58877d34
PZ
408 * to run next.
409 *
410 * Task enqueue is also under rq->lock, possibly taken from another CPU.
411 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
412 * the local CPU to avoid bouncing the runqueue state around [ see
413 * ttwu_queue_wakelist() ]
414 *
415 * Task wakeup, specifically wakeups that involve migration, are horribly
416 * complicated to avoid having to take two rq->locks.
417 *
418 * Special state:
419 *
420 * System-calls and anything external will use task_rq_lock() which acquires
421 * both p->pi_lock and rq->lock. As a consequence the state they change is
422 * stable while holding either lock:
423 *
424 * - sched_setaffinity()/
425 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
426 * - set_user_nice(): p->se.load, p->*prio
427 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
428 * p->se.load, p->rt_priority,
429 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
430 * - sched_setnuma(): p->numa_preferred_nid
431 * - sched_move_task()/
432 * cpu_cgroup_fork(): p->sched_task_group
433 * - uclamp_update_active() p->uclamp*
434 *
435 * p->state <- TASK_*:
436 *
437 * is changed locklessly using set_current_state(), __set_current_state() or
438 * set_special_state(), see their respective comments, or by
439 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
440 * concurrent self.
441 *
442 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
443 *
444 * is set by activate_task() and cleared by deactivate_task(), under
445 * rq->lock. Non-zero indicates the task is runnable, the special
446 * ON_RQ_MIGRATING state is used for migration without holding both
447 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
448 *
449 * p->on_cpu <- { 0, 1 }:
450 *
451 * is set by prepare_task() and cleared by finish_task() such that it will be
452 * set before p is scheduled-in and cleared after p is scheduled-out, both
453 * under rq->lock. Non-zero indicates the task is running on its CPU.
454 *
455 * [ The astute reader will observe that it is possible for two tasks on one
456 * CPU to have ->on_cpu = 1 at the same time. ]
457 *
458 * task_cpu(p): is changed by set_task_cpu(), the rules are:
459 *
460 * - Don't call set_task_cpu() on a blocked task:
461 *
462 * We don't care what CPU we're not running on, this simplifies hotplug,
463 * the CPU assignment of blocked tasks isn't required to be valid.
464 *
465 * - for try_to_wake_up(), called under p->pi_lock:
466 *
467 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
468 *
469 * - for migration called under rq->lock:
470 * [ see task_on_rq_migrating() in task_rq_lock() ]
471 *
472 * o move_queued_task()
473 * o detach_task()
474 *
475 * - for migration called under double_rq_lock():
476 *
477 * o __migrate_swap_task()
478 * o push_rt_task() / pull_rt_task()
479 * o push_dl_task() / pull_dl_task()
480 * o dl_task_offline_migration()
481 *
482 */
483
39d371b7
PZ
484void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
485{
d66f1b06
PZ
486 raw_spinlock_t *lock;
487
9edeaea1
PZ
488 /* Matches synchronize_rcu() in __sched_core_enable() */
489 preempt_disable();
d66f1b06
PZ
490 if (sched_core_disabled()) {
491 raw_spin_lock_nested(&rq->__lock, subclass);
9edeaea1
PZ
492 /* preempt_count *MUST* be > 1 */
493 preempt_enable_no_resched();
d66f1b06
PZ
494 return;
495 }
496
497 for (;;) {
9ef7e7e3 498 lock = __rq_lockp(rq);
d66f1b06 499 raw_spin_lock_nested(lock, subclass);
9ef7e7e3 500 if (likely(lock == __rq_lockp(rq))) {
9edeaea1
PZ
501 /* preempt_count *MUST* be > 1 */
502 preempt_enable_no_resched();
d66f1b06 503 return;
9edeaea1 504 }
d66f1b06
PZ
505 raw_spin_unlock(lock);
506 }
39d371b7
PZ
507}
508
509bool raw_spin_rq_trylock(struct rq *rq)
510{
d66f1b06
PZ
511 raw_spinlock_t *lock;
512 bool ret;
513
9edeaea1
PZ
514 /* Matches synchronize_rcu() in __sched_core_enable() */
515 preempt_disable();
516 if (sched_core_disabled()) {
517 ret = raw_spin_trylock(&rq->__lock);
518 preempt_enable();
519 return ret;
520 }
d66f1b06
PZ
521
522 for (;;) {
9ef7e7e3 523 lock = __rq_lockp(rq);
d66f1b06 524 ret = raw_spin_trylock(lock);
9ef7e7e3 525 if (!ret || (likely(lock == __rq_lockp(rq)))) {
9edeaea1 526 preempt_enable();
d66f1b06 527 return ret;
9edeaea1 528 }
d66f1b06
PZ
529 raw_spin_unlock(lock);
530 }
39d371b7
PZ
531}
532
533void raw_spin_rq_unlock(struct rq *rq)
534{
535 raw_spin_unlock(rq_lockp(rq));
536}
537
d66f1b06
PZ
538#ifdef CONFIG_SMP
539/*
540 * double_rq_lock - safely lock two runqueues
541 */
542void double_rq_lock(struct rq *rq1, struct rq *rq2)
543{
544 lockdep_assert_irqs_disabled();
545
546 if (rq_order_less(rq2, rq1))
547 swap(rq1, rq2);
548
549 raw_spin_rq_lock(rq1);
9ef7e7e3 550 if (__rq_lockp(rq1) == __rq_lockp(rq2))
d66f1b06
PZ
551 return;
552
553 raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
554}
555#endif
556
3e71a462
PZ
557/*
558 * __task_rq_lock - lock the rq @p resides on.
559 */
eb580751 560struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
561 __acquires(rq->lock)
562{
563 struct rq *rq;
564
565 lockdep_assert_held(&p->pi_lock);
566
567 for (;;) {
568 rq = task_rq(p);
5cb9eaa3 569 raw_spin_rq_lock(rq);
3e71a462 570 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 571 rq_pin_lock(rq, rf);
3e71a462
PZ
572 return rq;
573 }
5cb9eaa3 574 raw_spin_rq_unlock(rq);
3e71a462
PZ
575
576 while (unlikely(task_on_rq_migrating(p)))
577 cpu_relax();
578 }
579}
580
581/*
582 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
583 */
eb580751 584struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
585 __acquires(p->pi_lock)
586 __acquires(rq->lock)
587{
588 struct rq *rq;
589
590 for (;;) {
eb580751 591 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
3e71a462 592 rq = task_rq(p);
5cb9eaa3 593 raw_spin_rq_lock(rq);
3e71a462
PZ
594 /*
595 * move_queued_task() task_rq_lock()
596 *
597 * ACQUIRE (rq->lock)
598 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
599 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
600 * [S] ->cpu = new_cpu [L] task_rq()
601 * [L] ->on_rq
602 * RELEASE (rq->lock)
603 *
c546951d 604 * If we observe the old CPU in task_rq_lock(), the acquire of
3e71a462
PZ
605 * the old rq->lock will fully serialize against the stores.
606 *
c546951d
AP
607 * If we observe the new CPU in task_rq_lock(), the address
608 * dependency headed by '[L] rq = task_rq()' and the acquire
609 * will pair with the WMB to ensure we then also see migrating.
3e71a462
PZ
610 */
611 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 612 rq_pin_lock(rq, rf);
3e71a462
PZ
613 return rq;
614 }
5cb9eaa3 615 raw_spin_rq_unlock(rq);
eb580751 616 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
3e71a462
PZ
617
618 while (unlikely(task_on_rq_migrating(p)))
619 cpu_relax();
620 }
621}
622
535b9552
IM
623/*
624 * RQ-clock updating methods:
625 */
626
627static void update_rq_clock_task(struct rq *rq, s64 delta)
628{
629/*
630 * In theory, the compile should just see 0 here, and optimize out the call
631 * to sched_rt_avg_update. But I don't trust it...
632 */
11d4afd4
VG
633 s64 __maybe_unused steal = 0, irq_delta = 0;
634
535b9552
IM
635#ifdef CONFIG_IRQ_TIME_ACCOUNTING
636 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
637
638 /*
639 * Since irq_time is only updated on {soft,}irq_exit, we might run into
640 * this case when a previous update_rq_clock() happened inside a
641 * {soft,}irq region.
642 *
643 * When this happens, we stop ->clock_task and only update the
644 * prev_irq_time stamp to account for the part that fit, so that a next
645 * update will consume the rest. This ensures ->clock_task is
646 * monotonic.
647 *
648 * It does however cause some slight miss-attribution of {soft,}irq
649 * time, a more accurate solution would be to update the irq_time using
650 * the current rq->clock timestamp, except that would require using
651 * atomic ops.
652 */
653 if (irq_delta > delta)
654 irq_delta = delta;
655
656 rq->prev_irq_time += irq_delta;
657 delta -= irq_delta;
658#endif
659#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
660 if (static_key_false((&paravirt_steal_rq_enabled))) {
661 steal = paravirt_steal_clock(cpu_of(rq));
662 steal -= rq->prev_steal_time_rq;
663
664 if (unlikely(steal > delta))
665 steal = delta;
666
667 rq->prev_steal_time_rq += steal;
668 delta -= steal;
669 }
670#endif
671
672 rq->clock_task += delta;
673
11d4afd4 674#ifdef CONFIG_HAVE_SCHED_AVG_IRQ
535b9552 675 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
91c27493 676 update_irq_load_avg(rq, irq_delta + steal);
535b9552 677#endif
23127296 678 update_rq_clock_pelt(rq, delta);
535b9552
IM
679}
680
681void update_rq_clock(struct rq *rq)
682{
683 s64 delta;
684
5cb9eaa3 685 lockdep_assert_rq_held(rq);
535b9552
IM
686
687 if (rq->clock_update_flags & RQCF_ACT_SKIP)
688 return;
689
690#ifdef CONFIG_SCHED_DEBUG
26ae58d2
PZ
691 if (sched_feat(WARN_DOUBLE_CLOCK))
692 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
535b9552
IM
693 rq->clock_update_flags |= RQCF_UPDATED;
694#endif
26ae58d2 695
535b9552
IM
696 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
697 if (delta < 0)
698 return;
699 rq->clock += delta;
700 update_rq_clock_task(rq, delta);
701}
702
8f4d37ec
PZ
703#ifdef CONFIG_SCHED_HRTICK
704/*
705 * Use HR-timers to deliver accurate preemption points.
8f4d37ec 706 */
8f4d37ec 707
8f4d37ec
PZ
708static void hrtick_clear(struct rq *rq)
709{
710 if (hrtimer_active(&rq->hrtick_timer))
711 hrtimer_cancel(&rq->hrtick_timer);
712}
713
8f4d37ec
PZ
714/*
715 * High-resolution timer tick.
716 * Runs from hardirq context with interrupts disabled.
717 */
718static enum hrtimer_restart hrtick(struct hrtimer *timer)
719{
720 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
8a8c69c3 721 struct rq_flags rf;
8f4d37ec
PZ
722
723 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
724
8a8c69c3 725 rq_lock(rq, &rf);
3e51f33f 726 update_rq_clock(rq);
8f4d37ec 727 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
8a8c69c3 728 rq_unlock(rq, &rf);
8f4d37ec
PZ
729
730 return HRTIMER_NORESTART;
731}
732
95e904c7 733#ifdef CONFIG_SMP
971ee28c 734
4961b6e1 735static void __hrtick_restart(struct rq *rq)
971ee28c
PZ
736{
737 struct hrtimer *timer = &rq->hrtick_timer;
156ec6f4 738 ktime_t time = rq->hrtick_time;
971ee28c 739
156ec6f4 740 hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
971ee28c
PZ
741}
742
31656519
PZ
743/*
744 * called from hardirq (IPI) context
745 */
746static void __hrtick_start(void *arg)
b328ca18 747{
31656519 748 struct rq *rq = arg;
8a8c69c3 749 struct rq_flags rf;
b328ca18 750
8a8c69c3 751 rq_lock(rq, &rf);
971ee28c 752 __hrtick_restart(rq);
8a8c69c3 753 rq_unlock(rq, &rf);
b328ca18
PZ
754}
755
31656519
PZ
756/*
757 * Called to set the hrtick timer state.
758 *
759 * called with rq->lock held and irqs disabled
760 */
029632fb 761void hrtick_start(struct rq *rq, u64 delay)
b328ca18 762{
31656519 763 struct hrtimer *timer = &rq->hrtick_timer;
177ef2a6 764 s64 delta;
765
766 /*
767 * Don't schedule slices shorter than 10000ns, that just
768 * doesn't make sense and can cause timer DoS.
769 */
770 delta = max_t(s64, delay, 10000LL);
156ec6f4 771 rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
31656519 772
fd3eafda 773 if (rq == this_rq())
971ee28c 774 __hrtick_restart(rq);
fd3eafda 775 else
c46fff2a 776 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
b328ca18
PZ
777}
778
31656519
PZ
779#else
780/*
781 * Called to set the hrtick timer state.
782 *
783 * called with rq->lock held and irqs disabled
784 */
029632fb 785void hrtick_start(struct rq *rq, u64 delay)
31656519 786{
86893335
WL
787 /*
788 * Don't schedule slices shorter than 10000ns, that just
789 * doesn't make sense. Rely on vruntime for fairness.
790 */
791 delay = max_t(u64, delay, 10000LL);
4961b6e1 792 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
d5096aa6 793 HRTIMER_MODE_REL_PINNED_HARD);
31656519 794}
90b5363a 795
31656519 796#endif /* CONFIG_SMP */
8f4d37ec 797
77a021be 798static void hrtick_rq_init(struct rq *rq)
8f4d37ec 799{
31656519 800#ifdef CONFIG_SMP
545b8c8d 801 INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
31656519 802#endif
d5096aa6 803 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
31656519 804 rq->hrtick_timer.function = hrtick;
8f4d37ec 805}
006c75f1 806#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
807static inline void hrtick_clear(struct rq *rq)
808{
809}
810
77a021be 811static inline void hrtick_rq_init(struct rq *rq)
8f4d37ec
PZ
812{
813}
006c75f1 814#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 815
5529578a
FW
816/*
817 * cmpxchg based fetch_or, macro so it works for different integer types
818 */
819#define fetch_or(ptr, mask) \
820 ({ \
821 typeof(ptr) _ptr = (ptr); \
822 typeof(mask) _mask = (mask); \
823 typeof(*_ptr) _old, _val = *_ptr; \
824 \
825 for (;;) { \
826 _old = cmpxchg(_ptr, _val, _val | _mask); \
827 if (_old == _val) \
828 break; \
829 _val = _old; \
830 } \
831 _old; \
832})
833
e3baac47 834#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
fd99f91a
PZ
835/*
836 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
837 * this avoids any races wrt polling state changes and thereby avoids
838 * spurious IPIs.
839 */
840static bool set_nr_and_not_polling(struct task_struct *p)
841{
842 struct thread_info *ti = task_thread_info(p);
843 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
844}
e3baac47
PZ
845
846/*
847 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
848 *
849 * If this returns true, then the idle task promises to call
850 * sched_ttwu_pending() and reschedule soon.
851 */
852static bool set_nr_if_polling(struct task_struct *p)
853{
854 struct thread_info *ti = task_thread_info(p);
316c1608 855 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
e3baac47
PZ
856
857 for (;;) {
858 if (!(val & _TIF_POLLING_NRFLAG))
859 return false;
860 if (val & _TIF_NEED_RESCHED)
861 return true;
862 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
863 if (old == val)
864 break;
865 val = old;
866 }
867 return true;
868}
869
fd99f91a
PZ
870#else
871static bool set_nr_and_not_polling(struct task_struct *p)
872{
873 set_tsk_need_resched(p);
874 return true;
875}
e3baac47
PZ
876
877#ifdef CONFIG_SMP
878static bool set_nr_if_polling(struct task_struct *p)
879{
880 return false;
881}
882#endif
fd99f91a
PZ
883#endif
884
07879c6a 885static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
76751049
PZ
886{
887 struct wake_q_node *node = &task->wake_q;
888
889 /*
890 * Atomically grab the task, if ->wake_q is !nil already it means
b19a888c 891 * it's already queued (either by us or someone else) and will get the
76751049
PZ
892 * wakeup due to that.
893 *
4c4e3731
PZ
894 * In order to ensure that a pending wakeup will observe our pending
895 * state, even in the failed case, an explicit smp_mb() must be used.
76751049 896 */
4c4e3731 897 smp_mb__before_atomic();
87ff19cb 898 if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
07879c6a 899 return false;
76751049
PZ
900
901 /*
902 * The head is context local, there can be no concurrency.
903 */
904 *head->lastp = node;
905 head->lastp = &node->next;
07879c6a
DB
906 return true;
907}
908
909/**
910 * wake_q_add() - queue a wakeup for 'later' waking.
911 * @head: the wake_q_head to add @task to
912 * @task: the task to queue for 'later' wakeup
913 *
914 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
915 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
916 * instantly.
917 *
918 * This function must be used as-if it were wake_up_process(); IOW the task
919 * must be ready to be woken at this location.
920 */
921void wake_q_add(struct wake_q_head *head, struct task_struct *task)
922{
923 if (__wake_q_add(head, task))
924 get_task_struct(task);
925}
926
927/**
928 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
929 * @head: the wake_q_head to add @task to
930 * @task: the task to queue for 'later' wakeup
931 *
932 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
933 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
934 * instantly.
935 *
936 * This function must be used as-if it were wake_up_process(); IOW the task
937 * must be ready to be woken at this location.
938 *
939 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
940 * that already hold reference to @task can call the 'safe' version and trust
941 * wake_q to do the right thing depending whether or not the @task is already
942 * queued for wakeup.
943 */
944void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
945{
946 if (!__wake_q_add(head, task))
947 put_task_struct(task);
76751049
PZ
948}
949
950void wake_up_q(struct wake_q_head *head)
951{
952 struct wake_q_node *node = head->first;
953
954 while (node != WAKE_Q_TAIL) {
955 struct task_struct *task;
956
957 task = container_of(node, struct task_struct, wake_q);
d1ccc66d 958 /* Task can safely be re-inserted now: */
76751049
PZ
959 node = node->next;
960 task->wake_q.next = NULL;
961
962 /*
7696f991
AP
963 * wake_up_process() executes a full barrier, which pairs with
964 * the queueing in wake_q_add() so as not to miss wakeups.
76751049
PZ
965 */
966 wake_up_process(task);
967 put_task_struct(task);
968 }
969}
970
c24d20db 971/*
8875125e 972 * resched_curr - mark rq's current task 'to be rescheduled now'.
c24d20db
IM
973 *
974 * On UP this means the setting of the need_resched flag, on SMP it
975 * might also involve a cross-CPU call to trigger the scheduler on
976 * the target CPU.
977 */
8875125e 978void resched_curr(struct rq *rq)
c24d20db 979{
8875125e 980 struct task_struct *curr = rq->curr;
c24d20db
IM
981 int cpu;
982
5cb9eaa3 983 lockdep_assert_rq_held(rq);
c24d20db 984
8875125e 985 if (test_tsk_need_resched(curr))
c24d20db
IM
986 return;
987
8875125e 988 cpu = cpu_of(rq);
fd99f91a 989
f27dde8d 990 if (cpu == smp_processor_id()) {
8875125e 991 set_tsk_need_resched(curr);
f27dde8d 992 set_preempt_need_resched();
c24d20db 993 return;
f27dde8d 994 }
c24d20db 995
8875125e 996 if (set_nr_and_not_polling(curr))
c24d20db 997 smp_send_reschedule(cpu);
dfc68f29
AL
998 else
999 trace_sched_wake_idle_without_ipi(cpu);
c24d20db
IM
1000}
1001
029632fb 1002void resched_cpu(int cpu)
c24d20db
IM
1003{
1004 struct rq *rq = cpu_rq(cpu);
1005 unsigned long flags;
1006
5cb9eaa3 1007 raw_spin_rq_lock_irqsave(rq, flags);
a0982dfa
PM
1008 if (cpu_online(cpu) || cpu == smp_processor_id())
1009 resched_curr(rq);
5cb9eaa3 1010 raw_spin_rq_unlock_irqrestore(rq, flags);
c24d20db 1011}
06d8308c 1012
b021fe3e 1013#ifdef CONFIG_SMP
3451d024 1014#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2 1015/*
d1ccc66d
IM
1016 * In the semi idle case, use the nearest busy CPU for migrating timers
1017 * from an idle CPU. This is good for power-savings.
83cd4fe2
VP
1018 *
1019 * We don't do similar optimization for completely idle system, as
d1ccc66d
IM
1020 * selecting an idle CPU will add more delays to the timers than intended
1021 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
83cd4fe2 1022 */
bc7a34b8 1023int get_nohz_timer_target(void)
83cd4fe2 1024{
e938b9c9 1025 int i, cpu = smp_processor_id(), default_cpu = -1;
83cd4fe2 1026 struct sched_domain *sd;
031e3bd8 1027 const struct cpumask *hk_mask;
83cd4fe2 1028
04d4e665 1029 if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
e938b9c9
WL
1030 if (!idle_cpu(cpu))
1031 return cpu;
1032 default_cpu = cpu;
1033 }
6201b4d6 1034
04d4e665 1035 hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
031e3bd8 1036
057f3fad 1037 rcu_read_lock();
83cd4fe2 1038 for_each_domain(cpu, sd) {
031e3bd8 1039 for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
44496922
WL
1040 if (cpu == i)
1041 continue;
1042
e938b9c9 1043 if (!idle_cpu(i)) {
057f3fad
PZ
1044 cpu = i;
1045 goto unlock;
1046 }
1047 }
83cd4fe2 1048 }
9642d18e 1049
e938b9c9 1050 if (default_cpu == -1)
04d4e665 1051 default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
e938b9c9 1052 cpu = default_cpu;
057f3fad
PZ
1053unlock:
1054 rcu_read_unlock();
83cd4fe2
VP
1055 return cpu;
1056}
d1ccc66d 1057
06d8308c
TG
1058/*
1059 * When add_timer_on() enqueues a timer into the timer wheel of an
1060 * idle CPU then this timer might expire before the next timer event
1061 * which is scheduled to wake up that CPU. In case of a completely
1062 * idle system the next event might even be infinite time into the
1063 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1064 * leaves the inner idle loop so the newly added timer is taken into
1065 * account when the CPU goes back to idle and evaluates the timer
1066 * wheel for the next timer event.
1067 */
1c20091e 1068static void wake_up_idle_cpu(int cpu)
06d8308c
TG
1069{
1070 struct rq *rq = cpu_rq(cpu);
1071
1072 if (cpu == smp_processor_id())
1073 return;
1074
67b9ca70 1075 if (set_nr_and_not_polling(rq->idle))
06d8308c 1076 smp_send_reschedule(cpu);
dfc68f29
AL
1077 else
1078 trace_sched_wake_idle_without_ipi(cpu);
45bf76df
IM
1079}
1080
c5bfece2 1081static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 1082{
53c5fa16
FW
1083 /*
1084 * We just need the target to call irq_exit() and re-evaluate
1085 * the next tick. The nohz full kick at least implies that.
1086 * If needed we can still optimize that later with an
1087 * empty IRQ.
1088 */
379d9ecb
PM
1089 if (cpu_is_offline(cpu))
1090 return true; /* Don't try to wake offline CPUs. */
c5bfece2 1091 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
1092 if (cpu != smp_processor_id() ||
1093 tick_nohz_tick_stopped())
53c5fa16 1094 tick_nohz_full_kick_cpu(cpu);
1c20091e
FW
1095 return true;
1096 }
1097
1098 return false;
1099}
1100
379d9ecb
PM
1101/*
1102 * Wake up the specified CPU. If the CPU is going offline, it is the
1103 * caller's responsibility to deal with the lost wakeup, for example,
1104 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1105 */
1c20091e
FW
1106void wake_up_nohz_cpu(int cpu)
1107{
c5bfece2 1108 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
1109 wake_up_idle_cpu(cpu);
1110}
1111
19a1f5ec 1112static void nohz_csd_func(void *info)
45bf76df 1113{
19a1f5ec
PZ
1114 struct rq *rq = info;
1115 int cpu = cpu_of(rq);
1116 unsigned int flags;
873b4c65
VG
1117
1118 /*
19a1f5ec 1119 * Release the rq::nohz_csd.
873b4c65 1120 */
c6f88654 1121 flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
19a1f5ec 1122 WARN_ON(!(flags & NOHZ_KICK_MASK));
45bf76df 1123
19a1f5ec
PZ
1124 rq->idle_balance = idle_cpu(cpu);
1125 if (rq->idle_balance && !need_resched()) {
1126 rq->nohz_idle_balance = flags;
90b5363a
PZI
1127 raise_softirq_irqoff(SCHED_SOFTIRQ);
1128 }
2069dd75
PZ
1129}
1130
3451d024 1131#endif /* CONFIG_NO_HZ_COMMON */
d842de87 1132
ce831b38 1133#ifdef CONFIG_NO_HZ_FULL
76d92ac3 1134bool sched_can_stop_tick(struct rq *rq)
ce831b38 1135{
76d92ac3
FW
1136 int fifo_nr_running;
1137
1138 /* Deadline tasks, even if single, need the tick */
1139 if (rq->dl.dl_nr_running)
1140 return false;
1141
1e78cdbd 1142 /*
b19a888c 1143 * If there are more than one RR tasks, we need the tick to affect the
2548d546 1144 * actual RR behaviour.
1e78cdbd 1145 */
76d92ac3
FW
1146 if (rq->rt.rr_nr_running) {
1147 if (rq->rt.rr_nr_running == 1)
1148 return true;
1149 else
1150 return false;
1e78cdbd
RR
1151 }
1152
2548d546
PZ
1153 /*
1154 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1155 * forced preemption between FIFO tasks.
1156 */
1157 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
1158 if (fifo_nr_running)
1159 return true;
1160
1161 /*
1162 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1163 * if there's more than one we need the tick for involuntary
1164 * preemption.
1165 */
1166 if (rq->nr_running > 1)
541b8264 1167 return false;
ce831b38 1168
541b8264 1169 return true;
ce831b38
FW
1170}
1171#endif /* CONFIG_NO_HZ_FULL */
6d6bc0ad 1172#endif /* CONFIG_SMP */
18d95a28 1173
a790de99
PT
1174#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1175 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 1176/*
8277434e
PT
1177 * Iterate task_group tree rooted at *from, calling @down when first entering a
1178 * node and @up when leaving it for the final time.
1179 *
1180 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 1181 */
029632fb 1182int walk_tg_tree_from(struct task_group *from,
8277434e 1183 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
1184{
1185 struct task_group *parent, *child;
eb755805 1186 int ret;
c09595f6 1187
8277434e
PT
1188 parent = from;
1189
c09595f6 1190down:
eb755805
PZ
1191 ret = (*down)(parent, data);
1192 if (ret)
8277434e 1193 goto out;
c09595f6
PZ
1194 list_for_each_entry_rcu(child, &parent->children, siblings) {
1195 parent = child;
1196 goto down;
1197
1198up:
1199 continue;
1200 }
eb755805 1201 ret = (*up)(parent, data);
8277434e
PT
1202 if (ret || parent == from)
1203 goto out;
c09595f6
PZ
1204
1205 child = parent;
1206 parent = parent->parent;
1207 if (parent)
1208 goto up;
8277434e 1209out:
eb755805 1210 return ret;
c09595f6
PZ
1211}
1212
029632fb 1213int tg_nop(struct task_group *tg, void *data)
eb755805 1214{
e2b245f8 1215 return 0;
eb755805 1216}
18d95a28
PZ
1217#endif
1218
9059393e 1219static void set_load_weight(struct task_struct *p, bool update_load)
45bf76df 1220{
f05998d4
NR
1221 int prio = p->static_prio - MAX_RT_PRIO;
1222 struct load_weight *load = &p->se.load;
1223
dd41f596
IM
1224 /*
1225 * SCHED_IDLE tasks get minimal weight:
1226 */
1da1843f 1227 if (task_has_idle_policy(p)) {
c8b28116 1228 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 1229 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
1230 return;
1231 }
71f8bd46 1232
9059393e
VG
1233 /*
1234 * SCHED_OTHER tasks have to update their load when changing their
1235 * weight
1236 */
1237 if (update_load && p->sched_class == &fair_sched_class) {
1238 reweight_task(p, prio);
1239 } else {
1240 load->weight = scale_load(sched_prio_to_weight[prio]);
1241 load->inv_weight = sched_prio_to_wmult[prio];
1242 }
71f8bd46
IM
1243}
1244
69842cba 1245#ifdef CONFIG_UCLAMP_TASK
2480c093
PB
1246/*
1247 * Serializes updates of utilization clamp values
1248 *
1249 * The (slow-path) user-space triggers utilization clamp value updates which
1250 * can require updates on (fast-path) scheduler's data structures used to
1251 * support enqueue/dequeue operations.
1252 * While the per-CPU rq lock protects fast-path update operations, user-space
1253 * requests are serialized using a mutex to reduce the risk of conflicting
1254 * updates or API abuses.
1255 */
1256static DEFINE_MUTEX(uclamp_mutex);
1257
e8f14172
PB
1258/* Max allowed minimum utilization */
1259unsigned int sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
1260
1261/* Max allowed maximum utilization */
1262unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
1263
13685c4a
QY
1264/*
1265 * By default RT tasks run at the maximum performance point/capacity of the
1266 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1267 * SCHED_CAPACITY_SCALE.
1268 *
1269 * This knob allows admins to change the default behavior when uclamp is being
1270 * used. In battery powered devices, particularly, running at the maximum
1271 * capacity and frequency will increase energy consumption and shorten the
1272 * battery life.
1273 *
1274 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1275 *
1276 * This knob will not override the system default sched_util_clamp_min defined
1277 * above.
1278 */
1279unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
1280
e8f14172
PB
1281/* All clamps are required to be less or equal than these values */
1282static struct uclamp_se uclamp_default[UCLAMP_CNT];
69842cba 1283
46609ce2
QY
1284/*
1285 * This static key is used to reduce the uclamp overhead in the fast path. It
1286 * primarily disables the call to uclamp_rq_{inc, dec}() in
1287 * enqueue/dequeue_task().
1288 *
1289 * This allows users to continue to enable uclamp in their kernel config with
1290 * minimum uclamp overhead in the fast path.
1291 *
1292 * As soon as userspace modifies any of the uclamp knobs, the static key is
1293 * enabled, since we have an actual users that make use of uclamp
1294 * functionality.
1295 *
1296 * The knobs that would enable this static key are:
1297 *
1298 * * A task modifying its uclamp value with sched_setattr().
1299 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1300 * * An admin modifying the cgroup cpu.uclamp.{min, max}
1301 */
1302DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
1303
69842cba
PB
1304/* Integer rounded range for each bucket */
1305#define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1306
1307#define for_each_clamp_id(clamp_id) \
1308 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1309
1310static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
1311{
6d2f8909 1312 return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
69842cba
PB
1313}
1314
7763baac 1315static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
69842cba
PB
1316{
1317 if (clamp_id == UCLAMP_MIN)
1318 return 0;
1319 return SCHED_CAPACITY_SCALE;
1320}
1321
a509a7cd
PB
1322static inline void uclamp_se_set(struct uclamp_se *uc_se,
1323 unsigned int value, bool user_defined)
69842cba
PB
1324{
1325 uc_se->value = value;
1326 uc_se->bucket_id = uclamp_bucket_id(value);
a509a7cd 1327 uc_se->user_defined = user_defined;
69842cba
PB
1328}
1329
e496187d 1330static inline unsigned int
0413d7f3 1331uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
e496187d
PB
1332 unsigned int clamp_value)
1333{
1334 /*
1335 * Avoid blocked utilization pushing up the frequency when we go
1336 * idle (which drops the max-clamp) by retaining the last known
1337 * max-clamp.
1338 */
1339 if (clamp_id == UCLAMP_MAX) {
1340 rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1341 return clamp_value;
1342 }
1343
1344 return uclamp_none(UCLAMP_MIN);
1345}
1346
0413d7f3 1347static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
e496187d
PB
1348 unsigned int clamp_value)
1349{
1350 /* Reset max-clamp retention only on idle exit */
1351 if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1352 return;
1353
1354 WRITE_ONCE(rq->uclamp[clamp_id].value, clamp_value);
1355}
1356
69842cba 1357static inline
7763baac 1358unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
0413d7f3 1359 unsigned int clamp_value)
69842cba
PB
1360{
1361 struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1362 int bucket_id = UCLAMP_BUCKETS - 1;
1363
1364 /*
1365 * Since both min and max clamps are max aggregated, find the
1366 * top most bucket with tasks in.
1367 */
1368 for ( ; bucket_id >= 0; bucket_id--) {
1369 if (!bucket[bucket_id].tasks)
1370 continue;
1371 return bucket[bucket_id].value;
1372 }
1373
1374 /* No tasks -- default clamp values */
e496187d 1375 return uclamp_idle_value(rq, clamp_id, clamp_value);
69842cba
PB
1376}
1377
13685c4a
QY
1378static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1379{
1380 unsigned int default_util_min;
1381 struct uclamp_se *uc_se;
1382
1383 lockdep_assert_held(&p->pi_lock);
1384
1385 uc_se = &p->uclamp_req[UCLAMP_MIN];
1386
1387 /* Only sync if user didn't override the default */
1388 if (uc_se->user_defined)
1389 return;
1390
1391 default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1392 uclamp_se_set(uc_se, default_util_min, false);
1393}
1394
1395static void uclamp_update_util_min_rt_default(struct task_struct *p)
1396{
1397 struct rq_flags rf;
1398 struct rq *rq;
1399
1400 if (!rt_task(p))
1401 return;
1402
1403 /* Protect updates to p->uclamp_* */
1404 rq = task_rq_lock(p, &rf);
1405 __uclamp_update_util_min_rt_default(p);
1406 task_rq_unlock(rq, p, &rf);
1407}
1408
1409static void uclamp_sync_util_min_rt_default(void)
1410{
1411 struct task_struct *g, *p;
1412
1413 /*
1414 * copy_process() sysctl_uclamp
1415 * uclamp_min_rt = X;
1416 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1417 * // link thread smp_mb__after_spinlock()
1418 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1419 * sched_post_fork() for_each_process_thread()
1420 * __uclamp_sync_rt() __uclamp_sync_rt()
1421 *
1422 * Ensures that either sched_post_fork() will observe the new
1423 * uclamp_min_rt or for_each_process_thread() will observe the new
1424 * task.
1425 */
1426 read_lock(&tasklist_lock);
1427 smp_mb__after_spinlock();
1428 read_unlock(&tasklist_lock);
1429
1430 rcu_read_lock();
1431 for_each_process_thread(g, p)
1432 uclamp_update_util_min_rt_default(p);
1433 rcu_read_unlock();
1434}
1435
3eac870a 1436static inline struct uclamp_se
0413d7f3 1437uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
3eac870a 1438{
0213b708 1439 /* Copy by value as we could modify it */
3eac870a
PB
1440 struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1441#ifdef CONFIG_UCLAMP_TASK_GROUP
0213b708 1442 unsigned int tg_min, tg_max, value;
3eac870a
PB
1443
1444 /*
1445 * Tasks in autogroups or root task group will be
1446 * restricted by system defaults.
1447 */
1448 if (task_group_is_autogroup(task_group(p)))
1449 return uc_req;
1450 if (task_group(p) == &root_task_group)
1451 return uc_req;
1452
0213b708
QY
1453 tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1454 tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1455 value = uc_req.value;
1456 value = clamp(value, tg_min, tg_max);
1457 uclamp_se_set(&uc_req, value, false);
3eac870a
PB
1458#endif
1459
1460 return uc_req;
1461}
1462
e8f14172
PB
1463/*
1464 * The effective clamp bucket index of a task depends on, by increasing
1465 * priority:
1466 * - the task specific clamp value, when explicitly requested from userspace
3eac870a
PB
1467 * - the task group effective clamp value, for tasks not either in the root
1468 * group or in an autogroup
e8f14172
PB
1469 * - the system default clamp value, defined by the sysadmin
1470 */
1471static inline struct uclamp_se
0413d7f3 1472uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
e8f14172 1473{
3eac870a 1474 struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
e8f14172
PB
1475 struct uclamp_se uc_max = uclamp_default[clamp_id];
1476
1477 /* System default restrictions always apply */
1478 if (unlikely(uc_req.value > uc_max.value))
1479 return uc_max;
1480
1481 return uc_req;
1482}
1483
686516b5 1484unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
9d20ad7d
PB
1485{
1486 struct uclamp_se uc_eff;
1487
1488 /* Task currently refcounted: use back-annotated (effective) value */
1489 if (p->uclamp[clamp_id].active)
686516b5 1490 return (unsigned long)p->uclamp[clamp_id].value;
9d20ad7d
PB
1491
1492 uc_eff = uclamp_eff_get(p, clamp_id);
1493
686516b5 1494 return (unsigned long)uc_eff.value;
9d20ad7d
PB
1495}
1496
69842cba
PB
1497/*
1498 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1499 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1500 * updates the rq's clamp value if required.
60daf9c1
PB
1501 *
1502 * Tasks can have a task-specific value requested from user-space, track
1503 * within each bucket the maximum value for tasks refcounted in it.
1504 * This "local max aggregation" allows to track the exact "requested" value
1505 * for each bucket when all its RUNNABLE tasks require the same clamp.
69842cba
PB
1506 */
1507static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
0413d7f3 1508 enum uclamp_id clamp_id)
69842cba
PB
1509{
1510 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1511 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1512 struct uclamp_bucket *bucket;
1513
5cb9eaa3 1514 lockdep_assert_rq_held(rq);
69842cba 1515
e8f14172
PB
1516 /* Update task effective clamp */
1517 p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1518
69842cba
PB
1519 bucket = &uc_rq->bucket[uc_se->bucket_id];
1520 bucket->tasks++;
e8f14172 1521 uc_se->active = true;
69842cba 1522
e496187d
PB
1523 uclamp_idle_reset(rq, clamp_id, uc_se->value);
1524
60daf9c1
PB
1525 /*
1526 * Local max aggregation: rq buckets always track the max
1527 * "requested" clamp value of its RUNNABLE tasks.
1528 */
1529 if (bucket->tasks == 1 || uc_se->value > bucket->value)
1530 bucket->value = uc_se->value;
1531
69842cba 1532 if (uc_se->value > READ_ONCE(uc_rq->value))
60daf9c1 1533 WRITE_ONCE(uc_rq->value, uc_se->value);
69842cba
PB
1534}
1535
1536/*
1537 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1538 * is released. If this is the last task reference counting the rq's max
1539 * active clamp value, then the rq's clamp value is updated.
1540 *
1541 * Both refcounted tasks and rq's cached clamp values are expected to be
1542 * always valid. If it's detected they are not, as defensive programming,
1543 * enforce the expected state and warn.
1544 */
1545static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
0413d7f3 1546 enum uclamp_id clamp_id)
69842cba
PB
1547{
1548 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1549 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1550 struct uclamp_bucket *bucket;
e496187d 1551 unsigned int bkt_clamp;
69842cba
PB
1552 unsigned int rq_clamp;
1553
5cb9eaa3 1554 lockdep_assert_rq_held(rq);
69842cba 1555
46609ce2
QY
1556 /*
1557 * If sched_uclamp_used was enabled after task @p was enqueued,
1558 * we could end up with unbalanced call to uclamp_rq_dec_id().
1559 *
1560 * In this case the uc_se->active flag should be false since no uclamp
1561 * accounting was performed at enqueue time and we can just return
1562 * here.
1563 *
b19a888c 1564 * Need to be careful of the following enqueue/dequeue ordering
46609ce2
QY
1565 * problem too
1566 *
1567 * enqueue(taskA)
1568 * // sched_uclamp_used gets enabled
1569 * enqueue(taskB)
1570 * dequeue(taskA)
b19a888c 1571 * // Must not decrement bucket->tasks here
46609ce2
QY
1572 * dequeue(taskB)
1573 *
1574 * where we could end up with stale data in uc_se and
1575 * bucket[uc_se->bucket_id].
1576 *
1577 * The following check here eliminates the possibility of such race.
1578 */
1579 if (unlikely(!uc_se->active))
1580 return;
1581
69842cba 1582 bucket = &uc_rq->bucket[uc_se->bucket_id];
46609ce2 1583
69842cba
PB
1584 SCHED_WARN_ON(!bucket->tasks);
1585 if (likely(bucket->tasks))
1586 bucket->tasks--;
46609ce2 1587
e8f14172 1588 uc_se->active = false;
69842cba 1589
60daf9c1
PB
1590 /*
1591 * Keep "local max aggregation" simple and accept to (possibly)
1592 * overboost some RUNNABLE tasks in the same bucket.
1593 * The rq clamp bucket value is reset to its base value whenever
1594 * there are no more RUNNABLE tasks refcounting it.
1595 */
69842cba
PB
1596 if (likely(bucket->tasks))
1597 return;
1598
1599 rq_clamp = READ_ONCE(uc_rq->value);
1600 /*
1601 * Defensive programming: this should never happen. If it happens,
1602 * e.g. due to future modification, warn and fixup the expected value.
1603 */
1604 SCHED_WARN_ON(bucket->value > rq_clamp);
e496187d
PB
1605 if (bucket->value >= rq_clamp) {
1606 bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1607 WRITE_ONCE(uc_rq->value, bkt_clamp);
1608 }
69842cba
PB
1609}
1610
1611static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1612{
0413d7f3 1613 enum uclamp_id clamp_id;
69842cba 1614
46609ce2
QY
1615 /*
1616 * Avoid any overhead until uclamp is actually used by the userspace.
1617 *
1618 * The condition is constructed such that a NOP is generated when
1619 * sched_uclamp_used is disabled.
1620 */
1621 if (!static_branch_unlikely(&sched_uclamp_used))
1622 return;
1623
69842cba
PB
1624 if (unlikely(!p->sched_class->uclamp_enabled))
1625 return;
1626
1627 for_each_clamp_id(clamp_id)
1628 uclamp_rq_inc_id(rq, p, clamp_id);
e496187d
PB
1629
1630 /* Reset clamp idle holding when there is one RUNNABLE task */
1631 if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1632 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
69842cba
PB
1633}
1634
1635static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1636{
0413d7f3 1637 enum uclamp_id clamp_id;
69842cba 1638
46609ce2
QY
1639 /*
1640 * Avoid any overhead until uclamp is actually used by the userspace.
1641 *
1642 * The condition is constructed such that a NOP is generated when
1643 * sched_uclamp_used is disabled.
1644 */
1645 if (!static_branch_unlikely(&sched_uclamp_used))
1646 return;
1647
69842cba
PB
1648 if (unlikely(!p->sched_class->uclamp_enabled))
1649 return;
1650
1651 for_each_clamp_id(clamp_id)
1652 uclamp_rq_dec_id(rq, p, clamp_id);
1653}
1654
ca4984a7
QP
1655static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1656 enum uclamp_id clamp_id)
1657{
1658 if (!p->uclamp[clamp_id].active)
1659 return;
1660
1661 uclamp_rq_dec_id(rq, p, clamp_id);
1662 uclamp_rq_inc_id(rq, p, clamp_id);
1663
1664 /*
1665 * Make sure to clear the idle flag if we've transiently reached 0
1666 * active tasks on rq.
1667 */
1668 if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1669 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1670}
1671
babbe170 1672static inline void
0213b708 1673uclamp_update_active(struct task_struct *p)
babbe170 1674{
0213b708 1675 enum uclamp_id clamp_id;
babbe170
PB
1676 struct rq_flags rf;
1677 struct rq *rq;
1678
1679 /*
1680 * Lock the task and the rq where the task is (or was) queued.
1681 *
1682 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1683 * price to pay to safely serialize util_{min,max} updates with
1684 * enqueues, dequeues and migration operations.
1685 * This is the same locking schema used by __set_cpus_allowed_ptr().
1686 */
1687 rq = task_rq_lock(p, &rf);
1688
1689 /*
1690 * Setting the clamp bucket is serialized by task_rq_lock().
1691 * If the task is not yet RUNNABLE and its task_struct is not
1692 * affecting a valid clamp bucket, the next time it's enqueued,
1693 * it will already see the updated clamp bucket value.
1694 */
ca4984a7
QP
1695 for_each_clamp_id(clamp_id)
1696 uclamp_rq_reinc_id(rq, p, clamp_id);
babbe170
PB
1697
1698 task_rq_unlock(rq, p, &rf);
1699}
1700
e3b8b6a0 1701#ifdef CONFIG_UCLAMP_TASK_GROUP
babbe170 1702static inline void
0213b708 1703uclamp_update_active_tasks(struct cgroup_subsys_state *css)
babbe170
PB
1704{
1705 struct css_task_iter it;
1706 struct task_struct *p;
babbe170
PB
1707
1708 css_task_iter_start(css, 0, &it);
0213b708
QY
1709 while ((p = css_task_iter_next(&it)))
1710 uclamp_update_active(p);
babbe170
PB
1711 css_task_iter_end(&it);
1712}
1713
7274a5c1
PB
1714static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1715static void uclamp_update_root_tg(void)
1716{
1717 struct task_group *tg = &root_task_group;
1718
1719 uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1720 sysctl_sched_uclamp_util_min, false);
1721 uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1722 sysctl_sched_uclamp_util_max, false);
1723
1724 rcu_read_lock();
1725 cpu_util_update_eff(&root_task_group.css);
1726 rcu_read_unlock();
1727}
1728#else
1729static void uclamp_update_root_tg(void) { }
1730#endif
1731
e8f14172 1732int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
32927393 1733 void *buffer, size_t *lenp, loff_t *ppos)
e8f14172 1734{
7274a5c1 1735 bool update_root_tg = false;
13685c4a 1736 int old_min, old_max, old_min_rt;
e8f14172
PB
1737 int result;
1738
2480c093 1739 mutex_lock(&uclamp_mutex);
e8f14172
PB
1740 old_min = sysctl_sched_uclamp_util_min;
1741 old_max = sysctl_sched_uclamp_util_max;
13685c4a 1742 old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
e8f14172
PB
1743
1744 result = proc_dointvec(table, write, buffer, lenp, ppos);
1745 if (result)
1746 goto undo;
1747 if (!write)
1748 goto done;
1749
1750 if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
13685c4a
QY
1751 sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
1752 sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1753
e8f14172
PB
1754 result = -EINVAL;
1755 goto undo;
1756 }
1757
1758 if (old_min != sysctl_sched_uclamp_util_min) {
1759 uclamp_se_set(&uclamp_default[UCLAMP_MIN],
a509a7cd 1760 sysctl_sched_uclamp_util_min, false);
7274a5c1 1761 update_root_tg = true;
e8f14172
PB
1762 }
1763 if (old_max != sysctl_sched_uclamp_util_max) {
1764 uclamp_se_set(&uclamp_default[UCLAMP_MAX],
a509a7cd 1765 sysctl_sched_uclamp_util_max, false);
7274a5c1 1766 update_root_tg = true;
e8f14172
PB
1767 }
1768
46609ce2
QY
1769 if (update_root_tg) {
1770 static_branch_enable(&sched_uclamp_used);
7274a5c1 1771 uclamp_update_root_tg();
46609ce2 1772 }
7274a5c1 1773
13685c4a
QY
1774 if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1775 static_branch_enable(&sched_uclamp_used);
1776 uclamp_sync_util_min_rt_default();
1777 }
7274a5c1 1778
e8f14172 1779 /*
7274a5c1
PB
1780 * We update all RUNNABLE tasks only when task groups are in use.
1781 * Otherwise, keep it simple and do just a lazy update at each next
1782 * task enqueue time.
e8f14172 1783 */
7274a5c1 1784
e8f14172
PB
1785 goto done;
1786
1787undo:
1788 sysctl_sched_uclamp_util_min = old_min;
1789 sysctl_sched_uclamp_util_max = old_max;
13685c4a 1790 sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
e8f14172 1791done:
2480c093 1792 mutex_unlock(&uclamp_mutex);
e8f14172
PB
1793
1794 return result;
1795}
1796
a509a7cd
PB
1797static int uclamp_validate(struct task_struct *p,
1798 const struct sched_attr *attr)
1799{
480a6ca2
DE
1800 int util_min = p->uclamp_req[UCLAMP_MIN].value;
1801 int util_max = p->uclamp_req[UCLAMP_MAX].value;
a509a7cd 1802
480a6ca2
DE
1803 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1804 util_min = attr->sched_util_min;
a509a7cd 1805
480a6ca2
DE
1806 if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
1807 return -EINVAL;
1808 }
1809
1810 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1811 util_max = attr->sched_util_max;
1812
1813 if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
1814 return -EINVAL;
1815 }
1816
1817 if (util_min != -1 && util_max != -1 && util_min > util_max)
a509a7cd
PB
1818 return -EINVAL;
1819
e65855a5
QY
1820 /*
1821 * We have valid uclamp attributes; make sure uclamp is enabled.
1822 *
1823 * We need to do that here, because enabling static branches is a
1824 * blocking operation which obviously cannot be done while holding
1825 * scheduler locks.
1826 */
1827 static_branch_enable(&sched_uclamp_used);
1828
a509a7cd
PB
1829 return 0;
1830}
1831
480a6ca2
DE
1832static bool uclamp_reset(const struct sched_attr *attr,
1833 enum uclamp_id clamp_id,
1834 struct uclamp_se *uc_se)
1835{
1836 /* Reset on sched class change for a non user-defined clamp value. */
1837 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
1838 !uc_se->user_defined)
1839 return true;
1840
1841 /* Reset on sched_util_{min,max} == -1. */
1842 if (clamp_id == UCLAMP_MIN &&
1843 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1844 attr->sched_util_min == -1) {
1845 return true;
1846 }
1847
1848 if (clamp_id == UCLAMP_MAX &&
1849 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1850 attr->sched_util_max == -1) {
1851 return true;
1852 }
1853
1854 return false;
1855}
1856
a509a7cd
PB
1857static void __setscheduler_uclamp(struct task_struct *p,
1858 const struct sched_attr *attr)
1859{
0413d7f3 1860 enum uclamp_id clamp_id;
1a00d999 1861
1a00d999
PB
1862 for_each_clamp_id(clamp_id) {
1863 struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
480a6ca2 1864 unsigned int value;
1a00d999 1865
480a6ca2 1866 if (!uclamp_reset(attr, clamp_id, uc_se))
1a00d999
PB
1867 continue;
1868
13685c4a
QY
1869 /*
1870 * RT by default have a 100% boost value that could be modified
1871 * at runtime.
1872 */
1a00d999 1873 if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
480a6ca2 1874 value = sysctl_sched_uclamp_util_min_rt_default;
13685c4a 1875 else
480a6ca2
DE
1876 value = uclamp_none(clamp_id);
1877
1878 uclamp_se_set(uc_se, value, false);
1a00d999 1879
1a00d999
PB
1880 }
1881
a509a7cd
PB
1882 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1883 return;
1884
480a6ca2
DE
1885 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1886 attr->sched_util_min != -1) {
a509a7cd
PB
1887 uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1888 attr->sched_util_min, true);
1889 }
1890
480a6ca2
DE
1891 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1892 attr->sched_util_max != -1) {
a509a7cd
PB
1893 uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1894 attr->sched_util_max, true);
1895 }
1896}
1897
e8f14172
PB
1898static void uclamp_fork(struct task_struct *p)
1899{
0413d7f3 1900 enum uclamp_id clamp_id;
e8f14172 1901
13685c4a
QY
1902 /*
1903 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1904 * as the task is still at its early fork stages.
1905 */
e8f14172
PB
1906 for_each_clamp_id(clamp_id)
1907 p->uclamp[clamp_id].active = false;
a87498ac
PB
1908
1909 if (likely(!p->sched_reset_on_fork))
1910 return;
1911
1912 for_each_clamp_id(clamp_id) {
eaf5a92e
QP
1913 uclamp_se_set(&p->uclamp_req[clamp_id],
1914 uclamp_none(clamp_id), false);
a87498ac 1915 }
e8f14172
PB
1916}
1917
13685c4a
QY
1918static void uclamp_post_fork(struct task_struct *p)
1919{
1920 uclamp_update_util_min_rt_default(p);
1921}
1922
d81ae8aa
QY
1923static void __init init_uclamp_rq(struct rq *rq)
1924{
1925 enum uclamp_id clamp_id;
1926 struct uclamp_rq *uc_rq = rq->uclamp;
1927
1928 for_each_clamp_id(clamp_id) {
1929 uc_rq[clamp_id] = (struct uclamp_rq) {
1930 .value = uclamp_none(clamp_id)
1931 };
1932 }
1933
315c4f88 1934 rq->uclamp_flags = UCLAMP_FLAG_IDLE;
d81ae8aa
QY
1935}
1936
69842cba
PB
1937static void __init init_uclamp(void)
1938{
e8f14172 1939 struct uclamp_se uc_max = {};
0413d7f3 1940 enum uclamp_id clamp_id;
69842cba
PB
1941 int cpu;
1942
d81ae8aa
QY
1943 for_each_possible_cpu(cpu)
1944 init_uclamp_rq(cpu_rq(cpu));
69842cba 1945
69842cba 1946 for_each_clamp_id(clamp_id) {
e8f14172 1947 uclamp_se_set(&init_task.uclamp_req[clamp_id],
a509a7cd 1948 uclamp_none(clamp_id), false);
69842cba 1949 }
e8f14172
PB
1950
1951 /* System defaults allow max clamp values for both indexes */
a509a7cd 1952 uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
2480c093 1953 for_each_clamp_id(clamp_id) {
e8f14172 1954 uclamp_default[clamp_id] = uc_max;
2480c093
PB
1955#ifdef CONFIG_UCLAMP_TASK_GROUP
1956 root_task_group.uclamp_req[clamp_id] = uc_max;
0b60ba2d 1957 root_task_group.uclamp[clamp_id] = uc_max;
2480c093
PB
1958#endif
1959 }
69842cba
PB
1960}
1961
1962#else /* CONFIG_UCLAMP_TASK */
1963static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
1964static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
a509a7cd
PB
1965static inline int uclamp_validate(struct task_struct *p,
1966 const struct sched_attr *attr)
1967{
1968 return -EOPNOTSUPP;
1969}
1970static void __setscheduler_uclamp(struct task_struct *p,
1971 const struct sched_attr *attr) { }
e8f14172 1972static inline void uclamp_fork(struct task_struct *p) { }
13685c4a 1973static inline void uclamp_post_fork(struct task_struct *p) { }
69842cba
PB
1974static inline void init_uclamp(void) { }
1975#endif /* CONFIG_UCLAMP_TASK */
1976
a1dfb631
MT
1977bool sched_task_on_rq(struct task_struct *p)
1978{
1979 return task_on_rq_queued(p);
1980}
1981
42a20f86
KC
1982unsigned long get_wchan(struct task_struct *p)
1983{
1984 unsigned long ip = 0;
1985 unsigned int state;
1986
1987 if (!p || p == current)
1988 return 0;
1989
1990 /* Only get wchan if task is blocked and we can keep it that way. */
1991 raw_spin_lock_irq(&p->pi_lock);
1992 state = READ_ONCE(p->__state);
1993 smp_rmb(); /* see try_to_wake_up() */
1994 if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
1995 ip = __get_wchan(p);
1996 raw_spin_unlock_irq(&p->pi_lock);
1997
1998 return ip;
1999}
2000
1de64443 2001static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 2002{
0a67d1ee
PZ
2003 if (!(flags & ENQUEUE_NOCLOCK))
2004 update_rq_clock(rq);
2005
eb414681 2006 if (!(flags & ENQUEUE_RESTORE)) {
4e29fb70 2007 sched_info_enqueue(rq, p);
eb414681
JW
2008 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
2009 }
0a67d1ee 2010
69842cba 2011 uclamp_rq_inc(rq, p);
371fd7e7 2012 p->sched_class->enqueue_task(rq, p, flags);
8a311c74
PZ
2013
2014 if (sched_core_enabled(rq))
2015 sched_core_enqueue(rq, p);
71f8bd46
IM
2016}
2017
1de64443 2018static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 2019{
8a311c74 2020 if (sched_core_enabled(rq))
4feee7d1 2021 sched_core_dequeue(rq, p, flags);
8a311c74 2022
0a67d1ee
PZ
2023 if (!(flags & DEQUEUE_NOCLOCK))
2024 update_rq_clock(rq);
2025
eb414681 2026 if (!(flags & DEQUEUE_SAVE)) {
4e29fb70 2027 sched_info_dequeue(rq, p);
eb414681
JW
2028 psi_dequeue(p, flags & DEQUEUE_SLEEP);
2029 }
0a67d1ee 2030
69842cba 2031 uclamp_rq_dec(rq, p);
371fd7e7 2032 p->sched_class->dequeue_task(rq, p, flags);
71f8bd46
IM
2033}
2034
029632fb 2035void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd 2036{
371fd7e7 2037 enqueue_task(rq, p, flags);
7dd77884
PZ
2038
2039 p->on_rq = TASK_ON_RQ_QUEUED;
1e3c88bd
PZ
2040}
2041
029632fb 2042void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd 2043{
7dd77884
PZ
2044 p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
2045
371fd7e7 2046 dequeue_task(rq, p, flags);
1e3c88bd
PZ
2047}
2048
f558c2b8 2049static inline int __normal_prio(int policy, int rt_prio, int nice)
14531189 2050{
f558c2b8
PZ
2051 int prio;
2052
2053 if (dl_policy(policy))
2054 prio = MAX_DL_PRIO - 1;
2055 else if (rt_policy(policy))
2056 prio = MAX_RT_PRIO - 1 - rt_prio;
2057 else
2058 prio = NICE_TO_PRIO(nice);
2059
2060 return prio;
14531189
IM
2061}
2062
b29739f9
IM
2063/*
2064 * Calculate the expected normal priority: i.e. priority
2065 * without taking RT-inheritance into account. Might be
2066 * boosted by interactivity modifiers. Changes upon fork,
2067 * setprio syscalls, and whenever the interactivity
2068 * estimator recalculates.
2069 */
36c8b586 2070static inline int normal_prio(struct task_struct *p)
b29739f9 2071{
f558c2b8 2072 return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
b29739f9
IM
2073}
2074
2075/*
2076 * Calculate the current priority, i.e. the priority
2077 * taken into account by the scheduler. This value might
2078 * be boosted by RT tasks, or might be boosted by
2079 * interactivity modifiers. Will be RT if the task got
2080 * RT-boosted. If not then it returns p->normal_prio.
2081 */
36c8b586 2082static int effective_prio(struct task_struct *p)
b29739f9
IM
2083{
2084 p->normal_prio = normal_prio(p);
2085 /*
2086 * If we are RT tasks or we were boosted to RT priority,
2087 * keep the priority unchanged. Otherwise, update priority
2088 * to the normal priority:
2089 */
2090 if (!rt_prio(p->prio))
2091 return p->normal_prio;
2092 return p->prio;
2093}
2094
1da177e4
LT
2095/**
2096 * task_curr - is this task currently executing on a CPU?
2097 * @p: the task in question.
e69f6186
YB
2098 *
2099 * Return: 1 if the task is currently executing. 0 otherwise.
1da177e4 2100 */
36c8b586 2101inline int task_curr(const struct task_struct *p)
1da177e4
LT
2102{
2103 return cpu_curr(task_cpu(p)) == p;
2104}
2105
67dfa1b7 2106/*
4c9a4bc8
PZ
2107 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2108 * use the balance_callback list if you want balancing.
2109 *
2110 * this means any call to check_class_changed() must be followed by a call to
2111 * balance_callback().
67dfa1b7 2112 */
cb469845
SR
2113static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2114 const struct sched_class *prev_class,
da7a735e 2115 int oldprio)
cb469845
SR
2116{
2117 if (prev_class != p->sched_class) {
2118 if (prev_class->switched_from)
da7a735e 2119 prev_class->switched_from(rq, p);
4c9a4bc8 2120
da7a735e 2121 p->sched_class->switched_to(rq, p);
2d3d891d 2122 } else if (oldprio != p->prio || dl_task(p))
da7a735e 2123 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
2124}
2125
029632fb 2126void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405 2127{
aa93cd53 2128 if (p->sched_class == rq->curr->sched_class)
1e5a7405 2129 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
aa93cd53
KT
2130 else if (p->sched_class > rq->curr->sched_class)
2131 resched_curr(rq);
1e5a7405
PZ
2132
2133 /*
2134 * A queue event has occurred, and we're going to schedule. In
2135 * this case, we can save a useless back to back clock update.
2136 */
da0c1e65 2137 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
adcc8da8 2138 rq_clock_skip_update(rq);
1e5a7405
PZ
2139}
2140
1da177e4 2141#ifdef CONFIG_SMP
175f0e25 2142
af449901
PZ
2143static void
2144__do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags);
2145
2146static int __set_cpus_allowed_ptr(struct task_struct *p,
2147 const struct cpumask *new_mask,
2148 u32 flags);
2149
2150static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
2151{
2152 if (likely(!p->migration_disabled))
2153 return;
2154
2155 if (p->cpus_ptr != &p->cpus_mask)
2156 return;
2157
2158 /*
2159 * Violates locking rules! see comment in __do_set_cpus_allowed().
2160 */
2161 __do_set_cpus_allowed(p, cpumask_of(rq->cpu), SCA_MIGRATE_DISABLE);
2162}
2163
2164void migrate_disable(void)
2165{
3015ef4b
TG
2166 struct task_struct *p = current;
2167
2168 if (p->migration_disabled) {
2169 p->migration_disabled++;
af449901 2170 return;
3015ef4b 2171 }
af449901 2172
3015ef4b
TG
2173 preempt_disable();
2174 this_rq()->nr_pinned++;
2175 p->migration_disabled = 1;
2176 preempt_enable();
af449901
PZ
2177}
2178EXPORT_SYMBOL_GPL(migrate_disable);
2179
2180void migrate_enable(void)
2181{
2182 struct task_struct *p = current;
2183
6d337eab
PZ
2184 if (p->migration_disabled > 1) {
2185 p->migration_disabled--;
af449901 2186 return;
6d337eab 2187 }
af449901 2188
9d0df377
SAS
2189 if (WARN_ON_ONCE(!p->migration_disabled))
2190 return;
2191
6d337eab
PZ
2192 /*
2193 * Ensure stop_task runs either before or after this, and that
2194 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2195 */
2196 preempt_disable();
2197 if (p->cpus_ptr != &p->cpus_mask)
2198 __set_cpus_allowed_ptr(p, &p->cpus_mask, SCA_MIGRATE_ENABLE);
2199 /*
2200 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2201 * regular cpus_mask, otherwise things that race (eg.
2202 * select_fallback_rq) get confused.
2203 */
af449901 2204 barrier();
6d337eab 2205 p->migration_disabled = 0;
3015ef4b 2206 this_rq()->nr_pinned--;
6d337eab 2207 preempt_enable();
af449901
PZ
2208}
2209EXPORT_SYMBOL_GPL(migrate_enable);
2210
3015ef4b
TG
2211static inline bool rq_has_pinned_tasks(struct rq *rq)
2212{
2213 return rq->nr_pinned;
2214}
2215
175f0e25 2216/*
bee98539 2217 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
175f0e25
PZ
2218 * __set_cpus_allowed_ptr() and select_fallback_rq().
2219 */
2220static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
2221{
5ba2ffba 2222 /* When not in the task's cpumask, no point in looking further. */
3bd37062 2223 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
175f0e25
PZ
2224 return false;
2225
5ba2ffba
PZ
2226 /* migrate_disabled() must be allowed to finish. */
2227 if (is_migration_disabled(p))
175f0e25
PZ
2228 return cpu_online(cpu);
2229
5ba2ffba
PZ
2230 /* Non kernel threads are not allowed during either online or offline. */
2231 if (!(p->flags & PF_KTHREAD))
9ae606bc 2232 return cpu_active(cpu) && task_cpu_possible(cpu, p);
5ba2ffba
PZ
2233
2234 /* KTHREAD_IS_PER_CPU is always allowed. */
2235 if (kthread_is_per_cpu(p))
2236 return cpu_online(cpu);
2237
2238 /* Regular kernel threads don't get to stay during offline. */
b5c44773 2239 if (cpu_dying(cpu))
5ba2ffba
PZ
2240 return false;
2241
2242 /* But are allowed during online. */
2243 return cpu_online(cpu);
175f0e25
PZ
2244}
2245
5cc389bc
PZ
2246/*
2247 * This is how migration works:
2248 *
2249 * 1) we invoke migration_cpu_stop() on the target CPU using
2250 * stop_one_cpu().
2251 * 2) stopper starts to run (implicitly forcing the migrated thread
2252 * off the CPU)
2253 * 3) it checks whether the migrated task is still in the wrong runqueue.
2254 * 4) if it's in the wrong runqueue then the migration thread removes
2255 * it and puts it into the right queue.
2256 * 5) stopper completes and stop_one_cpu() returns and the migration
2257 * is done.
2258 */
2259
2260/*
2261 * move_queued_task - move a queued task to new rq.
2262 *
2263 * Returns (locked) new rq. Old rq's lock is released.
2264 */
8a8c69c3
PZ
2265static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
2266 struct task_struct *p, int new_cpu)
5cc389bc 2267{
5cb9eaa3 2268 lockdep_assert_rq_held(rq);
5cc389bc 2269
58877d34 2270 deactivate_task(rq, p, DEQUEUE_NOCLOCK);
5cc389bc 2271 set_task_cpu(p, new_cpu);
8a8c69c3 2272 rq_unlock(rq, rf);
5cc389bc
PZ
2273
2274 rq = cpu_rq(new_cpu);
2275
8a8c69c3 2276 rq_lock(rq, rf);
5cc389bc 2277 BUG_ON(task_cpu(p) != new_cpu);
58877d34 2278 activate_task(rq, p, 0);
5cc389bc
PZ
2279 check_preempt_curr(rq, p, 0);
2280
2281 return rq;
2282}
2283
2284struct migration_arg {
6d337eab
PZ
2285 struct task_struct *task;
2286 int dest_cpu;
2287 struct set_affinity_pending *pending;
2288};
2289
50caf9c1
PZ
2290/*
2291 * @refs: number of wait_for_completion()
2292 * @stop_pending: is @stop_work in use
2293 */
6d337eab
PZ
2294struct set_affinity_pending {
2295 refcount_t refs;
9e81889c 2296 unsigned int stop_pending;
6d337eab
PZ
2297 struct completion done;
2298 struct cpu_stop_work stop_work;
2299 struct migration_arg arg;
5cc389bc
PZ
2300};
2301
2302/*
d1ccc66d 2303 * Move (not current) task off this CPU, onto the destination CPU. We're doing
5cc389bc
PZ
2304 * this because either it can't run here any more (set_cpus_allowed()
2305 * away from this CPU, or CPU going down), or because we're
2306 * attempting to rebalance this task on exec (sched_exec).
2307 *
2308 * So we race with normal scheduler movements, but that's OK, as long
2309 * as the task is no longer on this CPU.
5cc389bc 2310 */
8a8c69c3
PZ
2311static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
2312 struct task_struct *p, int dest_cpu)
5cc389bc 2313{
5cc389bc 2314 /* Affinity changed (again). */
175f0e25 2315 if (!is_cpu_allowed(p, dest_cpu))
5e16bbc2 2316 return rq;
5cc389bc 2317
15ff991e 2318 update_rq_clock(rq);
8a8c69c3 2319 rq = move_queued_task(rq, rf, p, dest_cpu);
5e16bbc2
PZ
2320
2321 return rq;
5cc389bc
PZ
2322}
2323
2324/*
2325 * migration_cpu_stop - this will be executed by a highprio stopper thread
2326 * and performs thread migration by bumping thread off CPU then
2327 * 'pushing' onto another runqueue.
2328 */
2329static int migration_cpu_stop(void *data)
2330{
2331 struct migration_arg *arg = data;
c20cf065 2332 struct set_affinity_pending *pending = arg->pending;
5e16bbc2
PZ
2333 struct task_struct *p = arg->task;
2334 struct rq *rq = this_rq();
6d337eab 2335 bool complete = false;
8a8c69c3 2336 struct rq_flags rf;
5cc389bc
PZ
2337
2338 /*
d1ccc66d
IM
2339 * The original target CPU might have gone down and we might
2340 * be on another CPU but it doesn't matter.
5cc389bc 2341 */
6d337eab 2342 local_irq_save(rf.flags);
5cc389bc
PZ
2343 /*
2344 * We need to explicitly wake pending tasks before running
3bd37062 2345 * __migrate_task() such that we will not miss enforcing cpus_ptr
5cc389bc
PZ
2346 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2347 */
a1488664 2348 flush_smp_call_function_from_idle();
5e16bbc2
PZ
2349
2350 raw_spin_lock(&p->pi_lock);
8a8c69c3 2351 rq_lock(rq, &rf);
6d337eab 2352
e140749c
VS
2353 /*
2354 * If we were passed a pending, then ->stop_pending was set, thus
2355 * p->migration_pending must have remained stable.
2356 */
2357 WARN_ON_ONCE(pending && pending != p->migration_pending);
2358
5e16bbc2
PZ
2359 /*
2360 * If task_rq(p) != rq, it cannot be migrated here, because we're
2361 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2362 * we're holding p->pi_lock.
2363 */
bf89a304 2364 if (task_rq(p) == rq) {
6d337eab
PZ
2365 if (is_migration_disabled(p))
2366 goto out;
2367
2368 if (pending) {
e140749c 2369 p->migration_pending = NULL;
6d337eab 2370 complete = true;
6d337eab 2371
3f1bc119
PZ
2372 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
2373 goto out;
3f1bc119 2374 }
6d337eab 2375
bf89a304 2376 if (task_on_rq_queued(p))
475ea6c6 2377 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
bf89a304 2378 else
475ea6c6 2379 p->wake_cpu = arg->dest_cpu;
6d337eab 2380
3f1bc119
PZ
2381 /*
2382 * XXX __migrate_task() can fail, at which point we might end
2383 * up running on a dodgy CPU, AFAICT this can only happen
2384 * during CPU hotplug, at which point we'll get pushed out
2385 * anyway, so it's probably not a big deal.
2386 */
2387
c20cf065 2388 } else if (pending) {
6d337eab
PZ
2389 /*
2390 * This happens when we get migrated between migrate_enable()'s
2391 * preempt_enable() and scheduling the stopper task. At that
2392 * point we're a regular task again and not current anymore.
2393 *
2394 * A !PREEMPT kernel has a giant hole here, which makes it far
2395 * more likely.
2396 */
2397
d707faa6
VS
2398 /*
2399 * The task moved before the stopper got to run. We're holding
2400 * ->pi_lock, so the allowed mask is stable - if it got
2401 * somewhere allowed, we're done.
2402 */
c20cf065 2403 if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
e140749c 2404 p->migration_pending = NULL;
d707faa6
VS
2405 complete = true;
2406 goto out;
2407 }
2408
6d337eab
PZ
2409 /*
2410 * When migrate_enable() hits a rq mis-match we can't reliably
2411 * determine is_migration_disabled() and so have to chase after
2412 * it.
2413 */
9e81889c 2414 WARN_ON_ONCE(!pending->stop_pending);
6d337eab
PZ
2415 task_rq_unlock(rq, p, &rf);
2416 stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
2417 &pending->arg, &pending->stop_work);
2418 return 0;
bf89a304 2419 }
6d337eab 2420out:
9e81889c
PZ
2421 if (pending)
2422 pending->stop_pending = false;
6d337eab
PZ
2423 task_rq_unlock(rq, p, &rf);
2424
2425 if (complete)
2426 complete_all(&pending->done);
2427
5cc389bc
PZ
2428 return 0;
2429}
2430
a7c81556
PZ
2431int push_cpu_stop(void *arg)
2432{
2433 struct rq *lowest_rq = NULL, *rq = this_rq();
2434 struct task_struct *p = arg;
2435
2436 raw_spin_lock_irq(&p->pi_lock);
5cb9eaa3 2437 raw_spin_rq_lock(rq);
a7c81556
PZ
2438
2439 if (task_rq(p) != rq)
2440 goto out_unlock;
2441
2442 if (is_migration_disabled(p)) {
2443 p->migration_flags |= MDF_PUSH;
2444 goto out_unlock;
2445 }
2446
2447 p->migration_flags &= ~MDF_PUSH;
2448
2449 if (p->sched_class->find_lock_rq)
2450 lowest_rq = p->sched_class->find_lock_rq(p, rq);
5e16bbc2 2451
a7c81556
PZ
2452 if (!lowest_rq)
2453 goto out_unlock;
2454
2455 // XXX validate p is still the highest prio task
2456 if (task_rq(p) == rq) {
2457 deactivate_task(rq, p, 0);
2458 set_task_cpu(p, lowest_rq->cpu);
2459 activate_task(lowest_rq, p, 0);
2460 resched_curr(lowest_rq);
2461 }
2462
2463 double_unlock_balance(rq, lowest_rq);
2464
2465out_unlock:
2466 rq->push_busy = false;
5cb9eaa3 2467 raw_spin_rq_unlock(rq);
a7c81556
PZ
2468 raw_spin_unlock_irq(&p->pi_lock);
2469
2470 put_task_struct(p);
5cc389bc
PZ
2471 return 0;
2472}
2473
c5b28038
PZ
2474/*
2475 * sched_class::set_cpus_allowed must do the below, but is not required to
2476 * actually call this function.
2477 */
9cfc3e18 2478void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
5cc389bc 2479{
af449901
PZ
2480 if (flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
2481 p->cpus_ptr = new_mask;
2482 return;
2483 }
2484
3bd37062 2485 cpumask_copy(&p->cpus_mask, new_mask);
5cc389bc
PZ
2486 p->nr_cpus_allowed = cpumask_weight(new_mask);
2487}
2488
9cfc3e18
PZ
2489static void
2490__do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
c5b28038 2491{
6c37067e
PZ
2492 struct rq *rq = task_rq(p);
2493 bool queued, running;
2494
af449901
PZ
2495 /*
2496 * This here violates the locking rules for affinity, since we're only
2497 * supposed to change these variables while holding both rq->lock and
2498 * p->pi_lock.
2499 *
2500 * HOWEVER, it magically works, because ttwu() is the only code that
2501 * accesses these variables under p->pi_lock and only does so after
2502 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2503 * before finish_task().
2504 *
2505 * XXX do further audits, this smells like something putrid.
2506 */
2507 if (flags & SCA_MIGRATE_DISABLE)
2508 SCHED_WARN_ON(!p->on_cpu);
2509 else
2510 lockdep_assert_held(&p->pi_lock);
6c37067e
PZ
2511
2512 queued = task_on_rq_queued(p);
2513 running = task_current(rq, p);
2514
2515 if (queued) {
2516 /*
2517 * Because __kthread_bind() calls this on blocked tasks without
2518 * holding rq->lock.
2519 */
5cb9eaa3 2520 lockdep_assert_rq_held(rq);
7a57f32a 2521 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
6c37067e
PZ
2522 }
2523 if (running)
2524 put_prev_task(rq, p);
2525
9cfc3e18 2526 p->sched_class->set_cpus_allowed(p, new_mask, flags);
6c37067e 2527
6c37067e 2528 if (queued)
7134b3e9 2529 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 2530 if (running)
03b7fad1 2531 set_next_task(rq, p);
c5b28038
PZ
2532}
2533
9cfc3e18
PZ
2534void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
2535{
2536 __do_set_cpus_allowed(p, new_mask, 0);
2537}
2538
b90ca8ba
WD
2539int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
2540 int node)
2541{
2542 if (!src->user_cpus_ptr)
2543 return 0;
2544
2545 dst->user_cpus_ptr = kmalloc_node(cpumask_size(), GFP_KERNEL, node);
2546 if (!dst->user_cpus_ptr)
2547 return -ENOMEM;
2548
2549 cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
2550 return 0;
2551}
2552
07ec77a1
WD
2553static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
2554{
2555 struct cpumask *user_mask = NULL;
2556
2557 swap(p->user_cpus_ptr, user_mask);
2558
2559 return user_mask;
2560}
2561
b90ca8ba
WD
2562void release_user_cpus_ptr(struct task_struct *p)
2563{
07ec77a1 2564 kfree(clear_user_cpus_ptr(p));
b90ca8ba
WD
2565}
2566
6d337eab 2567/*
c777d847
VS
2568 * This function is wildly self concurrent; here be dragons.
2569 *
2570 *
2571 * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2572 * designated task is enqueued on an allowed CPU. If that task is currently
2573 * running, we have to kick it out using the CPU stopper.
2574 *
2575 * Migrate-Disable comes along and tramples all over our nice sandcastle.
2576 * Consider:
2577 *
2578 * Initial conditions: P0->cpus_mask = [0, 1]
2579 *
2580 * P0@CPU0 P1
2581 *
2582 * migrate_disable();
2583 * <preempted>
2584 * set_cpus_allowed_ptr(P0, [1]);
2585 *
2586 * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2587 * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2588 * This means we need the following scheme:
2589 *
2590 * P0@CPU0 P1
2591 *
2592 * migrate_disable();
2593 * <preempted>
2594 * set_cpus_allowed_ptr(P0, [1]);
2595 * <blocks>
2596 * <resumes>
2597 * migrate_enable();
2598 * __set_cpus_allowed_ptr();
2599 * <wakes local stopper>
2600 * `--> <woken on migration completion>
2601 *
2602 * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2603 * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
2604 * task p are serialized by p->pi_lock, which we can leverage: the one that
2605 * should come into effect at the end of the Migrate-Disable region is the last
2606 * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
2607 * but we still need to properly signal those waiting tasks at the appropriate
2608 * moment.
2609 *
2610 * This is implemented using struct set_affinity_pending. The first
2611 * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
2612 * setup an instance of that struct and install it on the targeted task_struct.
2613 * Any and all further callers will reuse that instance. Those then wait for
2614 * a completion signaled at the tail of the CPU stopper callback (1), triggered
2615 * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
2616 *
2617 *
2618 * (1) In the cases covered above. There is one more where the completion is
2619 * signaled within affine_move_task() itself: when a subsequent affinity request
e140749c
VS
2620 * occurs after the stopper bailed out due to the targeted task still being
2621 * Migrate-Disable. Consider:
c777d847
VS
2622 *
2623 * Initial conditions: P0->cpus_mask = [0, 1]
2624 *
e140749c
VS
2625 * CPU0 P1 P2
2626 * <P0>
2627 * migrate_disable();
2628 * <preempted>
c777d847
VS
2629 * set_cpus_allowed_ptr(P0, [1]);
2630 * <blocks>
e140749c
VS
2631 * <migration/0>
2632 * migration_cpu_stop()
2633 * is_migration_disabled()
2634 * <bails>
c777d847
VS
2635 * set_cpus_allowed_ptr(P0, [0, 1]);
2636 * <signal completion>
2637 * <awakes>
2638 *
2639 * Note that the above is safe vs a concurrent migrate_enable(), as any
2640 * pending affinity completion is preceded by an uninstallation of
2641 * p->migration_pending done with p->pi_lock held.
6d337eab
PZ
2642 */
2643static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
2644 int dest_cpu, unsigned int flags)
2645{
2646 struct set_affinity_pending my_pending = { }, *pending = NULL;
9e81889c 2647 bool stop_pending, complete = false;
6d337eab
PZ
2648
2649 /* Can the task run on the task's current CPU? If so, we're done */
2650 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
a7c81556
PZ
2651 struct task_struct *push_task = NULL;
2652
2653 if ((flags & SCA_MIGRATE_ENABLE) &&
2654 (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
2655 rq->push_busy = true;
2656 push_task = get_task_struct(p);
2657 }
2658
50caf9c1
PZ
2659 /*
2660 * If there are pending waiters, but no pending stop_work,
2661 * then complete now.
2662 */
6d337eab 2663 pending = p->migration_pending;
50caf9c1 2664 if (pending && !pending->stop_pending) {
6d337eab
PZ
2665 p->migration_pending = NULL;
2666 complete = true;
2667 }
50caf9c1 2668
6d337eab
PZ
2669 task_rq_unlock(rq, p, rf);
2670
a7c81556
PZ
2671 if (push_task) {
2672 stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
2673 p, &rq->push_work);
2674 }
2675
6d337eab 2676 if (complete)
50caf9c1 2677 complete_all(&pending->done);
6d337eab
PZ
2678
2679 return 0;
2680 }
2681
2682 if (!(flags & SCA_MIGRATE_ENABLE)) {
2683 /* serialized by p->pi_lock */
2684 if (!p->migration_pending) {
c777d847 2685 /* Install the request */
6d337eab
PZ
2686 refcount_set(&my_pending.refs, 1);
2687 init_completion(&my_pending.done);
8a6edb52
PZ
2688 my_pending.arg = (struct migration_arg) {
2689 .task = p,
475ea6c6 2690 .dest_cpu = dest_cpu,
8a6edb52
PZ
2691 .pending = &my_pending,
2692 };
2693
6d337eab
PZ
2694 p->migration_pending = &my_pending;
2695 } else {
2696 pending = p->migration_pending;
2697 refcount_inc(&pending->refs);
475ea6c6
VS
2698 /*
2699 * Affinity has changed, but we've already installed a
2700 * pending. migration_cpu_stop() *must* see this, else
2701 * we risk a completion of the pending despite having a
2702 * task on a disallowed CPU.
2703 *
2704 * Serialized by p->pi_lock, so this is safe.
2705 */
2706 pending->arg.dest_cpu = dest_cpu;
6d337eab
PZ
2707 }
2708 }
2709 pending = p->migration_pending;
2710 /*
2711 * - !MIGRATE_ENABLE:
2712 * we'll have installed a pending if there wasn't one already.
2713 *
2714 * - MIGRATE_ENABLE:
2715 * we're here because the current CPU isn't matching anymore,
2716 * the only way that can happen is because of a concurrent
2717 * set_cpus_allowed_ptr() call, which should then still be
2718 * pending completion.
2719 *
2720 * Either way, we really should have a @pending here.
2721 */
2722 if (WARN_ON_ONCE(!pending)) {
2723 task_rq_unlock(rq, p, rf);
2724 return -EINVAL;
2725 }
2726
2f064a59 2727 if (task_running(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
c777d847 2728 /*
58b1a450
PZ
2729 * MIGRATE_ENABLE gets here because 'p == current', but for
2730 * anything else we cannot do is_migration_disabled(), punt
2731 * and have the stopper function handle it all race-free.
c777d847 2732 */
9e81889c
PZ
2733 stop_pending = pending->stop_pending;
2734 if (!stop_pending)
2735 pending->stop_pending = true;
58b1a450 2736
58b1a450
PZ
2737 if (flags & SCA_MIGRATE_ENABLE)
2738 p->migration_flags &= ~MDF_PUSH;
50caf9c1 2739
6d337eab 2740 task_rq_unlock(rq, p, rf);
8a6edb52 2741
9e81889c
PZ
2742 if (!stop_pending) {
2743 stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
2744 &pending->arg, &pending->stop_work);
2745 }
6d337eab 2746
58b1a450
PZ
2747 if (flags & SCA_MIGRATE_ENABLE)
2748 return 0;
6d337eab
PZ
2749 } else {
2750
2751 if (!is_migration_disabled(p)) {
2752 if (task_on_rq_queued(p))
2753 rq = move_queued_task(rq, rf, p, dest_cpu);
2754
50caf9c1
PZ
2755 if (!pending->stop_pending) {
2756 p->migration_pending = NULL;
2757 complete = true;
2758 }
6d337eab
PZ
2759 }
2760 task_rq_unlock(rq, p, rf);
2761
6d337eab
PZ
2762 if (complete)
2763 complete_all(&pending->done);
2764 }
2765
2766 wait_for_completion(&pending->done);
2767
2768 if (refcount_dec_and_test(&pending->refs))
50caf9c1 2769 wake_up_var(&pending->refs); /* No UaF, just an address */
6d337eab 2770
c777d847
VS
2771 /*
2772 * Block the original owner of &pending until all subsequent callers
2773 * have seen the completion and decremented the refcount
2774 */
6d337eab
PZ
2775 wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
2776
50caf9c1
PZ
2777 /* ARGH */
2778 WARN_ON_ONCE(my_pending.stop_pending);
2779
6d337eab
PZ
2780 return 0;
2781}
2782
5cc389bc 2783/*
07ec77a1 2784 * Called with both p->pi_lock and rq->lock held; drops both before returning.
5cc389bc 2785 */
07ec77a1
WD
2786static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
2787 const struct cpumask *new_mask,
2788 u32 flags,
2789 struct rq *rq,
2790 struct rq_flags *rf)
2791 __releases(rq->lock)
2792 __releases(p->pi_lock)
5cc389bc 2793{
234a503e 2794 const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
e9d867a6 2795 const struct cpumask *cpu_valid_mask = cpu_active_mask;
234a503e 2796 bool kthread = p->flags & PF_KTHREAD;
07ec77a1 2797 struct cpumask *user_mask = NULL;
5cc389bc
PZ
2798 unsigned int dest_cpu;
2799 int ret = 0;
2800
a499c3ea 2801 update_rq_clock(rq);
5cc389bc 2802
234a503e 2803 if (kthread || is_migration_disabled(p)) {
e9d867a6 2804 /*
741ba80f
PZ
2805 * Kernel threads are allowed on online && !active CPUs,
2806 * however, during cpu-hot-unplug, even these might get pushed
2807 * away if not KTHREAD_IS_PER_CPU.
af449901
PZ
2808 *
2809 * Specifically, migration_disabled() tasks must not fail the
2810 * cpumask_any_and_distribute() pick below, esp. so on
2811 * SCA_MIGRATE_ENABLE, otherwise we'll not call
2812 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
e9d867a6
PZI
2813 */
2814 cpu_valid_mask = cpu_online_mask;
2815 }
2816
234a503e
WD
2817 if (!kthread && !cpumask_subset(new_mask, cpu_allowed_mask)) {
2818 ret = -EINVAL;
2819 goto out;
2820 }
2821
25834c73
PZ
2822 /*
2823 * Must re-check here, to close a race against __kthread_bind(),
2824 * sched_setaffinity() is not guaranteed to observe the flag.
2825 */
9cfc3e18 2826 if ((flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
25834c73
PZ
2827 ret = -EINVAL;
2828 goto out;
2829 }
2830
885b3ba4
VS
2831 if (!(flags & SCA_MIGRATE_ENABLE)) {
2832 if (cpumask_equal(&p->cpus_mask, new_mask))
2833 goto out;
2834
2835 if (WARN_ON_ONCE(p == current &&
2836 is_migration_disabled(p) &&
2837 !cpumask_test_cpu(task_cpu(p), new_mask))) {
2838 ret = -EBUSY;
2839 goto out;
2840 }
2841 }
5cc389bc 2842
46a87b38
PT
2843 /*
2844 * Picking a ~random cpu helps in cases where we are changing affinity
2845 * for groups of tasks (ie. cpuset), so that load balancing is not
2846 * immediately required to distribute the tasks within their new mask.
2847 */
2848 dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, new_mask);
714e501e 2849 if (dest_cpu >= nr_cpu_ids) {
5cc389bc
PZ
2850 ret = -EINVAL;
2851 goto out;
2852 }
2853
9cfc3e18 2854 __do_set_cpus_allowed(p, new_mask, flags);
5cc389bc 2855
07ec77a1
WD
2856 if (flags & SCA_USER)
2857 user_mask = clear_user_cpus_ptr(p);
2858
2859 ret = affine_move_task(rq, p, rf, dest_cpu, flags);
2860
2861 kfree(user_mask);
2862
2863 return ret;
5cc389bc 2864
5cc389bc 2865out:
07ec77a1 2866 task_rq_unlock(rq, p, rf);
5cc389bc
PZ
2867
2868 return ret;
2869}
25834c73 2870
07ec77a1
WD
2871/*
2872 * Change a given task's CPU affinity. Migrate the thread to a
2873 * proper CPU and schedule it away if the CPU it's executing on
2874 * is removed from the allowed bitmask.
2875 *
2876 * NOTE: the caller must have a valid reference to the task, the
2877 * task must not exit() & deallocate itself prematurely. The
2878 * call is not atomic; no spinlocks may be held.
2879 */
2880static int __set_cpus_allowed_ptr(struct task_struct *p,
2881 const struct cpumask *new_mask, u32 flags)
2882{
2883 struct rq_flags rf;
2884 struct rq *rq;
2885
2886 rq = task_rq_lock(p, &rf);
2887 return __set_cpus_allowed_ptr_locked(p, new_mask, flags, rq, &rf);
2888}
2889
25834c73
PZ
2890int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
2891{
9cfc3e18 2892 return __set_cpus_allowed_ptr(p, new_mask, 0);
25834c73 2893}
5cc389bc
PZ
2894EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
2895
07ec77a1
WD
2896/*
2897 * Change a given task's CPU affinity to the intersection of its current
2898 * affinity mask and @subset_mask, writing the resulting mask to @new_mask
2899 * and pointing @p->user_cpus_ptr to a copy of the old mask.
2900 * If the resulting mask is empty, leave the affinity unchanged and return
2901 * -EINVAL.
2902 */
2903static int restrict_cpus_allowed_ptr(struct task_struct *p,
2904 struct cpumask *new_mask,
2905 const struct cpumask *subset_mask)
2906{
2907 struct cpumask *user_mask = NULL;
2908 struct rq_flags rf;
2909 struct rq *rq;
2910 int err;
2911
2912 if (!p->user_cpus_ptr) {
2913 user_mask = kmalloc(cpumask_size(), GFP_KERNEL);
2914 if (!user_mask)
2915 return -ENOMEM;
2916 }
2917
2918 rq = task_rq_lock(p, &rf);
2919
2920 /*
2921 * Forcefully restricting the affinity of a deadline task is
2922 * likely to cause problems, so fail and noisily override the
2923 * mask entirely.
2924 */
2925 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
2926 err = -EPERM;
2927 goto err_unlock;
2928 }
2929
2930 if (!cpumask_and(new_mask, &p->cpus_mask, subset_mask)) {
2931 err = -EINVAL;
2932 goto err_unlock;
2933 }
2934
2935 /*
2936 * We're about to butcher the task affinity, so keep track of what
2937 * the user asked for in case we're able to restore it later on.
2938 */
2939 if (user_mask) {
2940 cpumask_copy(user_mask, p->cpus_ptr);
2941 p->user_cpus_ptr = user_mask;
2942 }
2943
2944 return __set_cpus_allowed_ptr_locked(p, new_mask, 0, rq, &rf);
2945
2946err_unlock:
2947 task_rq_unlock(rq, p, &rf);
2948 kfree(user_mask);
2949 return err;
2950}
2951
2952/*
2953 * Restrict the CPU affinity of task @p so that it is a subset of
2954 * task_cpu_possible_mask() and point @p->user_cpu_ptr to a copy of the
2955 * old affinity mask. If the resulting mask is empty, we warn and walk
2956 * up the cpuset hierarchy until we find a suitable mask.
2957 */
2958void force_compatible_cpus_allowed_ptr(struct task_struct *p)
2959{
2960 cpumask_var_t new_mask;
2961 const struct cpumask *override_mask = task_cpu_possible_mask(p);
2962
2963 alloc_cpumask_var(&new_mask, GFP_KERNEL);
2964
2965 /*
2966 * __migrate_task() can fail silently in the face of concurrent
2967 * offlining of the chosen destination CPU, so take the hotplug
2968 * lock to ensure that the migration succeeds.
2969 */
2970 cpus_read_lock();
2971 if (!cpumask_available(new_mask))
2972 goto out_set_mask;
2973
2974 if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
2975 goto out_free_mask;
2976
2977 /*
2978 * We failed to find a valid subset of the affinity mask for the
2979 * task, so override it based on its cpuset hierarchy.
2980 */
2981 cpuset_cpus_allowed(p, new_mask);
2982 override_mask = new_mask;
2983
2984out_set_mask:
2985 if (printk_ratelimit()) {
2986 printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
2987 task_pid_nr(p), p->comm,
2988 cpumask_pr_args(override_mask));
2989 }
2990
2991 WARN_ON(set_cpus_allowed_ptr(p, override_mask));
2992out_free_mask:
2993 cpus_read_unlock();
2994 free_cpumask_var(new_mask);
2995}
2996
2997static int
2998__sched_setaffinity(struct task_struct *p, const struct cpumask *mask);
2999
3000/*
3001 * Restore the affinity of a task @p which was previously restricted by a
3002 * call to force_compatible_cpus_allowed_ptr(). This will clear (and free)
3003 * @p->user_cpus_ptr.
3004 *
3005 * It is the caller's responsibility to serialise this with any calls to
3006 * force_compatible_cpus_allowed_ptr(@p).
3007 */
3008void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
3009{
3010 struct cpumask *user_mask = p->user_cpus_ptr;
3011 unsigned long flags;
3012
3013 /*
3014 * Try to restore the old affinity mask. If this fails, then
3015 * we free the mask explicitly to avoid it being inherited across
3016 * a subsequent fork().
3017 */
3018 if (!user_mask || !__sched_setaffinity(p, user_mask))
3019 return;
3020
3021 raw_spin_lock_irqsave(&p->pi_lock, flags);
3022 user_mask = clear_user_cpus_ptr(p);
3023 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3024
3025 kfree(user_mask);
3026}
3027
dd41f596 3028void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 3029{
e2912009 3030#ifdef CONFIG_SCHED_DEBUG
2f064a59
PZ
3031 unsigned int state = READ_ONCE(p->__state);
3032
e2912009
PZ
3033 /*
3034 * We should never call set_task_cpu() on a blocked task,
3035 * ttwu() will sort out the placement.
3036 */
2f064a59 3037 WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
0122ec5b 3038
3ea94de1
JP
3039 /*
3040 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
3041 * because schedstat_wait_{start,end} rebase migrating task's wait_start
3042 * time relying on p->on_rq.
3043 */
2f064a59 3044 WARN_ON_ONCE(state == TASK_RUNNING &&
3ea94de1
JP
3045 p->sched_class == &fair_sched_class &&
3046 (p->on_rq && !task_on_rq_migrating(p)));
3047
0122ec5b 3048#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
3049 /*
3050 * The caller should hold either p->pi_lock or rq->lock, when changing
3051 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
3052 *
3053 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 3054 * see task_group().
6c6c54e1
PZ
3055 *
3056 * Furthermore, all task_rq users should acquire both locks, see
3057 * task_rq_lock().
3058 */
0122ec5b 3059 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
9ef7e7e3 3060 lockdep_is_held(__rq_lockp(task_rq(p)))));
0122ec5b 3061#endif
4ff9083b
PZ
3062 /*
3063 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
3064 */
3065 WARN_ON_ONCE(!cpu_online(new_cpu));
af449901
PZ
3066
3067 WARN_ON_ONCE(is_migration_disabled(p));
e2912009
PZ
3068#endif
3069
de1d7286 3070 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 3071
0c69774e 3072 if (task_cpu(p) != new_cpu) {
0a74bef8 3073 if (p->sched_class->migrate_task_rq)
1327237a 3074 p->sched_class->migrate_task_rq(p, new_cpu);
0c69774e 3075 p->se.nr_migrations++;
d7822b1e 3076 rseq_migrate(p);
ff303e66 3077 perf_event_task_migrate(p);
0c69774e 3078 }
dd41f596
IM
3079
3080 __set_task_cpu(p, new_cpu);
c65cc870
IM
3081}
3082
0ad4e3df 3083#ifdef CONFIG_NUMA_BALANCING
ac66f547
PZ
3084static void __migrate_swap_task(struct task_struct *p, int cpu)
3085{
da0c1e65 3086 if (task_on_rq_queued(p)) {
ac66f547 3087 struct rq *src_rq, *dst_rq;
8a8c69c3 3088 struct rq_flags srf, drf;
ac66f547
PZ
3089
3090 src_rq = task_rq(p);
3091 dst_rq = cpu_rq(cpu);
3092
8a8c69c3
PZ
3093 rq_pin_lock(src_rq, &srf);
3094 rq_pin_lock(dst_rq, &drf);
3095
ac66f547
PZ
3096 deactivate_task(src_rq, p, 0);
3097 set_task_cpu(p, cpu);
3098 activate_task(dst_rq, p, 0);
3099 check_preempt_curr(dst_rq, p, 0);
8a8c69c3
PZ
3100
3101 rq_unpin_lock(dst_rq, &drf);
3102 rq_unpin_lock(src_rq, &srf);
3103
ac66f547
PZ
3104 } else {
3105 /*
3106 * Task isn't running anymore; make it appear like we migrated
3107 * it before it went to sleep. This means on wakeup we make the
d1ccc66d 3108 * previous CPU our target instead of where it really is.
ac66f547
PZ
3109 */
3110 p->wake_cpu = cpu;
3111 }
3112}
3113
3114struct migration_swap_arg {
3115 struct task_struct *src_task, *dst_task;
3116 int src_cpu, dst_cpu;
3117};
3118
3119static int migrate_swap_stop(void *data)
3120{
3121 struct migration_swap_arg *arg = data;
3122 struct rq *src_rq, *dst_rq;
3123 int ret = -EAGAIN;
3124
62694cd5
PZ
3125 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
3126 return -EAGAIN;
3127
ac66f547
PZ
3128 src_rq = cpu_rq(arg->src_cpu);
3129 dst_rq = cpu_rq(arg->dst_cpu);
3130
74602315
PZ
3131 double_raw_lock(&arg->src_task->pi_lock,
3132 &arg->dst_task->pi_lock);
ac66f547 3133 double_rq_lock(src_rq, dst_rq);
62694cd5 3134
ac66f547
PZ
3135 if (task_cpu(arg->dst_task) != arg->dst_cpu)
3136 goto unlock;
3137
3138 if (task_cpu(arg->src_task) != arg->src_cpu)
3139 goto unlock;
3140
3bd37062 3141 if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
ac66f547
PZ
3142 goto unlock;
3143
3bd37062 3144 if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
ac66f547
PZ
3145 goto unlock;
3146
3147 __migrate_swap_task(arg->src_task, arg->dst_cpu);
3148 __migrate_swap_task(arg->dst_task, arg->src_cpu);
3149
3150 ret = 0;
3151
3152unlock:
3153 double_rq_unlock(src_rq, dst_rq);
74602315
PZ
3154 raw_spin_unlock(&arg->dst_task->pi_lock);
3155 raw_spin_unlock(&arg->src_task->pi_lock);
ac66f547
PZ
3156
3157 return ret;
3158}
3159
3160/*
3161 * Cross migrate two tasks
3162 */
0ad4e3df
SD
3163int migrate_swap(struct task_struct *cur, struct task_struct *p,
3164 int target_cpu, int curr_cpu)
ac66f547
PZ
3165{
3166 struct migration_swap_arg arg;
3167 int ret = -EINVAL;
3168
ac66f547
PZ
3169 arg = (struct migration_swap_arg){
3170 .src_task = cur,
0ad4e3df 3171 .src_cpu = curr_cpu,
ac66f547 3172 .dst_task = p,
0ad4e3df 3173 .dst_cpu = target_cpu,
ac66f547
PZ
3174 };
3175
3176 if (arg.src_cpu == arg.dst_cpu)
3177 goto out;
3178
6acce3ef
PZ
3179 /*
3180 * These three tests are all lockless; this is OK since all of them
3181 * will be re-checked with proper locks held further down the line.
3182 */
ac66f547
PZ
3183 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
3184 goto out;
3185
3bd37062 3186 if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
ac66f547
PZ
3187 goto out;
3188
3bd37062 3189 if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
ac66f547
PZ
3190 goto out;
3191
286549dc 3192 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ac66f547
PZ
3193 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
3194
3195out:
ac66f547
PZ
3196 return ret;
3197}
0ad4e3df 3198#endif /* CONFIG_NUMA_BALANCING */
ac66f547 3199
1da177e4
LT
3200/*
3201 * wait_task_inactive - wait for a thread to unschedule.
3202 *
85ba2d86
RM
3203 * If @match_state is nonzero, it's the @p->state value just checked and
3204 * not expected to change. If it changes, i.e. @p might have woken up,
3205 * then return zero. When we succeed in waiting for @p to be off its CPU,
3206 * we return a positive number (its total switch count). If a second call
3207 * a short while later returns the same number, the caller can be sure that
3208 * @p has remained unscheduled the whole time.
3209 *
1da177e4
LT
3210 * The caller must ensure that the task *will* unschedule sometime soon,
3211 * else this function might spin for a *long* time. This function can't
3212 * be called with interrupts off, or it may introduce deadlock with
3213 * smp_call_function() if an IPI is sent by the same process we are
3214 * waiting to become inactive.
3215 */
2f064a59 3216unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
1da177e4 3217{
da0c1e65 3218 int running, queued;
eb580751 3219 struct rq_flags rf;
85ba2d86 3220 unsigned long ncsw;
70b97a7f 3221 struct rq *rq;
1da177e4 3222
3a5c359a
AK
3223 for (;;) {
3224 /*
3225 * We do the initial early heuristics without holding
3226 * any task-queue locks at all. We'll only try to get
3227 * the runqueue lock when things look like they will
3228 * work out!
3229 */
3230 rq = task_rq(p);
fa490cfd 3231
3a5c359a
AK
3232 /*
3233 * If the task is actively running on another CPU
3234 * still, just relax and busy-wait without holding
3235 * any locks.
3236 *
3237 * NOTE! Since we don't hold any locks, it's not
3238 * even sure that "rq" stays as the right runqueue!
3239 * But we don't care, since "task_running()" will
3240 * return false if the runqueue has changed and p
3241 * is actually now running somewhere else!
3242 */
85ba2d86 3243 while (task_running(rq, p)) {
2f064a59 3244 if (match_state && unlikely(READ_ONCE(p->__state) != match_state))
85ba2d86 3245 return 0;
3a5c359a 3246 cpu_relax();
85ba2d86 3247 }
fa490cfd 3248
3a5c359a
AK
3249 /*
3250 * Ok, time to look more closely! We need the rq
3251 * lock now, to be *sure*. If we're wrong, we'll
3252 * just go back and repeat.
3253 */
eb580751 3254 rq = task_rq_lock(p, &rf);
27a9da65 3255 trace_sched_wait_task(p);
3a5c359a 3256 running = task_running(rq, p);
da0c1e65 3257 queued = task_on_rq_queued(p);
85ba2d86 3258 ncsw = 0;
2f064a59 3259 if (!match_state || READ_ONCE(p->__state) == match_state)
93dcf55f 3260 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
eb580751 3261 task_rq_unlock(rq, p, &rf);
fa490cfd 3262
85ba2d86
RM
3263 /*
3264 * If it changed from the expected state, bail out now.
3265 */
3266 if (unlikely(!ncsw))
3267 break;
3268
3a5c359a
AK
3269 /*
3270 * Was it really running after all now that we
3271 * checked with the proper locks actually held?
3272 *
3273 * Oops. Go back and try again..
3274 */
3275 if (unlikely(running)) {
3276 cpu_relax();
3277 continue;
3278 }
fa490cfd 3279
3a5c359a
AK
3280 /*
3281 * It's not enough that it's not actively running,
3282 * it must be off the runqueue _entirely_, and not
3283 * preempted!
3284 *
80dd99b3 3285 * So if it was still runnable (but just not actively
3a5c359a
AK
3286 * running right now), it's preempted, and we should
3287 * yield - it could be a while.
3288 */
da0c1e65 3289 if (unlikely(queued)) {
8b0e1953 3290 ktime_t to = NSEC_PER_SEC / HZ;
8eb90c30
TG
3291
3292 set_current_state(TASK_UNINTERRUPTIBLE);
c33627e9 3293 schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
3a5c359a
AK
3294 continue;
3295 }
fa490cfd 3296
3a5c359a
AK
3297 /*
3298 * Ahh, all good. It wasn't running, and it wasn't
3299 * runnable, which means that it will never become
3300 * running in the future either. We're all done!
3301 */
3302 break;
3303 }
85ba2d86
RM
3304
3305 return ncsw;
1da177e4
LT
3306}
3307
3308/***
3309 * kick_process - kick a running thread to enter/exit the kernel
3310 * @p: the to-be-kicked thread
3311 *
3312 * Cause a process which is running on another CPU to enter
3313 * kernel-mode, without any delay. (to get signals handled.)
3314 *
25985edc 3315 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
3316 * because all it wants to ensure is that the remote task enters
3317 * the kernel. If the IPI races and the task has been migrated
3318 * to another CPU then no harm is done and the purpose has been
3319 * achieved as well.
3320 */
36c8b586 3321void kick_process(struct task_struct *p)
1da177e4
LT
3322{
3323 int cpu;
3324
3325 preempt_disable();
3326 cpu = task_cpu(p);
3327 if ((cpu != smp_processor_id()) && task_curr(p))
3328 smp_send_reschedule(cpu);
3329 preempt_enable();
3330}
b43e3521 3331EXPORT_SYMBOL_GPL(kick_process);
1da177e4 3332
30da688e 3333/*
3bd37062 3334 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
e9d867a6
PZI
3335 *
3336 * A few notes on cpu_active vs cpu_online:
3337 *
3338 * - cpu_active must be a subset of cpu_online
3339 *
97fb7a0a 3340 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
e9d867a6 3341 * see __set_cpus_allowed_ptr(). At this point the newly online
d1ccc66d 3342 * CPU isn't yet part of the sched domains, and balancing will not
e9d867a6
PZI
3343 * see it.
3344 *
d1ccc66d 3345 * - on CPU-down we clear cpu_active() to mask the sched domains and
e9d867a6 3346 * avoid the load balancer to place new tasks on the to be removed
d1ccc66d 3347 * CPU. Existing tasks will remain running there and will be taken
e9d867a6
PZI
3348 * off.
3349 *
3350 * This means that fallback selection must not select !active CPUs.
3351 * And can assume that any active CPU must be online. Conversely
3352 * select_task_rq() below may allow selection of !active CPUs in order
3353 * to satisfy the above rules.
30da688e 3354 */
5da9a0fb
PZ
3355static int select_fallback_rq(int cpu, struct task_struct *p)
3356{
aa00d89c
TC
3357 int nid = cpu_to_node(cpu);
3358 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
3359 enum { cpuset, possible, fail } state = cpuset;
3360 int dest_cpu;
5da9a0fb 3361
aa00d89c 3362 /*
d1ccc66d
IM
3363 * If the node that the CPU is on has been offlined, cpu_to_node()
3364 * will return -1. There is no CPU on the node, and we should
3365 * select the CPU on the other node.
aa00d89c
TC
3366 */
3367 if (nid != -1) {
3368 nodemask = cpumask_of_node(nid);
3369
3370 /* Look for allowed, online CPU in same node. */
3371 for_each_cpu(dest_cpu, nodemask) {
9ae606bc 3372 if (is_cpu_allowed(p, dest_cpu))
aa00d89c
TC
3373 return dest_cpu;
3374 }
2baab4e9 3375 }
5da9a0fb 3376
2baab4e9
PZ
3377 for (;;) {
3378 /* Any allowed, online CPU? */
3bd37062 3379 for_each_cpu(dest_cpu, p->cpus_ptr) {
175f0e25 3380 if (!is_cpu_allowed(p, dest_cpu))
2baab4e9 3381 continue;
175f0e25 3382
2baab4e9
PZ
3383 goto out;
3384 }
5da9a0fb 3385
e73e85f0 3386 /* No more Mr. Nice Guy. */
2baab4e9
PZ
3387 switch (state) {
3388 case cpuset:
97c0054d 3389 if (cpuset_cpus_allowed_fallback(p)) {
e73e85f0
ON
3390 state = possible;
3391 break;
3392 }
df561f66 3393 fallthrough;
2baab4e9 3394 case possible:
af449901
PZ
3395 /*
3396 * XXX When called from select_task_rq() we only
3397 * hold p->pi_lock and again violate locking order.
3398 *
3399 * More yuck to audit.
3400 */
9ae606bc 3401 do_set_cpus_allowed(p, task_cpu_possible_mask(p));
2baab4e9
PZ
3402 state = fail;
3403 break;
2baab4e9
PZ
3404 case fail:
3405 BUG();
3406 break;
3407 }
3408 }
3409
3410out:
3411 if (state != cpuset) {
3412 /*
3413 * Don't tell them about moving exiting tasks or
3414 * kernel threads (both mm NULL), since they never
3415 * leave kernel.
3416 */
3417 if (p->mm && printk_ratelimit()) {
aac74dc4 3418 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2baab4e9
PZ
3419 task_pid_nr(p), p->comm, cpu);
3420 }
5da9a0fb
PZ
3421 }
3422
3423 return dest_cpu;
3424}
3425
e2912009 3426/*
3bd37062 3427 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
e2912009 3428 */
970b13ba 3429static inline
3aef1551 3430int select_task_rq(struct task_struct *p, int cpu, int wake_flags)
970b13ba 3431{
cbce1a68
PZ
3432 lockdep_assert_held(&p->pi_lock);
3433
af449901 3434 if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p))
3aef1551 3435 cpu = p->sched_class->select_task_rq(p, cpu, wake_flags);
e9d867a6 3436 else
3bd37062 3437 cpu = cpumask_any(p->cpus_ptr);
e2912009
PZ
3438
3439 /*
3440 * In order not to call set_task_cpu() on a blocking task we need
3bd37062 3441 * to rely on ttwu() to place the task on a valid ->cpus_ptr
d1ccc66d 3442 * CPU.
e2912009
PZ
3443 *
3444 * Since this is common to all placement strategies, this lives here.
3445 *
3446 * [ this allows ->select_task() to simply return task_cpu(p) and
3447 * not worry about this generic constraint ]
3448 */
7af443ee 3449 if (unlikely(!is_cpu_allowed(p, cpu)))
5da9a0fb 3450 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
3451
3452 return cpu;
970b13ba 3453}
09a40af5 3454
f5832c19
NP
3455void sched_set_stop_task(int cpu, struct task_struct *stop)
3456{
ded467dc 3457 static struct lock_class_key stop_pi_lock;
f5832c19
NP
3458 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
3459 struct task_struct *old_stop = cpu_rq(cpu)->stop;
3460
3461 if (stop) {
3462 /*
3463 * Make it appear like a SCHED_FIFO task, its something
3464 * userspace knows about and won't get confused about.
3465 *
3466 * Also, it will make PI more or less work without too
3467 * much confusion -- but then, stop work should not
3468 * rely on PI working anyway.
3469 */
3470 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
3471
3472 stop->sched_class = &stop_sched_class;
ded467dc
PZ
3473
3474 /*
3475 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3476 * adjust the effective priority of a task. As a result,
3477 * rt_mutex_setprio() can trigger (RT) balancing operations,
3478 * which can then trigger wakeups of the stop thread to push
3479 * around the current task.
3480 *
3481 * The stop task itself will never be part of the PI-chain, it
3482 * never blocks, therefore that ->pi_lock recursion is safe.
3483 * Tell lockdep about this by placing the stop->pi_lock in its
3484 * own class.
3485 */
3486 lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
f5832c19
NP
3487 }
3488
3489 cpu_rq(cpu)->stop = stop;
3490
3491 if (old_stop) {
3492 /*
3493 * Reset it back to a normal scheduling class so that
3494 * it can die in pieces.
3495 */
3496 old_stop->sched_class = &rt_sched_class;
3497 }
3498}
3499
74d862b6 3500#else /* CONFIG_SMP */
25834c73
PZ
3501
3502static inline int __set_cpus_allowed_ptr(struct task_struct *p,
9cfc3e18
PZ
3503 const struct cpumask *new_mask,
3504 u32 flags)
25834c73
PZ
3505{
3506 return set_cpus_allowed_ptr(p, new_mask);
3507}
3508
af449901
PZ
3509static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
3510
3015ef4b
TG
3511static inline bool rq_has_pinned_tasks(struct rq *rq)
3512{
3513 return false;
3514}
3515
74d862b6 3516#endif /* !CONFIG_SMP */
970b13ba 3517
d7c01d27 3518static void
b84cb5df 3519ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 3520{
4fa8d299 3521 struct rq *rq;
b84cb5df 3522
4fa8d299
JP
3523 if (!schedstat_enabled())
3524 return;
3525
3526 rq = this_rq();
d7c01d27 3527
4fa8d299
JP
3528#ifdef CONFIG_SMP
3529 if (cpu == rq->cpu) {
b85c8b71 3530 __schedstat_inc(rq->ttwu_local);
ceeadb83 3531 __schedstat_inc(p->stats.nr_wakeups_local);
d7c01d27
PZ
3532 } else {
3533 struct sched_domain *sd;
3534
ceeadb83 3535 __schedstat_inc(p->stats.nr_wakeups_remote);
057f3fad 3536 rcu_read_lock();
4fa8d299 3537 for_each_domain(rq->cpu, sd) {
d7c01d27 3538 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
b85c8b71 3539 __schedstat_inc(sd->ttwu_wake_remote);
d7c01d27
PZ
3540 break;
3541 }
3542 }
057f3fad 3543 rcu_read_unlock();
d7c01d27 3544 }
f339b9dc
PZ
3545
3546 if (wake_flags & WF_MIGRATED)
ceeadb83 3547 __schedstat_inc(p->stats.nr_wakeups_migrate);
d7c01d27
PZ
3548#endif /* CONFIG_SMP */
3549
b85c8b71 3550 __schedstat_inc(rq->ttwu_count);
ceeadb83 3551 __schedstat_inc(p->stats.nr_wakeups);
d7c01d27
PZ
3552
3553 if (wake_flags & WF_SYNC)
ceeadb83 3554 __schedstat_inc(p->stats.nr_wakeups_sync);
d7c01d27
PZ
3555}
3556
23f41eeb
PZ
3557/*
3558 * Mark the task runnable and perform wakeup-preemption.
3559 */
e7904a28 3560static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 3561 struct rq_flags *rf)
9ed3811a 3562{
9ed3811a 3563 check_preempt_curr(rq, p, wake_flags);
2f064a59 3564 WRITE_ONCE(p->__state, TASK_RUNNING);
fbd705a0
PZ
3565 trace_sched_wakeup(p);
3566
9ed3811a 3567#ifdef CONFIG_SMP
4c9a4bc8
PZ
3568 if (p->sched_class->task_woken) {
3569 /*
b19a888c 3570 * Our task @p is fully woken up and running; so it's safe to
cbce1a68 3571 * drop the rq->lock, hereafter rq is only used for statistics.
4c9a4bc8 3572 */
d8ac8971 3573 rq_unpin_lock(rq, rf);
9ed3811a 3574 p->sched_class->task_woken(rq, p);
d8ac8971 3575 rq_repin_lock(rq, rf);
4c9a4bc8 3576 }
9ed3811a 3577
e69c6341 3578 if (rq->idle_stamp) {
78becc27 3579 u64 delta = rq_clock(rq) - rq->idle_stamp;
9bd721c5 3580 u64 max = 2*rq->max_idle_balance_cost;
9ed3811a 3581
abfafa54
JL
3582 update_avg(&rq->avg_idle, delta);
3583
3584 if (rq->avg_idle > max)
9ed3811a 3585 rq->avg_idle = max;
abfafa54 3586
94aafc3e
PZ
3587 rq->wake_stamp = jiffies;
3588 rq->wake_avg_idle = rq->avg_idle / 2;
3589
9ed3811a
TH
3590 rq->idle_stamp = 0;
3591 }
3592#endif
3593}
3594
c05fbafb 3595static void
e7904a28 3596ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 3597 struct rq_flags *rf)
c05fbafb 3598{
77558e4d 3599 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
b5179ac7 3600
5cb9eaa3 3601 lockdep_assert_rq_held(rq);
cbce1a68 3602
c05fbafb
PZ
3603 if (p->sched_contributes_to_load)
3604 rq->nr_uninterruptible--;
b5179ac7 3605
dbfb089d 3606#ifdef CONFIG_SMP
b5179ac7 3607 if (wake_flags & WF_MIGRATED)
59efa0ba 3608 en_flags |= ENQUEUE_MIGRATED;
ec618b84 3609 else
c05fbafb 3610#endif
ec618b84
PZ
3611 if (p->in_iowait) {
3612 delayacct_blkio_end(p);
3613 atomic_dec(&task_rq(p)->nr_iowait);
3614 }
c05fbafb 3615
1b174a2c 3616 activate_task(rq, p, en_flags);
d8ac8971 3617 ttwu_do_wakeup(rq, p, wake_flags, rf);
c05fbafb
PZ
3618}
3619
3620/*
58877d34
PZ
3621 * Consider @p being inside a wait loop:
3622 *
3623 * for (;;) {
3624 * set_current_state(TASK_UNINTERRUPTIBLE);
3625 *
3626 * if (CONDITION)
3627 * break;
3628 *
3629 * schedule();
3630 * }
3631 * __set_current_state(TASK_RUNNING);
3632 *
3633 * between set_current_state() and schedule(). In this case @p is still
3634 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3635 * an atomic manner.
3636 *
3637 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3638 * then schedule() must still happen and p->state can be changed to
3639 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3640 * need to do a full wakeup with enqueue.
3641 *
3642 * Returns: %true when the wakeup is done,
3643 * %false otherwise.
c05fbafb 3644 */
58877d34 3645static int ttwu_runnable(struct task_struct *p, int wake_flags)
c05fbafb 3646{
eb580751 3647 struct rq_flags rf;
c05fbafb
PZ
3648 struct rq *rq;
3649 int ret = 0;
3650
eb580751 3651 rq = __task_rq_lock(p, &rf);
da0c1e65 3652 if (task_on_rq_queued(p)) {
1ad4ec0d
FW
3653 /* check_preempt_curr() may use rq clock */
3654 update_rq_clock(rq);
d8ac8971 3655 ttwu_do_wakeup(rq, p, wake_flags, &rf);
c05fbafb
PZ
3656 ret = 1;
3657 }
eb580751 3658 __task_rq_unlock(rq, &rf);
c05fbafb
PZ
3659
3660 return ret;
3661}
3662
317f3941 3663#ifdef CONFIG_SMP
a1488664 3664void sched_ttwu_pending(void *arg)
317f3941 3665{
a1488664 3666 struct llist_node *llist = arg;
317f3941 3667 struct rq *rq = this_rq();
73215849 3668 struct task_struct *p, *t;
d8ac8971 3669 struct rq_flags rf;
317f3941 3670
e3baac47
PZ
3671 if (!llist)
3672 return;
3673
126c2092
PZ
3674 /*
3675 * rq::ttwu_pending racy indication of out-standing wakeups.
3676 * Races such that false-negatives are possible, since they
3677 * are shorter lived that false-positives would be.
3678 */
3679 WRITE_ONCE(rq->ttwu_pending, 0);
3680
8a8c69c3 3681 rq_lock_irqsave(rq, &rf);
77558e4d 3682 update_rq_clock(rq);
317f3941 3683
8c4890d1 3684 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
b6e13e85
PZ
3685 if (WARN_ON_ONCE(p->on_cpu))
3686 smp_cond_load_acquire(&p->on_cpu, !VAL);
3687
3688 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
3689 set_task_cpu(p, cpu_of(rq));
3690
73215849 3691 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
b6e13e85 3692 }
317f3941 3693
8a8c69c3 3694 rq_unlock_irqrestore(rq, &rf);
317f3941
PZ
3695}
3696
b2a02fc4 3697void send_call_function_single_ipi(int cpu)
317f3941 3698{
b2a02fc4 3699 struct rq *rq = cpu_rq(cpu);
ca38062e 3700
b2a02fc4
PZ
3701 if (!set_nr_if_polling(rq->idle))
3702 arch_send_call_function_single_ipi(cpu);
3703 else
3704 trace_sched_wake_idle_without_ipi(cpu);
317f3941
PZ
3705}
3706
2ebb1771
MG
3707/*
3708 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
3709 * necessary. The wakee CPU on receipt of the IPI will queue the task
3710 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
3711 * of the wakeup instead of the waker.
3712 */
3713static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
317f3941 3714{
e3baac47
PZ
3715 struct rq *rq = cpu_rq(cpu);
3716
b7e7ade3
PZ
3717 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
3718
126c2092 3719 WRITE_ONCE(rq->ttwu_pending, 1);
8c4890d1 3720 __smp_call_single_queue(cpu, &p->wake_entry.llist);
317f3941 3721}
d6aa8f85 3722
f6be8af1
CL
3723void wake_up_if_idle(int cpu)
3724{
3725 struct rq *rq = cpu_rq(cpu);
8a8c69c3 3726 struct rq_flags rf;
f6be8af1 3727
fd7de1e8
AL
3728 rcu_read_lock();
3729
3730 if (!is_idle_task(rcu_dereference(rq->curr)))
3731 goto out;
f6be8af1 3732
8850cb66
PZ
3733 rq_lock_irqsave(rq, &rf);
3734 if (is_idle_task(rq->curr))
3735 resched_curr(rq);
3736 /* Else CPU is not idle, do nothing here: */
3737 rq_unlock_irqrestore(rq, &rf);
fd7de1e8
AL
3738
3739out:
3740 rcu_read_unlock();
f6be8af1
CL
3741}
3742
39be3501 3743bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623 3744{
42dc938a
VD
3745 if (this_cpu == that_cpu)
3746 return true;
3747
518cd623
PZ
3748 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
3749}
c6e7bd7a 3750
2ebb1771
MG
3751static inline bool ttwu_queue_cond(int cpu, int wake_flags)
3752{
5ba2ffba
PZ
3753 /*
3754 * Do not complicate things with the async wake_list while the CPU is
3755 * in hotplug state.
3756 */
3757 if (!cpu_active(cpu))
3758 return false;
3759
2ebb1771
MG
3760 /*
3761 * If the CPU does not share cache, then queue the task on the
3762 * remote rqs wakelist to avoid accessing remote data.
3763 */
3764 if (!cpus_share_cache(smp_processor_id(), cpu))
3765 return true;
3766
3767 /*
3768 * If the task is descheduling and the only running task on the
3769 * CPU then use the wakelist to offload the task activation to
3770 * the soon-to-be-idle CPU as the current CPU is likely busy.
3771 * nr_running is checked to avoid unnecessary task stacking.
3772 */
739f70b4 3773 if ((wake_flags & WF_ON_CPU) && cpu_rq(cpu)->nr_running <= 1)
2ebb1771
MG
3774 return true;
3775
3776 return false;
3777}
3778
3779static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
c6e7bd7a 3780{
2ebb1771 3781 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(cpu, wake_flags)) {
b6e13e85
PZ
3782 if (WARN_ON_ONCE(cpu == smp_processor_id()))
3783 return false;
3784
c6e7bd7a 3785 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
2ebb1771 3786 __ttwu_queue_wakelist(p, cpu, wake_flags);
c6e7bd7a
PZ
3787 return true;
3788 }
3789
3790 return false;
3791}
58877d34
PZ
3792
3793#else /* !CONFIG_SMP */
3794
3795static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3796{
3797 return false;
3798}
3799
d6aa8f85 3800#endif /* CONFIG_SMP */
317f3941 3801
b5179ac7 3802static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
c05fbafb
PZ
3803{
3804 struct rq *rq = cpu_rq(cpu);
d8ac8971 3805 struct rq_flags rf;
c05fbafb 3806
2ebb1771 3807 if (ttwu_queue_wakelist(p, cpu, wake_flags))
317f3941 3808 return;
317f3941 3809
8a8c69c3 3810 rq_lock(rq, &rf);
77558e4d 3811 update_rq_clock(rq);
d8ac8971 3812 ttwu_do_activate(rq, p, wake_flags, &rf);
8a8c69c3 3813 rq_unlock(rq, &rf);
9ed3811a
TH
3814}
3815
43295d73
TG
3816/*
3817 * Invoked from try_to_wake_up() to check whether the task can be woken up.
3818 *
3819 * The caller holds p::pi_lock if p != current or has preemption
3820 * disabled when p == current.
5f220be2
TG
3821 *
3822 * The rules of PREEMPT_RT saved_state:
3823 *
3824 * The related locking code always holds p::pi_lock when updating
3825 * p::saved_state, which means the code is fully serialized in both cases.
3826 *
3827 * The lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. No other
3828 * bits set. This allows to distinguish all wakeup scenarios.
43295d73
TG
3829 */
3830static __always_inline
3831bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
3832{
5f220be2
TG
3833 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
3834 WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
3835 state != TASK_RTLOCK_WAIT);
3836 }
3837
43295d73
TG
3838 if (READ_ONCE(p->__state) & state) {
3839 *success = 1;
3840 return true;
3841 }
5f220be2
TG
3842
3843#ifdef CONFIG_PREEMPT_RT
3844 /*
3845 * Saved state preserves the task state across blocking on
3846 * an RT lock. If the state matches, set p::saved_state to
3847 * TASK_RUNNING, but do not wake the task because it waits
3848 * for a lock wakeup. Also indicate success because from
3849 * the regular waker's point of view this has succeeded.
3850 *
3851 * After acquiring the lock the task will restore p::__state
3852 * from p::saved_state which ensures that the regular
3853 * wakeup is not lost. The restore will also set
3854 * p::saved_state to TASK_RUNNING so any further tests will
3855 * not result in false positives vs. @success
3856 */
3857 if (p->saved_state & state) {
3858 p->saved_state = TASK_RUNNING;
3859 *success = 1;
3860 }
3861#endif
43295d73
TG
3862 return false;
3863}
3864
8643cda5
PZ
3865/*
3866 * Notes on Program-Order guarantees on SMP systems.
3867 *
3868 * MIGRATION
3869 *
3870 * The basic program-order guarantee on SMP systems is that when a task [t]
d1ccc66d
IM
3871 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
3872 * execution on its new CPU [c1].
8643cda5
PZ
3873 *
3874 * For migration (of runnable tasks) this is provided by the following means:
3875 *
3876 * A) UNLOCK of the rq(c0)->lock scheduling out task t
3877 * B) migration for t is required to synchronize *both* rq(c0)->lock and
3878 * rq(c1)->lock (if not at the same time, then in that order).
3879 * C) LOCK of the rq(c1)->lock scheduling in task
3880 *
7696f991 3881 * Release/acquire chaining guarantees that B happens after A and C after B.
d1ccc66d 3882 * Note: the CPU doing B need not be c0 or c1
8643cda5
PZ
3883 *
3884 * Example:
3885 *
3886 * CPU0 CPU1 CPU2
3887 *
3888 * LOCK rq(0)->lock
3889 * sched-out X
3890 * sched-in Y
3891 * UNLOCK rq(0)->lock
3892 *
3893 * LOCK rq(0)->lock // orders against CPU0
3894 * dequeue X
3895 * UNLOCK rq(0)->lock
3896 *
3897 * LOCK rq(1)->lock
3898 * enqueue X
3899 * UNLOCK rq(1)->lock
3900 *
3901 * LOCK rq(1)->lock // orders against CPU2
3902 * sched-out Z
3903 * sched-in X
3904 * UNLOCK rq(1)->lock
3905 *
3906 *
3907 * BLOCKING -- aka. SLEEP + WAKEUP
3908 *
3909 * For blocking we (obviously) need to provide the same guarantee as for
3910 * migration. However the means are completely different as there is no lock
3911 * chain to provide order. Instead we do:
3912 *
58877d34
PZ
3913 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
3914 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
8643cda5
PZ
3915 *
3916 * Example:
3917 *
3918 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
3919 *
3920 * LOCK rq(0)->lock LOCK X->pi_lock
3921 * dequeue X
3922 * sched-out X
3923 * smp_store_release(X->on_cpu, 0);
3924 *
1f03e8d2 3925 * smp_cond_load_acquire(&X->on_cpu, !VAL);
8643cda5
PZ
3926 * X->state = WAKING
3927 * set_task_cpu(X,2)
3928 *
3929 * LOCK rq(2)->lock
3930 * enqueue X
3931 * X->state = RUNNING
3932 * UNLOCK rq(2)->lock
3933 *
3934 * LOCK rq(2)->lock // orders against CPU1
3935 * sched-out Z
3936 * sched-in X
3937 * UNLOCK rq(2)->lock
3938 *
3939 * UNLOCK X->pi_lock
3940 * UNLOCK rq(0)->lock
3941 *
3942 *
7696f991
AP
3943 * However, for wakeups there is a second guarantee we must provide, namely we
3944 * must ensure that CONDITION=1 done by the caller can not be reordered with
3945 * accesses to the task state; see try_to_wake_up() and set_current_state().
8643cda5
PZ
3946 */
3947
9ed3811a 3948/**
1da177e4 3949 * try_to_wake_up - wake up a thread
9ed3811a 3950 * @p: the thread to be awakened
1da177e4 3951 * @state: the mask of task states that can be woken
9ed3811a 3952 * @wake_flags: wake modifier flags (WF_*)
1da177e4 3953 *
58877d34
PZ
3954 * Conceptually does:
3955 *
3956 * If (@state & @p->state) @p->state = TASK_RUNNING.
1da177e4 3957 *
a2250238
PZ
3958 * If the task was not queued/runnable, also place it back on a runqueue.
3959 *
58877d34
PZ
3960 * This function is atomic against schedule() which would dequeue the task.
3961 *
3962 * It issues a full memory barrier before accessing @p->state, see the comment
3963 * with set_current_state().
a2250238 3964 *
58877d34 3965 * Uses p->pi_lock to serialize against concurrent wake-ups.
a2250238 3966 *
58877d34
PZ
3967 * Relies on p->pi_lock stabilizing:
3968 * - p->sched_class
3969 * - p->cpus_ptr
3970 * - p->sched_task_group
3971 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
3972 *
3973 * Tries really hard to only take one task_rq(p)->lock for performance.
3974 * Takes rq->lock in:
3975 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
3976 * - ttwu_queue() -- new rq, for enqueue of the task;
3977 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
3978 *
3979 * As a consequence we race really badly with just about everything. See the
3980 * many memory barriers and their comments for details.
7696f991 3981 *
a2250238
PZ
3982 * Return: %true if @p->state changes (an actual wakeup was done),
3983 * %false otherwise.
1da177e4 3984 */
e4a52bcb
PZ
3985static int
3986try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 3987{
1da177e4 3988 unsigned long flags;
c05fbafb 3989 int cpu, success = 0;
2398f2c6 3990
e3d85487 3991 preempt_disable();
aacedf26
PZ
3992 if (p == current) {
3993 /*
3994 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
3995 * == smp_processor_id()'. Together this means we can special
58877d34 3996 * case the whole 'p->on_rq && ttwu_runnable()' case below
aacedf26
PZ
3997 * without taking any locks.
3998 *
3999 * In particular:
4000 * - we rely on Program-Order guarantees for all the ordering,
4001 * - we're serialized against set_special_state() by virtue of
4002 * it disabling IRQs (this allows not taking ->pi_lock).
4003 */
43295d73 4004 if (!ttwu_state_match(p, state, &success))
e3d85487 4005 goto out;
aacedf26 4006
aacedf26 4007 trace_sched_waking(p);
2f064a59 4008 WRITE_ONCE(p->__state, TASK_RUNNING);
aacedf26
PZ
4009 trace_sched_wakeup(p);
4010 goto out;
4011 }
4012
e0acd0a6
ON
4013 /*
4014 * If we are going to wake up a thread waiting for CONDITION we
4015 * need to ensure that CONDITION=1 done by the caller can not be
58877d34
PZ
4016 * reordered with p->state check below. This pairs with smp_store_mb()
4017 * in set_current_state() that the waiting thread does.
e0acd0a6 4018 */
013fdb80 4019 raw_spin_lock_irqsave(&p->pi_lock, flags);
d89e588c 4020 smp_mb__after_spinlock();
43295d73 4021 if (!ttwu_state_match(p, state, &success))
aacedf26 4022 goto unlock;
1da177e4 4023
fbd705a0
PZ
4024 trace_sched_waking(p);
4025
135e8c92
BS
4026 /*
4027 * Ensure we load p->on_rq _after_ p->state, otherwise it would
4028 * be possible to, falsely, observe p->on_rq == 0 and get stuck
4029 * in smp_cond_load_acquire() below.
4030 *
3d85b270
AP
4031 * sched_ttwu_pending() try_to_wake_up()
4032 * STORE p->on_rq = 1 LOAD p->state
4033 * UNLOCK rq->lock
4034 *
4035 * __schedule() (switch to task 'p')
4036 * LOCK rq->lock smp_rmb();
4037 * smp_mb__after_spinlock();
4038 * UNLOCK rq->lock
135e8c92
BS
4039 *
4040 * [task p]
3d85b270 4041 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
135e8c92 4042 *
3d85b270
AP
4043 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4044 * __schedule(). See the comment for smp_mb__after_spinlock().
2beaf328
PM
4045 *
4046 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
135e8c92
BS
4047 */
4048 smp_rmb();
58877d34 4049 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
aacedf26 4050 goto unlock;
1da177e4 4051
1da177e4 4052#ifdef CONFIG_SMP
ecf7d01c
PZ
4053 /*
4054 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
4055 * possible to, falsely, observe p->on_cpu == 0.
4056 *
4057 * One must be running (->on_cpu == 1) in order to remove oneself
4058 * from the runqueue.
4059 *
3d85b270
AP
4060 * __schedule() (switch to task 'p') try_to_wake_up()
4061 * STORE p->on_cpu = 1 LOAD p->on_rq
4062 * UNLOCK rq->lock
4063 *
4064 * __schedule() (put 'p' to sleep)
4065 * LOCK rq->lock smp_rmb();
4066 * smp_mb__after_spinlock();
4067 * STORE p->on_rq = 0 LOAD p->on_cpu
ecf7d01c 4068 *
3d85b270
AP
4069 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4070 * __schedule(). See the comment for smp_mb__after_spinlock().
dbfb089d
PZ
4071 *
4072 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
4073 * schedule()'s deactivate_task() has 'happened' and p will no longer
4074 * care about it's own p->state. See the comment in __schedule().
ecf7d01c 4075 */
dbfb089d
PZ
4076 smp_acquire__after_ctrl_dep();
4077
4078 /*
4079 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
4080 * == 0), which means we need to do an enqueue, change p->state to
4081 * TASK_WAKING such that we can unlock p->pi_lock before doing the
4082 * enqueue, such as ttwu_queue_wakelist().
4083 */
2f064a59 4084 WRITE_ONCE(p->__state, TASK_WAKING);
ecf7d01c 4085
c6e7bd7a
PZ
4086 /*
4087 * If the owning (remote) CPU is still in the middle of schedule() with
4088 * this task as prev, considering queueing p on the remote CPUs wake_list
4089 * which potentially sends an IPI instead of spinning on p->on_cpu to
4090 * let the waker make forward progress. This is safe because IRQs are
4091 * disabled and the IPI will deliver after on_cpu is cleared.
b6e13e85
PZ
4092 *
4093 * Ensure we load task_cpu(p) after p->on_cpu:
4094 *
4095 * set_task_cpu(p, cpu);
4096 * STORE p->cpu = @cpu
4097 * __schedule() (switch to task 'p')
4098 * LOCK rq->lock
4099 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
4100 * STORE p->on_cpu = 1 LOAD p->cpu
4101 *
4102 * to ensure we observe the correct CPU on which the task is currently
4103 * scheduling.
c6e7bd7a 4104 */
b6e13e85 4105 if (smp_load_acquire(&p->on_cpu) &&
739f70b4 4106 ttwu_queue_wakelist(p, task_cpu(p), wake_flags | WF_ON_CPU))
c6e7bd7a
PZ
4107 goto unlock;
4108
e9c84311 4109 /*
d1ccc66d 4110 * If the owning (remote) CPU is still in the middle of schedule() with
b19a888c 4111 * this task as prev, wait until it's done referencing the task.
b75a2253 4112 *
31cb1bc0 4113 * Pairs with the smp_store_release() in finish_task().
b75a2253
PZ
4114 *
4115 * This ensures that tasks getting woken will be fully ordered against
4116 * their previous state and preserve Program Order.
0970d299 4117 */
1f03e8d2 4118 smp_cond_load_acquire(&p->on_cpu, !VAL);
1da177e4 4119
3aef1551 4120 cpu = select_task_rq(p, p->wake_cpu, wake_flags | WF_TTWU);
f339b9dc 4121 if (task_cpu(p) != cpu) {
ec618b84
PZ
4122 if (p->in_iowait) {
4123 delayacct_blkio_end(p);
4124 atomic_dec(&task_rq(p)->nr_iowait);
4125 }
4126
f339b9dc 4127 wake_flags |= WF_MIGRATED;
eb414681 4128 psi_ttwu_dequeue(p);
e4a52bcb 4129 set_task_cpu(p, cpu);
f339b9dc 4130 }
b6e13e85
PZ
4131#else
4132 cpu = task_cpu(p);
1da177e4 4133#endif /* CONFIG_SMP */
1da177e4 4134
b5179ac7 4135 ttwu_queue(p, cpu, wake_flags);
aacedf26 4136unlock:
013fdb80 4137 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
aacedf26
PZ
4138out:
4139 if (success)
b6e13e85 4140 ttwu_stat(p, task_cpu(p), wake_flags);
e3d85487 4141 preempt_enable();
1da177e4
LT
4142
4143 return success;
4144}
4145
2beaf328 4146/**
9b3c4ab3 4147 * task_call_func - Invoke a function on task in fixed state
1b7af295 4148 * @p: Process for which the function is to be invoked, can be @current.
2beaf328
PM
4149 * @func: Function to invoke.
4150 * @arg: Argument to function.
4151 *
f6ac18fa
PZ
4152 * Fix the task in it's current state by avoiding wakeups and or rq operations
4153 * and call @func(@arg) on it. This function can use ->on_rq and task_curr()
4154 * to work out what the state is, if required. Given that @func can be invoked
4155 * with a runqueue lock held, it had better be quite lightweight.
2beaf328
PM
4156 *
4157 * Returns:
f6ac18fa 4158 * Whatever @func returns
2beaf328 4159 */
9b3c4ab3 4160int task_call_func(struct task_struct *p, task_call_f func, void *arg)
2beaf328 4161{
f6ac18fa
PZ
4162 struct rq *rq = NULL;
4163 unsigned int state;
2beaf328 4164 struct rq_flags rf;
9b3c4ab3 4165 int ret;
2beaf328 4166
1b7af295 4167 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
f6ac18fa
PZ
4168
4169 state = READ_ONCE(p->__state);
4170
4171 /*
4172 * Ensure we load p->on_rq after p->__state, otherwise it would be
4173 * possible to, falsely, observe p->on_rq == 0.
4174 *
4175 * See try_to_wake_up() for a longer comment.
4176 */
4177 smp_rmb();
4178
4179 /*
4180 * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
4181 * the task is blocked. Make sure to check @state since ttwu() can drop
4182 * locks at the end, see ttwu_queue_wakelist().
4183 */
4184 if (state == TASK_RUNNING || state == TASK_WAKING || p->on_rq)
2beaf328 4185 rq = __task_rq_lock(p, &rf);
f6ac18fa
PZ
4186
4187 /*
4188 * At this point the task is pinned; either:
4189 * - blocked and we're holding off wakeups (pi->lock)
4190 * - woken, and we're holding off enqueue (rq->lock)
4191 * - queued, and we're holding off schedule (rq->lock)
4192 * - running, and we're holding off de-schedule (rq->lock)
4193 *
4194 * The called function (@func) can use: task_curr(), p->on_rq and
4195 * p->__state to differentiate between these states.
4196 */
4197 ret = func(p, arg);
4198
4199 if (rq)
2beaf328 4200 rq_unlock(rq, &rf);
f6ac18fa 4201
1b7af295 4202 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
2beaf328
PM
4203 return ret;
4204}
4205
50fa610a
DH
4206/**
4207 * wake_up_process - Wake up a specific process
4208 * @p: The process to be woken up.
4209 *
4210 * Attempt to wake up the nominated process and move it to the set of runnable
e69f6186
YB
4211 * processes.
4212 *
4213 * Return: 1 if the process was woken up, 0 if it was already running.
50fa610a 4214 *
7696f991 4215 * This function executes a full memory barrier before accessing the task state.
50fa610a 4216 */
7ad5b3a5 4217int wake_up_process(struct task_struct *p)
1da177e4 4218{
9067ac85 4219 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 4220}
1da177e4
LT
4221EXPORT_SYMBOL(wake_up_process);
4222
7ad5b3a5 4223int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
4224{
4225 return try_to_wake_up(p, state, 0);
4226}
4227
1da177e4
LT
4228/*
4229 * Perform scheduler related setup for a newly forked process p.
4230 * p is forked by current.
dd41f596
IM
4231 *
4232 * __sched_fork() is basic setup used by init_idle() too:
4233 */
5e1576ed 4234static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 4235{
fd2f4419
PZ
4236 p->on_rq = 0;
4237
4238 p->se.on_rq = 0;
dd41f596
IM
4239 p->se.exec_start = 0;
4240 p->se.sum_exec_runtime = 0;
f6cf891c 4241 p->se.prev_sum_exec_runtime = 0;
6c594c21 4242 p->se.nr_migrations = 0;
da7a735e 4243 p->se.vruntime = 0;
fd2f4419 4244 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 4245
ad936d86
BP
4246#ifdef CONFIG_FAIR_GROUP_SCHED
4247 p->se.cfs_rq = NULL;
4248#endif
4249
6cfb0d5d 4250#ifdef CONFIG_SCHEDSTATS
cb251765 4251 /* Even if schedstat is disabled, there should not be garbage */
ceeadb83 4252 memset(&p->stats, 0, sizeof(p->stats));
6cfb0d5d 4253#endif
476d139c 4254
aab03e05 4255 RB_CLEAR_NODE(&p->dl.rb_node);
40767b0d 4256 init_dl_task_timer(&p->dl);
209a0cbd 4257 init_dl_inactive_task_timer(&p->dl);
a5e7be3b 4258 __dl_clear_params(p);
aab03e05 4259
fa717060 4260 INIT_LIST_HEAD(&p->rt.run_list);
ff77e468
PZ
4261 p->rt.timeout = 0;
4262 p->rt.time_slice = sched_rr_timeslice;
4263 p->rt.on_rq = 0;
4264 p->rt.on_list = 0;
476d139c 4265
e107be36
AK
4266#ifdef CONFIG_PREEMPT_NOTIFIERS
4267 INIT_HLIST_HEAD(&p->preempt_notifiers);
4268#endif
cbee9f88 4269
5e1f0f09
MG
4270#ifdef CONFIG_COMPACTION
4271 p->capture_control = NULL;
4272#endif
13784475 4273 init_numa_balancing(clone_flags, p);
a1488664 4274#ifdef CONFIG_SMP
8c4890d1 4275 p->wake_entry.u_flags = CSD_TYPE_TTWU;
6d337eab 4276 p->migration_pending = NULL;
a1488664 4277#endif
dd41f596
IM
4278}
4279
2a595721
SD
4280DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
4281
1a687c2e 4282#ifdef CONFIG_NUMA_BALANCING
c3b9bc5b 4283
1a687c2e
MG
4284void set_numabalancing_state(bool enabled)
4285{
4286 if (enabled)
2a595721 4287 static_branch_enable(&sched_numa_balancing);
1a687c2e 4288 else
2a595721 4289 static_branch_disable(&sched_numa_balancing);
1a687c2e 4290}
54a43d54
AK
4291
4292#ifdef CONFIG_PROC_SYSCTL
4293int sysctl_numa_balancing(struct ctl_table *table, int write,
32927393 4294 void *buffer, size_t *lenp, loff_t *ppos)
54a43d54
AK
4295{
4296 struct ctl_table t;
4297 int err;
2a595721 4298 int state = static_branch_likely(&sched_numa_balancing);
54a43d54
AK
4299
4300 if (write && !capable(CAP_SYS_ADMIN))
4301 return -EPERM;
4302
4303 t = *table;
4304 t.data = &state;
4305 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4306 if (err < 0)
4307 return err;
4308 if (write)
4309 set_numabalancing_state(state);
4310 return err;
4311}
4312#endif
4313#endif
dd41f596 4314
4698f88c
JP
4315#ifdef CONFIG_SCHEDSTATS
4316
cb251765
MG
4317DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4318
cb251765
MG
4319static void set_schedstats(bool enabled)
4320{
4321 if (enabled)
4322 static_branch_enable(&sched_schedstats);
4323 else
4324 static_branch_disable(&sched_schedstats);
4325}
4326
4327void force_schedstat_enabled(void)
4328{
4329 if (!schedstat_enabled()) {
4330 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4331 static_branch_enable(&sched_schedstats);
4332 }
4333}
4334
4335static int __init setup_schedstats(char *str)
4336{
4337 int ret = 0;
4338 if (!str)
4339 goto out;
4340
4341 if (!strcmp(str, "enable")) {
1faa491a 4342 set_schedstats(true);
cb251765
MG
4343 ret = 1;
4344 } else if (!strcmp(str, "disable")) {
1faa491a 4345 set_schedstats(false);
cb251765
MG
4346 ret = 1;
4347 }
4348out:
4349 if (!ret)
4350 pr_warn("Unable to parse schedstats=\n");
4351
4352 return ret;
4353}
4354__setup("schedstats=", setup_schedstats);
4355
4356#ifdef CONFIG_PROC_SYSCTL
32927393
CH
4357int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
4358 size_t *lenp, loff_t *ppos)
cb251765
MG
4359{
4360 struct ctl_table t;
4361 int err;
4362 int state = static_branch_likely(&sched_schedstats);
4363
4364 if (write && !capable(CAP_SYS_ADMIN))
4365 return -EPERM;
4366
4367 t = *table;
4368 t.data = &state;
4369 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4370 if (err < 0)
4371 return err;
4372 if (write)
4373 set_schedstats(state);
4374 return err;
4375}
4698f88c 4376#endif /* CONFIG_PROC_SYSCTL */
4698f88c 4377#endif /* CONFIG_SCHEDSTATS */
dd41f596
IM
4378
4379/*
4380 * fork()/clone()-time setup:
4381 */
aab03e05 4382int sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 4383{
5e1576ed 4384 __sched_fork(clone_flags, p);
06b83b5f 4385 /*
7dc603c9 4386 * We mark the process as NEW here. This guarantees that
06b83b5f
PZ
4387 * nobody will actually run it, and a signal or other external
4388 * event cannot wake it up and insert it on the runqueue either.
4389 */
2f064a59 4390 p->__state = TASK_NEW;
dd41f596 4391
c350a04e
MG
4392 /*
4393 * Make sure we do not leak PI boosting priority to the child.
4394 */
4395 p->prio = current->normal_prio;
4396
e8f14172
PB
4397 uclamp_fork(p);
4398
b9dc29e7
MG
4399 /*
4400 * Revert to default priority/policy on fork if requested.
4401 */
4402 if (unlikely(p->sched_reset_on_fork)) {
aab03e05 4403 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
b9dc29e7 4404 p->policy = SCHED_NORMAL;
6c697bdf 4405 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
4406 p->rt_priority = 0;
4407 } else if (PRIO_TO_NICE(p->static_prio) < 0)
4408 p->static_prio = NICE_TO_PRIO(0);
4409
f558c2b8 4410 p->prio = p->normal_prio = p->static_prio;
9059393e 4411 set_load_weight(p, false);
6c697bdf 4412
b9dc29e7
MG
4413 /*
4414 * We don't need the reset flag anymore after the fork. It has
4415 * fulfilled its duty:
4416 */
4417 p->sched_reset_on_fork = 0;
4418 }
ca94c442 4419
af0fffd9 4420 if (dl_prio(p->prio))
aab03e05 4421 return -EAGAIN;
af0fffd9 4422 else if (rt_prio(p->prio))
aab03e05 4423 p->sched_class = &rt_sched_class;
af0fffd9 4424 else
2ddbf952 4425 p->sched_class = &fair_sched_class;
b29739f9 4426
7dc603c9 4427 init_entity_runnable_average(&p->se);
cd29fe6f 4428
f6db8347 4429#ifdef CONFIG_SCHED_INFO
dd41f596 4430 if (likely(sched_info_on()))
52f17b6c 4431 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 4432#endif
3ca7a440
PZ
4433#if defined(CONFIG_SMP)
4434 p->on_cpu = 0;
4866cde0 4435#endif
01028747 4436 init_task_preempt_count(p);
806c09a7 4437#ifdef CONFIG_SMP
917b627d 4438 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1baca4ce 4439 RB_CLEAR_NODE(&p->pushable_dl_tasks);
806c09a7 4440#endif
aab03e05 4441 return 0;
1da177e4
LT
4442}
4443
4ef0c5c6 4444void sched_post_fork(struct task_struct *p, struct kernel_clone_args *kargs)
13685c4a 4445{
4ef0c5c6
ZQ
4446 unsigned long flags;
4447#ifdef CONFIG_CGROUP_SCHED
4448 struct task_group *tg;
4449#endif
4450
4451 raw_spin_lock_irqsave(&p->pi_lock, flags);
4452#ifdef CONFIG_CGROUP_SCHED
4453 tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
4454 struct task_group, css);
4455 p->sched_task_group = autogroup_task_group(p, tg);
4456#endif
4457 rseq_migrate(p);
4458 /*
4459 * We're setting the CPU for the first time, we don't migrate,
4460 * so use __set_task_cpu().
4461 */
4462 __set_task_cpu(p, smp_processor_id());
4463 if (p->sched_class->task_fork)
4464 p->sched_class->task_fork(p);
4465 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4466
13685c4a
QY
4467 uclamp_post_fork(p);
4468}
4469
332ac17e
DF
4470unsigned long to_ratio(u64 period, u64 runtime)
4471{
4472 if (runtime == RUNTIME_INF)
c52f14d3 4473 return BW_UNIT;
332ac17e
DF
4474
4475 /*
4476 * Doing this here saves a lot of checks in all
4477 * the calling paths, and returning zero seems
4478 * safe for them anyway.
4479 */
4480 if (period == 0)
4481 return 0;
4482
c52f14d3 4483 return div64_u64(runtime << BW_SHIFT, period);
332ac17e
DF
4484}
4485
1da177e4
LT
4486/*
4487 * wake_up_new_task - wake up a newly created task for the first time.
4488 *
4489 * This function will do some initial scheduler statistics housekeeping
4490 * that must be done for every newly created context, then puts the task
4491 * on the runqueue and wakes it.
4492 */
3e51e3ed 4493void wake_up_new_task(struct task_struct *p)
1da177e4 4494{
eb580751 4495 struct rq_flags rf;
dd41f596 4496 struct rq *rq;
fabf318e 4497
eb580751 4498 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2f064a59 4499 WRITE_ONCE(p->__state, TASK_RUNNING);
fabf318e
PZ
4500#ifdef CONFIG_SMP
4501 /*
4502 * Fork balancing, do it here and not earlier because:
3bd37062 4503 * - cpus_ptr can change in the fork path
d1ccc66d 4504 * - any previously selected CPU might disappear through hotplug
e210bffd
PZ
4505 *
4506 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4507 * as we're not fully set-up yet.
fabf318e 4508 */
32e839dd 4509 p->recent_used_cpu = task_cpu(p);
ce3614da 4510 rseq_migrate(p);
3aef1551 4511 __set_task_cpu(p, select_task_rq(p, task_cpu(p), WF_FORK));
0017d735 4512#endif
b7fa30c9 4513 rq = __task_rq_lock(p, &rf);
4126bad6 4514 update_rq_clock(rq);
d0fe0b9c 4515 post_init_entity_util_avg(p);
0017d735 4516
7a57f32a 4517 activate_task(rq, p, ENQUEUE_NOCLOCK);
fbd705a0 4518 trace_sched_wakeup_new(p);
a7558e01 4519 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 4520#ifdef CONFIG_SMP
0aaafaab
PZ
4521 if (p->sched_class->task_woken) {
4522 /*
b19a888c 4523 * Nothing relies on rq->lock after this, so it's fine to
0aaafaab
PZ
4524 * drop it.
4525 */
d8ac8971 4526 rq_unpin_lock(rq, &rf);
efbbd05a 4527 p->sched_class->task_woken(rq, p);
d8ac8971 4528 rq_repin_lock(rq, &rf);
0aaafaab 4529 }
9a897c5a 4530#endif
eb580751 4531 task_rq_unlock(rq, p, &rf);
1da177e4
LT
4532}
4533
e107be36
AK
4534#ifdef CONFIG_PREEMPT_NOTIFIERS
4535
b7203428 4536static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
1cde2930 4537
2ecd9d29
PZ
4538void preempt_notifier_inc(void)
4539{
b7203428 4540 static_branch_inc(&preempt_notifier_key);
2ecd9d29
PZ
4541}
4542EXPORT_SYMBOL_GPL(preempt_notifier_inc);
4543
4544void preempt_notifier_dec(void)
4545{
b7203428 4546 static_branch_dec(&preempt_notifier_key);
2ecd9d29
PZ
4547}
4548EXPORT_SYMBOL_GPL(preempt_notifier_dec);
4549
e107be36 4550/**
80dd99b3 4551 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 4552 * @notifier: notifier struct to register
e107be36
AK
4553 */
4554void preempt_notifier_register(struct preempt_notifier *notifier)
4555{
b7203428 4556 if (!static_branch_unlikely(&preempt_notifier_key))
2ecd9d29
PZ
4557 WARN(1, "registering preempt_notifier while notifiers disabled\n");
4558
e107be36
AK
4559 hlist_add_head(&notifier->link, &current->preempt_notifiers);
4560}
4561EXPORT_SYMBOL_GPL(preempt_notifier_register);
4562
4563/**
4564 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 4565 * @notifier: notifier struct to unregister
e107be36 4566 *
d84525a8 4567 * This is *not* safe to call from within a preemption notifier.
e107be36
AK
4568 */
4569void preempt_notifier_unregister(struct preempt_notifier *notifier)
4570{
4571 hlist_del(&notifier->link);
4572}
4573EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
4574
1cde2930 4575static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
4576{
4577 struct preempt_notifier *notifier;
e107be36 4578
b67bfe0d 4579 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
4580 notifier->ops->sched_in(notifier, raw_smp_processor_id());
4581}
4582
1cde2930
PZ
4583static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4584{
b7203428 4585 if (static_branch_unlikely(&preempt_notifier_key))
1cde2930
PZ
4586 __fire_sched_in_preempt_notifiers(curr);
4587}
4588
e107be36 4589static void
1cde2930
PZ
4590__fire_sched_out_preempt_notifiers(struct task_struct *curr,
4591 struct task_struct *next)
e107be36
AK
4592{
4593 struct preempt_notifier *notifier;
e107be36 4594
b67bfe0d 4595 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
4596 notifier->ops->sched_out(notifier, next);
4597}
4598
1cde2930
PZ
4599static __always_inline void
4600fire_sched_out_preempt_notifiers(struct task_struct *curr,
4601 struct task_struct *next)
4602{
b7203428 4603 if (static_branch_unlikely(&preempt_notifier_key))
1cde2930
PZ
4604 __fire_sched_out_preempt_notifiers(curr, next);
4605}
4606
6d6bc0ad 4607#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36 4608
1cde2930 4609static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
4610{
4611}
4612
1cde2930 4613static inline void
e107be36
AK
4614fire_sched_out_preempt_notifiers(struct task_struct *curr,
4615 struct task_struct *next)
4616{
4617}
4618
6d6bc0ad 4619#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 4620
31cb1bc0 4621static inline void prepare_task(struct task_struct *next)
4622{
4623#ifdef CONFIG_SMP
4624 /*
4625 * Claim the task as running, we do this before switching to it
4626 * such that any running task will have this set.
58877d34
PZ
4627 *
4628 * See the ttwu() WF_ON_CPU case and its ordering comment.
31cb1bc0 4629 */
58877d34 4630 WRITE_ONCE(next->on_cpu, 1);
31cb1bc0 4631#endif
4632}
4633
4634static inline void finish_task(struct task_struct *prev)
4635{
4636#ifdef CONFIG_SMP
4637 /*
58877d34
PZ
4638 * This must be the very last reference to @prev from this CPU. After
4639 * p->on_cpu is cleared, the task can be moved to a different CPU. We
4640 * must ensure this doesn't happen until the switch is completely
31cb1bc0 4641 * finished.
4642 *
4643 * In particular, the load of prev->state in finish_task_switch() must
4644 * happen before this.
4645 *
4646 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
4647 */
4648 smp_store_release(&prev->on_cpu, 0);
4649#endif
4650}
4651
565790d2
PZ
4652#ifdef CONFIG_SMP
4653
4654static void do_balance_callbacks(struct rq *rq, struct callback_head *head)
4655{
4656 void (*func)(struct rq *rq);
4657 struct callback_head *next;
4658
5cb9eaa3 4659 lockdep_assert_rq_held(rq);
565790d2
PZ
4660
4661 while (head) {
4662 func = (void (*)(struct rq *))head->func;
4663 next = head->next;
4664 head->next = NULL;
4665 head = next;
4666
4667 func(rq);
4668 }
4669}
4670
ae792702
PZ
4671static void balance_push(struct rq *rq);
4672
4673struct callback_head balance_push_callback = {
4674 .next = NULL,
4675 .func = (void (*)(struct callback_head *))balance_push,
4676};
4677
565790d2
PZ
4678static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4679{
4680 struct callback_head *head = rq->balance_callback;
4681
5cb9eaa3 4682 lockdep_assert_rq_held(rq);
ae792702 4683 if (head)
565790d2
PZ
4684 rq->balance_callback = NULL;
4685
4686 return head;
4687}
4688
4689static void __balance_callbacks(struct rq *rq)
4690{
4691 do_balance_callbacks(rq, splice_balance_callbacks(rq));
4692}
4693
4694static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4695{
4696 unsigned long flags;
4697
4698 if (unlikely(head)) {
5cb9eaa3 4699 raw_spin_rq_lock_irqsave(rq, flags);
565790d2 4700 do_balance_callbacks(rq, head);
5cb9eaa3 4701 raw_spin_rq_unlock_irqrestore(rq, flags);
565790d2
PZ
4702 }
4703}
4704
4705#else
4706
4707static inline void __balance_callbacks(struct rq *rq)
4708{
4709}
4710
4711static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4712{
4713 return NULL;
4714}
4715
4716static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4717{
4718}
4719
4720#endif
4721
269d5992
PZ
4722static inline void
4723prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
31cb1bc0 4724{
269d5992
PZ
4725 /*
4726 * Since the runqueue lock will be released by the next
4727 * task (which is an invalid locking op but in the case
4728 * of the scheduler it's an obvious special-case), so we
4729 * do an early lockdep release here:
4730 */
4731 rq_unpin_lock(rq, rf);
9ef7e7e3 4732 spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
31cb1bc0 4733#ifdef CONFIG_DEBUG_SPINLOCK
4734 /* this is a valid case when another task releases the spinlock */
5cb9eaa3 4735 rq_lockp(rq)->owner = next;
31cb1bc0 4736#endif
269d5992
PZ
4737}
4738
4739static inline void finish_lock_switch(struct rq *rq)
4740{
31cb1bc0 4741 /*
4742 * If we are tracking spinlock dependencies then we have to
4743 * fix up the runqueue lock - which gets 'carried over' from
4744 * prev into current:
4745 */
9ef7e7e3 4746 spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
ae792702 4747 __balance_callbacks(rq);
5cb9eaa3 4748 raw_spin_rq_unlock_irq(rq);
31cb1bc0 4749}
4750
325ea10c
IM
4751/*
4752 * NOP if the arch has not defined these:
4753 */
4754
4755#ifndef prepare_arch_switch
4756# define prepare_arch_switch(next) do { } while (0)
4757#endif
4758
4759#ifndef finish_arch_post_lock_switch
4760# define finish_arch_post_lock_switch() do { } while (0)
4761#endif
4762
5fbda3ec
TG
4763static inline void kmap_local_sched_out(void)
4764{
4765#ifdef CONFIG_KMAP_LOCAL
4766 if (unlikely(current->kmap_ctrl.idx))
4767 __kmap_local_sched_out();
4768#endif
4769}
4770
4771static inline void kmap_local_sched_in(void)
4772{
4773#ifdef CONFIG_KMAP_LOCAL
4774 if (unlikely(current->kmap_ctrl.idx))
4775 __kmap_local_sched_in();
4776#endif
4777}
4778
4866cde0
NP
4779/**
4780 * prepare_task_switch - prepare to switch tasks
4781 * @rq: the runqueue preparing to switch
421cee29 4782 * @prev: the current task that is being switched out
4866cde0
NP
4783 * @next: the task we are going to switch to.
4784 *
4785 * This is called with the rq lock held and interrupts off. It must
4786 * be paired with a subsequent finish_task_switch after the context
4787 * switch.
4788 *
4789 * prepare_task_switch sets up locking and calls architecture specific
4790 * hooks.
4791 */
e107be36
AK
4792static inline void
4793prepare_task_switch(struct rq *rq, struct task_struct *prev,
4794 struct task_struct *next)
4866cde0 4795{
0ed557aa 4796 kcov_prepare_switch(prev);
43148951 4797 sched_info_switch(rq, prev, next);
fe4b04fa 4798 perf_event_task_sched_out(prev, next);
d7822b1e 4799 rseq_preempt(prev);
e107be36 4800 fire_sched_out_preempt_notifiers(prev, next);
5fbda3ec 4801 kmap_local_sched_out();
31cb1bc0 4802 prepare_task(next);
4866cde0
NP
4803 prepare_arch_switch(next);
4804}
4805
1da177e4
LT
4806/**
4807 * finish_task_switch - clean up after a task-switch
4808 * @prev: the thread we just switched away from.
4809 *
4866cde0
NP
4810 * finish_task_switch must be called after the context switch, paired
4811 * with a prepare_task_switch call before the context switch.
4812 * finish_task_switch will reconcile locking set up by prepare_task_switch,
4813 * and do any other architecture-specific cleanup actions.
1da177e4
LT
4814 *
4815 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 4816 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
4817 * with the lock held can cause deadlocks; see schedule() for
4818 * details.)
dfa50b60
ON
4819 *
4820 * The context switch have flipped the stack from under us and restored the
4821 * local variables which were saved when this task called schedule() in the
4822 * past. prev == current is still correct but we need to recalculate this_rq
4823 * because prev may have moved to another CPU.
1da177e4 4824 */
dfa50b60 4825static struct rq *finish_task_switch(struct task_struct *prev)
1da177e4
LT
4826 __releases(rq->lock)
4827{
dfa50b60 4828 struct rq *rq = this_rq();
1da177e4 4829 struct mm_struct *mm = rq->prev_mm;
55a101f8 4830 long prev_state;
1da177e4 4831
609ca066
PZ
4832 /*
4833 * The previous task will have left us with a preempt_count of 2
4834 * because it left us after:
4835 *
4836 * schedule()
4837 * preempt_disable(); // 1
4838 * __schedule()
4839 * raw_spin_lock_irq(&rq->lock) // 2
4840 *
4841 * Also, see FORK_PREEMPT_COUNT.
4842 */
e2bf1c4b
PZ
4843 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
4844 "corrupted preempt_count: %s/%d/0x%x\n",
4845 current->comm, current->pid, preempt_count()))
4846 preempt_count_set(FORK_PREEMPT_COUNT);
609ca066 4847
1da177e4
LT
4848 rq->prev_mm = NULL;
4849
4850 /*
4851 * A task struct has one reference for the use as "current".
c394cc9f 4852 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
4853 * schedule one last time. The schedule call will never return, and
4854 * the scheduled task must drop that reference.
95913d97
PZ
4855 *
4856 * We must observe prev->state before clearing prev->on_cpu (in
31cb1bc0 4857 * finish_task), otherwise a concurrent wakeup can get prev
95913d97
PZ
4858 * running on another CPU and we could rave with its RUNNING -> DEAD
4859 * transition, resulting in a double drop.
1da177e4 4860 */
2f064a59 4861 prev_state = READ_ONCE(prev->__state);
bf9fae9f 4862 vtime_task_switch(prev);
a8d757ef 4863 perf_event_task_sched_in(prev, current);
31cb1bc0 4864 finish_task(prev);
0fdcccfa 4865 tick_nohz_task_switch();
31cb1bc0 4866 finish_lock_switch(rq);
01f23e16 4867 finish_arch_post_lock_switch();
0ed557aa 4868 kcov_finish_switch(current);
5fbda3ec
TG
4869 /*
4870 * kmap_local_sched_out() is invoked with rq::lock held and
4871 * interrupts disabled. There is no requirement for that, but the
4872 * sched out code does not have an interrupt enabled section.
4873 * Restoring the maps on sched in does not require interrupts being
4874 * disabled either.
4875 */
4876 kmap_local_sched_in();
e8fa1362 4877
e107be36 4878 fire_sched_in_preempt_notifiers(current);
306e0604 4879 /*
70216e18
MD
4880 * When switching through a kernel thread, the loop in
4881 * membarrier_{private,global}_expedited() may have observed that
4882 * kernel thread and not issued an IPI. It is therefore possible to
4883 * schedule between user->kernel->user threads without passing though
4884 * switch_mm(). Membarrier requires a barrier after storing to
4885 * rq->curr, before returning to userspace, so provide them here:
4886 *
4887 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
4888 * provided by mmdrop(),
4889 * - a sync_core for SYNC_CORE.
306e0604 4890 */
70216e18
MD
4891 if (mm) {
4892 membarrier_mm_sync_core_before_usermode(mm);
8d491de6 4893 mmdrop_sched(mm);
70216e18 4894 }
1cef1150
PZ
4895 if (unlikely(prev_state == TASK_DEAD)) {
4896 if (prev->sched_class->task_dead)
4897 prev->sched_class->task_dead(prev);
68f24b08 4898
1cef1150
PZ
4899 /* Task is done with its stack. */
4900 put_task_stack(prev);
4901
0ff7b2cf 4902 put_task_struct_rcu_user(prev);
c6fd91f0 4903 }
99e5ada9 4904
dfa50b60 4905 return rq;
1da177e4
LT
4906}
4907
4908/**
4909 * schedule_tail - first thing a freshly forked thread must call.
4910 * @prev: the thread we just switched away from.
4911 */
722a9f92 4912asmlinkage __visible void schedule_tail(struct task_struct *prev)
1da177e4
LT
4913 __releases(rq->lock)
4914{
609ca066
PZ
4915 /*
4916 * New tasks start with FORK_PREEMPT_COUNT, see there and
4917 * finish_task_switch() for details.
4918 *
4919 * finish_task_switch() will drop rq->lock() and lower preempt_count
4920 * and the preempt_enable() will end up enabling preemption (on
4921 * PREEMPT_COUNT kernels).
4922 */
4923
13c2235b 4924 finish_task_switch(prev);
1a43a14a 4925 preempt_enable();
70b97a7f 4926
1da177e4 4927 if (current->set_child_tid)
b488893a 4928 put_user(task_pid_vnr(current), current->set_child_tid);
088fe47c
EB
4929
4930 calculate_sigpending();
1da177e4
LT
4931}
4932
4933/*
dfa50b60 4934 * context_switch - switch to the new MM and the new thread's register state.
1da177e4 4935 */
04936948 4936static __always_inline struct rq *
70b97a7f 4937context_switch(struct rq *rq, struct task_struct *prev,
d8ac8971 4938 struct task_struct *next, struct rq_flags *rf)
1da177e4 4939{
e107be36 4940 prepare_task_switch(rq, prev, next);
fe4b04fa 4941
9226d125
ZA
4942 /*
4943 * For paravirt, this is coupled with an exit in switch_to to
4944 * combine the page table reload and the switch backend into
4945 * one hypercall.
4946 */
224101ed 4947 arch_start_context_switch(prev);
9226d125 4948
306e0604 4949 /*
139d025c
PZ
4950 * kernel -> kernel lazy + transfer active
4951 * user -> kernel lazy + mmgrab() active
4952 *
4953 * kernel -> user switch + mmdrop() active
4954 * user -> user switch
306e0604 4955 */
139d025c
PZ
4956 if (!next->mm) { // to kernel
4957 enter_lazy_tlb(prev->active_mm, next);
4958
4959 next->active_mm = prev->active_mm;
4960 if (prev->mm) // from user
4961 mmgrab(prev->active_mm);
4962 else
4963 prev->active_mm = NULL;
4964 } else { // to user
227a4aad 4965 membarrier_switch_mm(rq, prev->active_mm, next->mm);
139d025c
PZ
4966 /*
4967 * sys_membarrier() requires an smp_mb() between setting
227a4aad 4968 * rq->curr / membarrier_switch_mm() and returning to userspace.
139d025c
PZ
4969 *
4970 * The below provides this either through switch_mm(), or in
4971 * case 'prev->active_mm == next->mm' through
4972 * finish_task_switch()'s mmdrop().
4973 */
139d025c 4974 switch_mm_irqs_off(prev->active_mm, next->mm, next);
1da177e4 4975
139d025c
PZ
4976 if (!prev->mm) { // from kernel
4977 /* will mmdrop() in finish_task_switch(). */
4978 rq->prev_mm = prev->active_mm;
4979 prev->active_mm = NULL;
4980 }
1da177e4 4981 }
92509b73 4982
cb42c9a3 4983 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
92509b73 4984
269d5992 4985 prepare_lock_switch(rq, next, rf);
1da177e4
LT
4986
4987 /* Here we just switch the register state and the stack. */
4988 switch_to(prev, next, prev);
dd41f596 4989 barrier();
dfa50b60
ON
4990
4991 return finish_task_switch(prev);
1da177e4
LT
4992}
4993
4994/*
1c3e8264 4995 * nr_running and nr_context_switches:
1da177e4
LT
4996 *
4997 * externally visible scheduler statistics: current number of runnable
1c3e8264 4998 * threads, total number of context switches performed since bootup.
1da177e4 4999 */
01aee8fd 5000unsigned int nr_running(void)
1da177e4 5001{
01aee8fd 5002 unsigned int i, sum = 0;
1da177e4
LT
5003
5004 for_each_online_cpu(i)
5005 sum += cpu_rq(i)->nr_running;
5006
5007 return sum;
f711f609 5008}
1da177e4 5009
2ee507c4 5010/*
d1ccc66d 5011 * Check if only the current task is running on the CPU.
00cc1633
DD
5012 *
5013 * Caution: this function does not check that the caller has disabled
5014 * preemption, thus the result might have a time-of-check-to-time-of-use
5015 * race. The caller is responsible to use it correctly, for example:
5016 *
dfcb245e 5017 * - from a non-preemptible section (of course)
00cc1633
DD
5018 *
5019 * - from a thread that is bound to a single CPU
5020 *
5021 * - in a loop with very short iterations (e.g. a polling loop)
2ee507c4
TC
5022 */
5023bool single_task_running(void)
5024{
00cc1633 5025 return raw_rq()->nr_running == 1;
2ee507c4
TC
5026}
5027EXPORT_SYMBOL(single_task_running);
5028
1da177e4 5029unsigned long long nr_context_switches(void)
46cb4b7c 5030{
cc94abfc
SR
5031 int i;
5032 unsigned long long sum = 0;
46cb4b7c 5033
0a945022 5034 for_each_possible_cpu(i)
1da177e4 5035 sum += cpu_rq(i)->nr_switches;
46cb4b7c 5036
1da177e4
LT
5037 return sum;
5038}
483b4ee6 5039
145d952a
DL
5040/*
5041 * Consumers of these two interfaces, like for example the cpuidle menu
5042 * governor, are using nonsensical data. Preferring shallow idle state selection
5043 * for a CPU that has IO-wait which might not even end up running the task when
5044 * it does become runnable.
5045 */
5046
8fc2858e 5047unsigned int nr_iowait_cpu(int cpu)
145d952a
DL
5048{
5049 return atomic_read(&cpu_rq(cpu)->nr_iowait);
5050}
5051
e33a9bba 5052/*
b19a888c 5053 * IO-wait accounting, and how it's mostly bollocks (on SMP).
e33a9bba
TH
5054 *
5055 * The idea behind IO-wait account is to account the idle time that we could
5056 * have spend running if it were not for IO. That is, if we were to improve the
5057 * storage performance, we'd have a proportional reduction in IO-wait time.
5058 *
5059 * This all works nicely on UP, where, when a task blocks on IO, we account
5060 * idle time as IO-wait, because if the storage were faster, it could've been
5061 * running and we'd not be idle.
5062 *
5063 * This has been extended to SMP, by doing the same for each CPU. This however
5064 * is broken.
5065 *
5066 * Imagine for instance the case where two tasks block on one CPU, only the one
5067 * CPU will have IO-wait accounted, while the other has regular idle. Even
5068 * though, if the storage were faster, both could've ran at the same time,
5069 * utilising both CPUs.
5070 *
5071 * This means, that when looking globally, the current IO-wait accounting on
5072 * SMP is a lower bound, by reason of under accounting.
5073 *
5074 * Worse, since the numbers are provided per CPU, they are sometimes
5075 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
5076 * associated with any one particular CPU, it can wake to another CPU than it
5077 * blocked on. This means the per CPU IO-wait number is meaningless.
5078 *
5079 * Task CPU affinities can make all that even more 'interesting'.
5080 */
5081
97455168 5082unsigned int nr_iowait(void)
1da177e4 5083{
97455168 5084 unsigned int i, sum = 0;
483b4ee6 5085
0a945022 5086 for_each_possible_cpu(i)
145d952a 5087 sum += nr_iowait_cpu(i);
46cb4b7c 5088
1da177e4
LT
5089 return sum;
5090}
483b4ee6 5091
dd41f596 5092#ifdef CONFIG_SMP
8a0be9ef 5093
46cb4b7c 5094/*
38022906
PZ
5095 * sched_exec - execve() is a valuable balancing opportunity, because at
5096 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 5097 */
38022906 5098void sched_exec(void)
46cb4b7c 5099{
38022906 5100 struct task_struct *p = current;
1da177e4 5101 unsigned long flags;
0017d735 5102 int dest_cpu;
46cb4b7c 5103
8f42ced9 5104 raw_spin_lock_irqsave(&p->pi_lock, flags);
3aef1551 5105 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
0017d735
PZ
5106 if (dest_cpu == smp_processor_id())
5107 goto unlock;
38022906 5108
8f42ced9 5109 if (likely(cpu_active(dest_cpu))) {
969c7921 5110 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 5111
8f42ced9
PZ
5112 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5113 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
5114 return;
5115 }
0017d735 5116unlock:
8f42ced9 5117 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 5118}
dd41f596 5119
1da177e4
LT
5120#endif
5121
1da177e4 5122DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 5123DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
5124
5125EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 5126EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4 5127
6075620b
GG
5128/*
5129 * The function fair_sched_class.update_curr accesses the struct curr
5130 * and its field curr->exec_start; when called from task_sched_runtime(),
5131 * we observe a high rate of cache misses in practice.
5132 * Prefetching this data results in improved performance.
5133 */
5134static inline void prefetch_curr_exec_start(struct task_struct *p)
5135{
5136#ifdef CONFIG_FAIR_GROUP_SCHED
5137 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
5138#else
5139 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
5140#endif
5141 prefetch(curr);
5142 prefetch(&curr->exec_start);
5143}
5144
c5f8d995
HS
5145/*
5146 * Return accounted runtime for the task.
5147 * In case the task is currently running, return the runtime plus current's
5148 * pending runtime that have not been accounted yet.
5149 */
5150unsigned long long task_sched_runtime(struct task_struct *p)
5151{
eb580751 5152 struct rq_flags rf;
c5f8d995 5153 struct rq *rq;
6e998916 5154 u64 ns;
c5f8d995 5155
911b2898
PZ
5156#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
5157 /*
97fb7a0a 5158 * 64-bit doesn't need locks to atomically read a 64-bit value.
911b2898
PZ
5159 * So we have a optimization chance when the task's delta_exec is 0.
5160 * Reading ->on_cpu is racy, but this is ok.
5161 *
d1ccc66d
IM
5162 * If we race with it leaving CPU, we'll take a lock. So we're correct.
5163 * If we race with it entering CPU, unaccounted time is 0. This is
911b2898 5164 * indistinguishable from the read occurring a few cycles earlier.
4036ac15
MG
5165 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
5166 * been accounted, so we're correct here as well.
911b2898 5167 */
da0c1e65 5168 if (!p->on_cpu || !task_on_rq_queued(p))
911b2898
PZ
5169 return p->se.sum_exec_runtime;
5170#endif
5171
eb580751 5172 rq = task_rq_lock(p, &rf);
6e998916
SG
5173 /*
5174 * Must be ->curr _and_ ->on_rq. If dequeued, we would
5175 * project cycles that may never be accounted to this
5176 * thread, breaking clock_gettime().
5177 */
5178 if (task_current(rq, p) && task_on_rq_queued(p)) {
6075620b 5179 prefetch_curr_exec_start(p);
6e998916
SG
5180 update_rq_clock(rq);
5181 p->sched_class->update_curr(rq);
5182 }
5183 ns = p->se.sum_exec_runtime;
eb580751 5184 task_rq_unlock(rq, p, &rf);
c5f8d995
HS
5185
5186 return ns;
5187}
48f24c4d 5188
c006fac5
PT
5189#ifdef CONFIG_SCHED_DEBUG
5190static u64 cpu_resched_latency(struct rq *rq)
5191{
5192 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
5193 u64 resched_latency, now = rq_clock(rq);
5194 static bool warned_once;
5195
5196 if (sysctl_resched_latency_warn_once && warned_once)
5197 return 0;
5198
5199 if (!need_resched() || !latency_warn_ms)
5200 return 0;
5201
5202 if (system_state == SYSTEM_BOOTING)
5203 return 0;
5204
5205 if (!rq->last_seen_need_resched_ns) {
5206 rq->last_seen_need_resched_ns = now;
5207 rq->ticks_without_resched = 0;
5208 return 0;
5209 }
5210
5211 rq->ticks_without_resched++;
5212 resched_latency = now - rq->last_seen_need_resched_ns;
5213 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
5214 return 0;
5215
5216 warned_once = true;
5217
5218 return resched_latency;
5219}
5220
5221static int __init setup_resched_latency_warn_ms(char *str)
5222{
5223 long val;
5224
5225 if ((kstrtol(str, 0, &val))) {
5226 pr_warn("Unable to set resched_latency_warn_ms\n");
5227 return 1;
5228 }
5229
5230 sysctl_resched_latency_warn_ms = val;
5231 return 1;
5232}
5233__setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
5234#else
5235static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
5236#endif /* CONFIG_SCHED_DEBUG */
5237
7835b98b
CL
5238/*
5239 * This function gets called by the timer code, with HZ frequency.
5240 * We call it with interrupts disabled.
7835b98b
CL
5241 */
5242void scheduler_tick(void)
5243{
7835b98b
CL
5244 int cpu = smp_processor_id();
5245 struct rq *rq = cpu_rq(cpu);
dd41f596 5246 struct task_struct *curr = rq->curr;
8a8c69c3 5247 struct rq_flags rf;
b4eccf5f 5248 unsigned long thermal_pressure;
c006fac5 5249 u64 resched_latency;
3e51f33f 5250
1567c3e3 5251 arch_scale_freq_tick();
3e51f33f 5252 sched_clock_tick();
dd41f596 5253
8a8c69c3
PZ
5254 rq_lock(rq, &rf);
5255
3e51f33f 5256 update_rq_clock(rq);
b4eccf5f 5257 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
05289b90 5258 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
fa85ae24 5259 curr->sched_class->task_tick(rq, curr, 0);
c006fac5
PT
5260 if (sched_feat(LATENCY_WARN))
5261 resched_latency = cpu_resched_latency(rq);
3289bdb4 5262 calc_global_load_tick(rq);
4feee7d1 5263 sched_core_tick(rq);
8a8c69c3
PZ
5264
5265 rq_unlock(rq, &rf);
7835b98b 5266
c006fac5
PT
5267 if (sched_feat(LATENCY_WARN) && resched_latency)
5268 resched_latency_warn(cpu, resched_latency);
5269
e9d2b064 5270 perf_event_task_tick();
e220d2dc 5271
e418e1c2 5272#ifdef CONFIG_SMP
6eb57e0d 5273 rq->idle_balance = idle_cpu(cpu);
7caff66f 5274 trigger_load_balance(rq);
e418e1c2 5275#endif
1da177e4
LT
5276}
5277
265f22a9 5278#ifdef CONFIG_NO_HZ_FULL
d84b3131
FW
5279
5280struct tick_work {
5281 int cpu;
b55bd585 5282 atomic_t state;
d84b3131
FW
5283 struct delayed_work work;
5284};
b55bd585
PM
5285/* Values for ->state, see diagram below. */
5286#define TICK_SCHED_REMOTE_OFFLINE 0
5287#define TICK_SCHED_REMOTE_OFFLINING 1
5288#define TICK_SCHED_REMOTE_RUNNING 2
5289
5290/*
5291 * State diagram for ->state:
5292 *
5293 *
5294 * TICK_SCHED_REMOTE_OFFLINE
5295 * | ^
5296 * | |
5297 * | | sched_tick_remote()
5298 * | |
5299 * | |
5300 * +--TICK_SCHED_REMOTE_OFFLINING
5301 * | ^
5302 * | |
5303 * sched_tick_start() | | sched_tick_stop()
5304 * | |
5305 * V |
5306 * TICK_SCHED_REMOTE_RUNNING
5307 *
5308 *
5309 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5310 * and sched_tick_start() are happy to leave the state in RUNNING.
5311 */
d84b3131
FW
5312
5313static struct tick_work __percpu *tick_work_cpu;
5314
5315static void sched_tick_remote(struct work_struct *work)
5316{
5317 struct delayed_work *dwork = to_delayed_work(work);
5318 struct tick_work *twork = container_of(dwork, struct tick_work, work);
5319 int cpu = twork->cpu;
5320 struct rq *rq = cpu_rq(cpu);
d9c0ffca 5321 struct task_struct *curr;
d84b3131 5322 struct rq_flags rf;
d9c0ffca 5323 u64 delta;
b55bd585 5324 int os;
d84b3131
FW
5325
5326 /*
5327 * Handle the tick only if it appears the remote CPU is running in full
5328 * dynticks mode. The check is racy by nature, but missing a tick or
5329 * having one too much is no big deal because the scheduler tick updates
5330 * statistics and checks timeslices in a time-independent way, regardless
5331 * of when exactly it is running.
5332 */
488603b8 5333 if (!tick_nohz_tick_stopped_cpu(cpu))
d9c0ffca 5334 goto out_requeue;
d84b3131 5335
d9c0ffca
FW
5336 rq_lock_irq(rq, &rf);
5337 curr = rq->curr;
488603b8 5338 if (cpu_is_offline(cpu))
d9c0ffca 5339 goto out_unlock;
d84b3131 5340
d9c0ffca 5341 update_rq_clock(rq);
d9c0ffca 5342
488603b8
SW
5343 if (!is_idle_task(curr)) {
5344 /*
5345 * Make sure the next tick runs within a reasonable
5346 * amount of time.
5347 */
5348 delta = rq_clock_task(rq) - curr->se.exec_start;
5349 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5350 }
d9c0ffca
FW
5351 curr->sched_class->task_tick(rq, curr, 0);
5352
ebc0f83c 5353 calc_load_nohz_remote(rq);
d9c0ffca
FW
5354out_unlock:
5355 rq_unlock_irq(rq, &rf);
d9c0ffca 5356out_requeue:
ebc0f83c 5357
d84b3131
FW
5358 /*
5359 * Run the remote tick once per second (1Hz). This arbitrary
5360 * frequency is large enough to avoid overload but short enough
b55bd585
PM
5361 * to keep scheduler internal stats reasonably up to date. But
5362 * first update state to reflect hotplug activity if required.
d84b3131 5363 */
b55bd585
PM
5364 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5365 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5366 if (os == TICK_SCHED_REMOTE_RUNNING)
5367 queue_delayed_work(system_unbound_wq, dwork, HZ);
d84b3131
FW
5368}
5369
5370static void sched_tick_start(int cpu)
5371{
b55bd585 5372 int os;
d84b3131
FW
5373 struct tick_work *twork;
5374
04d4e665 5375 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
d84b3131
FW
5376 return;
5377
5378 WARN_ON_ONCE(!tick_work_cpu);
5379
5380 twork = per_cpu_ptr(tick_work_cpu, cpu);
b55bd585
PM
5381 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5382 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5383 if (os == TICK_SCHED_REMOTE_OFFLINE) {
5384 twork->cpu = cpu;
5385 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5386 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5387 }
d84b3131
FW
5388}
5389
5390#ifdef CONFIG_HOTPLUG_CPU
5391static void sched_tick_stop(int cpu)
5392{
5393 struct tick_work *twork;
b55bd585 5394 int os;
d84b3131 5395
04d4e665 5396 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
d84b3131
FW
5397 return;
5398
5399 WARN_ON_ONCE(!tick_work_cpu);
5400
5401 twork = per_cpu_ptr(tick_work_cpu, cpu);
b55bd585
PM
5402 /* There cannot be competing actions, but don't rely on stop-machine. */
5403 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5404 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5405 /* Don't cancel, as this would mess up the state machine. */
d84b3131
FW
5406}
5407#endif /* CONFIG_HOTPLUG_CPU */
5408
5409int __init sched_tick_offload_init(void)
5410{
5411 tick_work_cpu = alloc_percpu(struct tick_work);
5412 BUG_ON(!tick_work_cpu);
d84b3131
FW
5413 return 0;
5414}
5415
5416#else /* !CONFIG_NO_HZ_FULL */
5417static inline void sched_tick_start(int cpu) { }
5418static inline void sched_tick_stop(int cpu) { }
265f22a9 5419#endif
1da177e4 5420
c1a280b6 5421#if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
c3bc8fd6 5422 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
47252cfb
SR
5423/*
5424 * If the value passed in is equal to the current preempt count
5425 * then we just disabled preemption. Start timing the latency.
5426 */
5427static inline void preempt_latency_start(int val)
5428{
5429 if (preempt_count() == val) {
5430 unsigned long ip = get_lock_parent_ip();
5431#ifdef CONFIG_DEBUG_PREEMPT
5432 current->preempt_disable_ip = ip;
5433#endif
5434 trace_preempt_off(CALLER_ADDR0, ip);
5435 }
5436}
7e49fcce 5437
edafe3a5 5438void preempt_count_add(int val)
1da177e4 5439{
6cd8a4bb 5440#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5441 /*
5442 * Underflow?
5443 */
9a11b49a
IM
5444 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5445 return;
6cd8a4bb 5446#endif
bdb43806 5447 __preempt_count_add(val);
6cd8a4bb 5448#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5449 /*
5450 * Spinlock count overflowing soon?
5451 */
33859f7f
MOS
5452 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5453 PREEMPT_MASK - 10);
6cd8a4bb 5454#endif
47252cfb 5455 preempt_latency_start(val);
1da177e4 5456}
bdb43806 5457EXPORT_SYMBOL(preempt_count_add);
edafe3a5 5458NOKPROBE_SYMBOL(preempt_count_add);
1da177e4 5459
47252cfb
SR
5460/*
5461 * If the value passed in equals to the current preempt count
5462 * then we just enabled preemption. Stop timing the latency.
5463 */
5464static inline void preempt_latency_stop(int val)
5465{
5466 if (preempt_count() == val)
5467 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
5468}
5469
edafe3a5 5470void preempt_count_sub(int val)
1da177e4 5471{
6cd8a4bb 5472#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5473 /*
5474 * Underflow?
5475 */
01e3eb82 5476 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 5477 return;
1da177e4
LT
5478 /*
5479 * Is the spinlock portion underflowing?
5480 */
9a11b49a
IM
5481 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5482 !(preempt_count() & PREEMPT_MASK)))
5483 return;
6cd8a4bb 5484#endif
9a11b49a 5485
47252cfb 5486 preempt_latency_stop(val);
bdb43806 5487 __preempt_count_sub(val);
1da177e4 5488}
bdb43806 5489EXPORT_SYMBOL(preempt_count_sub);
edafe3a5 5490NOKPROBE_SYMBOL(preempt_count_sub);
1da177e4 5491
47252cfb
SR
5492#else
5493static inline void preempt_latency_start(int val) { }
5494static inline void preempt_latency_stop(int val) { }
1da177e4
LT
5495#endif
5496
59ddbcb2
IM
5497static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
5498{
5499#ifdef CONFIG_DEBUG_PREEMPT
5500 return p->preempt_disable_ip;
5501#else
5502 return 0;
5503#endif
5504}
5505
1da177e4 5506/*
dd41f596 5507 * Print scheduling while atomic bug:
1da177e4 5508 */
dd41f596 5509static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 5510{
d1c6d149
VN
5511 /* Save this before calling printk(), since that will clobber it */
5512 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
5513
664dfa65
DJ
5514 if (oops_in_progress)
5515 return;
5516
3df0fc5b
PZ
5517 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5518 prev->comm, prev->pid, preempt_count());
838225b4 5519
dd41f596 5520 debug_show_held_locks(prev);
e21f5b15 5521 print_modules();
dd41f596
IM
5522 if (irqs_disabled())
5523 print_irqtrace_events(prev);
d1c6d149
VN
5524 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
5525 && in_atomic_preempt_off()) {
8f47b187 5526 pr_err("Preemption disabled at:");
2062a4e8 5527 print_ip_sym(KERN_ERR, preempt_disable_ip);
8f47b187 5528 }
748c7201
DBO
5529 if (panic_on_warn)
5530 panic("scheduling while atomic\n");
5531
6135fc1e 5532 dump_stack();
373d4d09 5533 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
dd41f596 5534}
1da177e4 5535
dd41f596
IM
5536/*
5537 * Various schedule()-time debugging checks and statistics:
5538 */
312364f3 5539static inline void schedule_debug(struct task_struct *prev, bool preempt)
dd41f596 5540{
0d9e2632 5541#ifdef CONFIG_SCHED_STACK_END_CHECK
29d64551
JH
5542 if (task_stack_end_corrupted(prev))
5543 panic("corrupted stack end detected inside scheduler\n");
88485be5
WD
5544
5545 if (task_scs_end_corrupted(prev))
5546 panic("corrupted shadow stack detected inside scheduler\n");
0d9e2632 5547#endif
b99def8b 5548
312364f3 5549#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
2f064a59 5550 if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
312364f3
DV
5551 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5552 prev->comm, prev->pid, prev->non_block_count);
5553 dump_stack();
5554 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5555 }
5556#endif
5557
1dc0fffc 5558 if (unlikely(in_atomic_preempt_off())) {
dd41f596 5559 __schedule_bug(prev);
1dc0fffc
PZ
5560 preempt_count_set(PREEMPT_DISABLED);
5561 }
b3fbab05 5562 rcu_sleep_check();
9f68b5b7 5563 SCHED_WARN_ON(ct_state() == CONTEXT_USER);
dd41f596 5564
1da177e4
LT
5565 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5566
ae92882e 5567 schedstat_inc(this_rq()->sched_count);
dd41f596
IM
5568}
5569
457d1f46
CY
5570static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
5571 struct rq_flags *rf)
5572{
5573#ifdef CONFIG_SMP
5574 const struct sched_class *class;
5575 /*
5576 * We must do the balancing pass before put_prev_task(), such
5577 * that when we release the rq->lock the task is in the same
5578 * state as before we took rq->lock.
5579 *
5580 * We can terminate the balance pass as soon as we know there is
5581 * a runnable task of @class priority or higher.
5582 */
5583 for_class_range(class, prev->sched_class, &idle_sched_class) {
5584 if (class->balance(rq, prev, rf))
5585 break;
5586 }
5587#endif
5588
5589 put_prev_task(rq, prev);
5590}
5591
dd41f596
IM
5592/*
5593 * Pick up the highest-prio task:
5594 */
5595static inline struct task_struct *
539f6512 5596__pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
dd41f596 5597{
49ee5768 5598 const struct sched_class *class;
dd41f596 5599 struct task_struct *p;
1da177e4
LT
5600
5601 /*
0ba87bb2
PZ
5602 * Optimization: we know that if all tasks are in the fair class we can
5603 * call that function directly, but only if the @prev task wasn't of a
b19a888c 5604 * higher scheduling class, because otherwise those lose the
0ba87bb2 5605 * opportunity to pull in more work from other CPUs.
1da177e4 5606 */
aa93cd53 5607 if (likely(prev->sched_class <= &fair_sched_class &&
0ba87bb2
PZ
5608 rq->nr_running == rq->cfs.h_nr_running)) {
5609
5d7d6056 5610 p = pick_next_task_fair(rq, prev, rf);
6ccdc84b 5611 if (unlikely(p == RETRY_TASK))
67692435 5612 goto restart;
6ccdc84b 5613
1699949d 5614 /* Assume the next prioritized class is idle_sched_class */
5d7d6056 5615 if (!p) {
f488e105 5616 put_prev_task(rq, prev);
98c2f700 5617 p = pick_next_task_idle(rq);
f488e105 5618 }
6ccdc84b
PZ
5619
5620 return p;
1da177e4
LT
5621 }
5622
67692435 5623restart:
457d1f46 5624 put_prev_task_balance(rq, prev, rf);
67692435 5625
34f971f6 5626 for_each_class(class) {
98c2f700 5627 p = class->pick_next_task(rq);
67692435 5628 if (p)
dd41f596 5629 return p;
dd41f596 5630 }
34f971f6 5631
bc9ffef3 5632 BUG(); /* The idle class should always have a runnable task. */
dd41f596 5633}
1da177e4 5634
9edeaea1 5635#ifdef CONFIG_SCHED_CORE
539f6512
PZ
5636static inline bool is_task_rq_idle(struct task_struct *t)
5637{
5638 return (task_rq(t)->idle == t);
5639}
5640
5641static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
5642{
5643 return is_task_rq_idle(a) || (a->core_cookie == cookie);
5644}
5645
5646static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
5647{
5648 if (is_task_rq_idle(a) || is_task_rq_idle(b))
5649 return true;
5650
5651 return a->core_cookie == b->core_cookie;
5652}
5653
bc9ffef3 5654static inline struct task_struct *pick_task(struct rq *rq)
539f6512 5655{
bc9ffef3
PZ
5656 const struct sched_class *class;
5657 struct task_struct *p;
539f6512 5658
bc9ffef3
PZ
5659 for_each_class(class) {
5660 p = class->pick_task(rq);
5661 if (p)
5662 return p;
539f6512
PZ
5663 }
5664
bc9ffef3 5665 BUG(); /* The idle class should always have a runnable task. */
539f6512
PZ
5666}
5667
c6047c2e
JFG
5668extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
5669
539f6512
PZ
5670static struct task_struct *
5671pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5672{
bc9ffef3 5673 struct task_struct *next, *p, *max = NULL;
539f6512 5674 const struct cpumask *smt_mask;
c6047c2e 5675 bool fi_before = false;
4feee7d1 5676 bool core_clock_updated = (rq == rq->core);
bc9ffef3
PZ
5677 unsigned long cookie;
5678 int i, cpu, occ = 0;
5679 struct rq *rq_i;
539f6512 5680 bool need_sync;
539f6512
PZ
5681
5682 if (!sched_core_enabled(rq))
5683 return __pick_next_task(rq, prev, rf);
5684
5685 cpu = cpu_of(rq);
5686
5687 /* Stopper task is switching into idle, no need core-wide selection. */
5688 if (cpu_is_offline(cpu)) {
5689 /*
5690 * Reset core_pick so that we don't enter the fastpath when
5691 * coming online. core_pick would already be migrated to
5692 * another cpu during offline.
5693 */
5694 rq->core_pick = NULL;
5695 return __pick_next_task(rq, prev, rf);
5696 }
5697
5698 /*
5699 * If there were no {en,de}queues since we picked (IOW, the task
5700 * pointers are all still valid), and we haven't scheduled the last
5701 * pick yet, do so now.
5702 *
5703 * rq->core_pick can be NULL if no selection was made for a CPU because
5704 * it was either offline or went offline during a sibling's core-wide
5705 * selection. In this case, do a core-wide selection.
5706 */
5707 if (rq->core->core_pick_seq == rq->core->core_task_seq &&
5708 rq->core->core_pick_seq != rq->core_sched_seq &&
5709 rq->core_pick) {
5710 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
5711
5712 next = rq->core_pick;
5713 if (next != prev) {
5714 put_prev_task(rq, prev);
5715 set_next_task(rq, next);
5716 }
5717
5718 rq->core_pick = NULL;
5719 return next;
5720 }
5721
5722 put_prev_task_balance(rq, prev, rf);
5723
5724 smt_mask = cpu_smt_mask(cpu);
7afbba11
JFG
5725 need_sync = !!rq->core->core_cookie;
5726
5727 /* reset state */
5728 rq->core->core_cookie = 0UL;
4feee7d1
JD
5729 if (rq->core->core_forceidle_count) {
5730 if (!core_clock_updated) {
5731 update_rq_clock(rq->core);
5732 core_clock_updated = true;
5733 }
5734 sched_core_account_forceidle(rq);
5735 /* reset after accounting force idle */
5736 rq->core->core_forceidle_start = 0;
5737 rq->core->core_forceidle_count = 0;
5738 rq->core->core_forceidle_occupation = 0;
7afbba11
JFG
5739 need_sync = true;
5740 fi_before = true;
7afbba11 5741 }
539f6512
PZ
5742
5743 /*
5744 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
5745 *
5746 * @task_seq guards the task state ({en,de}queues)
5747 * @pick_seq is the @task_seq we did a selection on
5748 * @sched_seq is the @pick_seq we scheduled
5749 *
5750 * However, preemptions can cause multiple picks on the same task set.
5751 * 'Fix' this by also increasing @task_seq for every pick.
5752 */
5753 rq->core->core_task_seq++;
539f6512 5754
7afbba11
JFG
5755 /*
5756 * Optimize for common case where this CPU has no cookies
5757 * and there are no cookied tasks running on siblings.
5758 */
5759 if (!need_sync) {
bc9ffef3 5760 next = pick_task(rq);
7afbba11
JFG
5761 if (!next->core_cookie) {
5762 rq->core_pick = NULL;
c6047c2e
JFG
5763 /*
5764 * For robustness, update the min_vruntime_fi for
5765 * unconstrained picks as well.
5766 */
5767 WARN_ON_ONCE(fi_before);
5768 task_vruntime_update(rq, next, false);
7afbba11
JFG
5769 goto done;
5770 }
8039e96f 5771 }
7afbba11 5772
bc9ffef3
PZ
5773 /*
5774 * For each thread: do the regular task pick and find the max prio task
5775 * amongst them.
5776 *
5777 * Tie-break prio towards the current CPU
5778 */
5779 for_each_cpu_wrap(i, smt_mask, cpu) {
5780 rq_i = cpu_rq(i);
539f6512 5781
4feee7d1
JD
5782 /*
5783 * Current cpu always has its clock updated on entrance to
5784 * pick_next_task(). If the current cpu is not the core,
5785 * the core may also have been updated above.
5786 */
5787 if (i != cpu && (rq_i != rq->core || !core_clock_updated))
539f6512 5788 update_rq_clock(rq_i);
bc9ffef3
PZ
5789
5790 p = rq_i->core_pick = pick_task(rq_i);
5791 if (!max || prio_less(max, p, fi_before))
5792 max = p;
539f6512
PZ
5793 }
5794
bc9ffef3
PZ
5795 cookie = rq->core->core_cookie = max->core_cookie;
5796
539f6512 5797 /*
bc9ffef3
PZ
5798 * For each thread: try and find a runnable task that matches @max or
5799 * force idle.
539f6512 5800 */
bc9ffef3
PZ
5801 for_each_cpu(i, smt_mask) {
5802 rq_i = cpu_rq(i);
5803 p = rq_i->core_pick;
539f6512 5804
bc9ffef3
PZ
5805 if (!cookie_equals(p, cookie)) {
5806 p = NULL;
5807 if (cookie)
5808 p = sched_core_find(rq_i, cookie);
7afbba11 5809 if (!p)
bc9ffef3
PZ
5810 p = idle_sched_class.pick_task(rq_i);
5811 }
539f6512 5812
bc9ffef3 5813 rq_i->core_pick = p;
d2dfa17b 5814
bc9ffef3
PZ
5815 if (p == rq_i->idle) {
5816 if (rq_i->nr_running) {
4feee7d1 5817 rq->core->core_forceidle_count++;
c6047c2e
JFG
5818 if (!fi_before)
5819 rq->core->core_forceidle_seq++;
5820 }
bc9ffef3
PZ
5821 } else {
5822 occ++;
539f6512 5823 }
539f6512
PZ
5824 }
5825
4feee7d1
JD
5826 if (schedstat_enabled() && rq->core->core_forceidle_count) {
5827 if (cookie)
5828 rq->core->core_forceidle_start = rq_clock(rq->core);
5829 rq->core->core_forceidle_occupation = occ;
5830 }
5831
539f6512
PZ
5832 rq->core->core_pick_seq = rq->core->core_task_seq;
5833 next = rq->core_pick;
5834 rq->core_sched_seq = rq->core->core_pick_seq;
5835
5836 /* Something should have been selected for current CPU */
5837 WARN_ON_ONCE(!next);
5838
5839 /*
5840 * Reschedule siblings
5841 *
5842 * NOTE: L1TF -- at this point we're no longer running the old task and
5843 * sending an IPI (below) ensures the sibling will no longer be running
5844 * their task. This ensures there is no inter-sibling overlap between
5845 * non-matching user state.
5846 */
5847 for_each_cpu(i, smt_mask) {
bc9ffef3 5848 rq_i = cpu_rq(i);
539f6512
PZ
5849
5850 /*
5851 * An online sibling might have gone offline before a task
5852 * could be picked for it, or it might be offline but later
5853 * happen to come online, but its too late and nothing was
5854 * picked for it. That's Ok - it will pick tasks for itself,
5855 * so ignore it.
5856 */
5857 if (!rq_i->core_pick)
5858 continue;
5859
c6047c2e
JFG
5860 /*
5861 * Update for new !FI->FI transitions, or if continuing to be in !FI:
5862 * fi_before fi update?
5863 * 0 0 1
5864 * 0 1 1
5865 * 1 0 1
5866 * 1 1 0
5867 */
4feee7d1
JD
5868 if (!(fi_before && rq->core->core_forceidle_count))
5869 task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
539f6512 5870
d2dfa17b
PZ
5871 rq_i->core_pick->core_occupation = occ;
5872
539f6512
PZ
5873 if (i == cpu) {
5874 rq_i->core_pick = NULL;
5875 continue;
5876 }
5877
5878 /* Did we break L1TF mitigation requirements? */
5879 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
5880
5881 if (rq_i->curr == rq_i->core_pick) {
5882 rq_i->core_pick = NULL;
5883 continue;
5884 }
5885
5886 resched_curr(rq_i);
5887 }
5888
5889done:
5890 set_next_task(rq, next);
5891 return next;
5892}
9edeaea1 5893
d2dfa17b
PZ
5894static bool try_steal_cookie(int this, int that)
5895{
5896 struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
5897 struct task_struct *p;
5898 unsigned long cookie;
5899 bool success = false;
5900
5901 local_irq_disable();
5902 double_rq_lock(dst, src);
5903
5904 cookie = dst->core->core_cookie;
5905 if (!cookie)
5906 goto unlock;
5907
5908 if (dst->curr != dst->idle)
5909 goto unlock;
5910
5911 p = sched_core_find(src, cookie);
5912 if (p == src->idle)
5913 goto unlock;
5914
5915 do {
5916 if (p == src->core_pick || p == src->curr)
5917 goto next;
5918
5919 if (!cpumask_test_cpu(this, &p->cpus_mask))
5920 goto next;
5921
5922 if (p->core_occupation > dst->idle->core_occupation)
5923 goto next;
5924
d2dfa17b
PZ
5925 deactivate_task(src, p, 0);
5926 set_task_cpu(p, this);
5927 activate_task(dst, p, 0);
d2dfa17b
PZ
5928
5929 resched_curr(dst);
5930
5931 success = true;
5932 break;
5933
5934next:
5935 p = sched_core_next(p, cookie);
5936 } while (p);
5937
5938unlock:
5939 double_rq_unlock(dst, src);
5940 local_irq_enable();
5941
5942 return success;
5943}
5944
5945static bool steal_cookie_task(int cpu, struct sched_domain *sd)
5946{
5947 int i;
5948
5949 for_each_cpu_wrap(i, sched_domain_span(sd), cpu) {
5950 if (i == cpu)
5951 continue;
5952
5953 if (need_resched())
5954 break;
5955
5956 if (try_steal_cookie(cpu, i))
5957 return true;
5958 }
5959
5960 return false;
5961}
5962
5963static void sched_core_balance(struct rq *rq)
5964{
5965 struct sched_domain *sd;
5966 int cpu = cpu_of(rq);
5967
5968 preempt_disable();
5969 rcu_read_lock();
5970 raw_spin_rq_unlock_irq(rq);
5971 for_each_domain(cpu, sd) {
5972 if (need_resched())
5973 break;
5974
5975 if (steal_cookie_task(cpu, sd))
5976 break;
5977 }
5978 raw_spin_rq_lock_irq(rq);
5979 rcu_read_unlock();
5980 preempt_enable();
5981}
5982
5983static DEFINE_PER_CPU(struct callback_head, core_balance_head);
5984
5985void queue_core_balance(struct rq *rq)
5986{
5987 if (!sched_core_enabled(rq))
5988 return;
5989
5990 if (!rq->core->core_cookie)
5991 return;
5992
5993 if (!rq->nr_running) /* not forced idle */
5994 return;
5995
5996 queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
5997}
5998
3c474b32 5999static void sched_core_cpu_starting(unsigned int cpu)
9edeaea1
PZ
6000{
6001 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
3c474b32
PZ
6002 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6003 unsigned long flags;
6004 int t;
9edeaea1 6005
3c474b32 6006 sched_core_lock(cpu, &flags);
9edeaea1 6007
3c474b32
PZ
6008 WARN_ON_ONCE(rq->core != rq);
6009
6010 /* if we're the first, we'll be our own leader */
6011 if (cpumask_weight(smt_mask) == 1)
6012 goto unlock;
6013
6014 /* find the leader */
6015 for_each_cpu(t, smt_mask) {
6016 if (t == cpu)
6017 continue;
6018 rq = cpu_rq(t);
6019 if (rq->core == rq) {
6020 core_rq = rq;
6021 break;
9edeaea1 6022 }
3c474b32 6023 }
9edeaea1 6024
3c474b32
PZ
6025 if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
6026 goto unlock;
9edeaea1 6027
3c474b32
PZ
6028 /* install and validate core_rq */
6029 for_each_cpu(t, smt_mask) {
6030 rq = cpu_rq(t);
9edeaea1 6031
3c474b32 6032 if (t == cpu)
9edeaea1 6033 rq->core = core_rq;
3c474b32
PZ
6034
6035 WARN_ON_ONCE(rq->core != core_rq);
9edeaea1 6036 }
3c474b32
PZ
6037
6038unlock:
6039 sched_core_unlock(cpu, &flags);
9edeaea1 6040}
3c474b32
PZ
6041
6042static void sched_core_cpu_deactivate(unsigned int cpu)
6043{
6044 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6045 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6046 unsigned long flags;
6047 int t;
6048
6049 sched_core_lock(cpu, &flags);
6050
6051 /* if we're the last man standing, nothing to do */
6052 if (cpumask_weight(smt_mask) == 1) {
6053 WARN_ON_ONCE(rq->core != rq);
6054 goto unlock;
6055 }
6056
6057 /* if we're not the leader, nothing to do */
6058 if (rq->core != rq)
6059 goto unlock;
6060
6061 /* find a new leader */
6062 for_each_cpu(t, smt_mask) {
6063 if (t == cpu)
6064 continue;
6065 core_rq = cpu_rq(t);
6066 break;
6067 }
6068
6069 if (WARN_ON_ONCE(!core_rq)) /* impossible */
6070 goto unlock;
6071
6072 /* copy the shared state to the new leader */
4feee7d1
JD
6073 core_rq->core_task_seq = rq->core_task_seq;
6074 core_rq->core_pick_seq = rq->core_pick_seq;
6075 core_rq->core_cookie = rq->core_cookie;
6076 core_rq->core_forceidle_count = rq->core_forceidle_count;
6077 core_rq->core_forceidle_seq = rq->core_forceidle_seq;
6078 core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
6079
6080 /*
6081 * Accounting edge for forced idle is handled in pick_next_task().
6082 * Don't need another one here, since the hotplug thread shouldn't
6083 * have a cookie.
6084 */
6085 core_rq->core_forceidle_start = 0;
3c474b32
PZ
6086
6087 /* install new leader */
6088 for_each_cpu(t, smt_mask) {
6089 rq = cpu_rq(t);
6090 rq->core = core_rq;
6091 }
6092
6093unlock:
6094 sched_core_unlock(cpu, &flags);
6095}
6096
6097static inline void sched_core_cpu_dying(unsigned int cpu)
6098{
6099 struct rq *rq = cpu_rq(cpu);
6100
6101 if (rq->core != rq)
6102 rq->core = rq;
6103}
6104
9edeaea1
PZ
6105#else /* !CONFIG_SCHED_CORE */
6106
6107static inline void sched_core_cpu_starting(unsigned int cpu) {}
3c474b32
PZ
6108static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
6109static inline void sched_core_cpu_dying(unsigned int cpu) {}
9edeaea1 6110
539f6512
PZ
6111static struct task_struct *
6112pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6113{
6114 return __pick_next_task(rq, prev, rf);
6115}
6116
9edeaea1
PZ
6117#endif /* CONFIG_SCHED_CORE */
6118
b4bfa3fc
TG
6119/*
6120 * Constants for the sched_mode argument of __schedule().
6121 *
6122 * The mode argument allows RT enabled kernels to differentiate a
6123 * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6124 * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6125 * optimize the AND operation out and just check for zero.
6126 */
6127#define SM_NONE 0x0
6128#define SM_PREEMPT 0x1
6991436c
TG
6129#define SM_RTLOCK_WAIT 0x2
6130
6131#ifndef CONFIG_PREEMPT_RT
6132# define SM_MASK_PREEMPT (~0U)
6133#else
6134# define SM_MASK_PREEMPT SM_PREEMPT
6135#endif
b4bfa3fc 6136
dd41f596 6137/*
c259e01a 6138 * __schedule() is the main scheduler function.
edde96ea
PE
6139 *
6140 * The main means of driving the scheduler and thus entering this function are:
6141 *
6142 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6143 *
6144 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6145 * paths. For example, see arch/x86/entry_64.S.
6146 *
6147 * To drive preemption between tasks, the scheduler sets the flag in timer
6148 * interrupt handler scheduler_tick().
6149 *
6150 * 3. Wakeups don't really cause entry into schedule(). They add a
6151 * task to the run-queue and that's it.
6152 *
6153 * Now, if the new task added to the run-queue preempts the current
6154 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6155 * called on the nearest possible occasion:
6156 *
c1a280b6 6157 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
edde96ea
PE
6158 *
6159 * - in syscall or exception context, at the next outmost
6160 * preempt_enable(). (this might be as soon as the wake_up()'s
6161 * spin_unlock()!)
6162 *
6163 * - in IRQ context, return from interrupt-handler to
6164 * preemptible context
6165 *
c1a280b6 6166 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
edde96ea
PE
6167 * then at the next:
6168 *
6169 * - cond_resched() call
6170 * - explicit schedule() call
6171 * - return from syscall or exception to user-space
6172 * - return from interrupt-handler to user-space
bfd9b2b5 6173 *
b30f0e3f 6174 * WARNING: must be called with preemption disabled!
dd41f596 6175 */
b4bfa3fc 6176static void __sched notrace __schedule(unsigned int sched_mode)
dd41f596
IM
6177{
6178 struct task_struct *prev, *next;
67ca7bde 6179 unsigned long *switch_count;
dbfb089d 6180 unsigned long prev_state;
d8ac8971 6181 struct rq_flags rf;
dd41f596 6182 struct rq *rq;
31656519 6183 int cpu;
dd41f596 6184
dd41f596
IM
6185 cpu = smp_processor_id();
6186 rq = cpu_rq(cpu);
dd41f596 6187 prev = rq->curr;
dd41f596 6188
b4bfa3fc 6189 schedule_debug(prev, !!sched_mode);
1da177e4 6190
e0ee463c 6191 if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
f333fdc9 6192 hrtick_clear(rq);
8f4d37ec 6193
46a5d164 6194 local_irq_disable();
b4bfa3fc 6195 rcu_note_context_switch(!!sched_mode);
46a5d164 6196
e0acd0a6
ON
6197 /*
6198 * Make sure that signal_pending_state()->signal_pending() below
6199 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
dbfb089d
PZ
6200 * done by the caller to avoid the race with signal_wake_up():
6201 *
6202 * __set_current_state(@state) signal_wake_up()
6203 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
6204 * wake_up_state(p, state)
6205 * LOCK rq->lock LOCK p->pi_state
6206 * smp_mb__after_spinlock() smp_mb__after_spinlock()
6207 * if (signal_pending_state()) if (p->state & @state)
306e0604 6208 *
dbfb089d 6209 * Also, the membarrier system call requires a full memory barrier
306e0604 6210 * after coming from user-space, before storing to rq->curr.
e0acd0a6 6211 */
8a8c69c3 6212 rq_lock(rq, &rf);
d89e588c 6213 smp_mb__after_spinlock();
1da177e4 6214
d1ccc66d
IM
6215 /* Promote REQ to ACT */
6216 rq->clock_update_flags <<= 1;
bce4dc80 6217 update_rq_clock(rq);
9edfbfed 6218
246d86b5 6219 switch_count = &prev->nivcsw;
d136122f 6220
dbfb089d 6221 /*
d136122f
PZ
6222 * We must load prev->state once (task_struct::state is volatile), such
6223 * that:
6224 *
6225 * - we form a control dependency vs deactivate_task() below.
6226 * - ptrace_{,un}freeze_traced() can change ->state underneath us.
dbfb089d 6227 */
2f064a59 6228 prev_state = READ_ONCE(prev->__state);
b4bfa3fc 6229 if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {
dbfb089d 6230 if (signal_pending_state(prev_state, prev)) {
2f064a59 6231 WRITE_ONCE(prev->__state, TASK_RUNNING);
21aa9af0 6232 } else {
dbfb089d
PZ
6233 prev->sched_contributes_to_load =
6234 (prev_state & TASK_UNINTERRUPTIBLE) &&
6235 !(prev_state & TASK_NOLOAD) &&
6236 !(prev->flags & PF_FROZEN);
6237
6238 if (prev->sched_contributes_to_load)
6239 rq->nr_uninterruptible++;
6240
6241 /*
6242 * __schedule() ttwu()
d136122f
PZ
6243 * prev_state = prev->state; if (p->on_rq && ...)
6244 * if (prev_state) goto out;
6245 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
6246 * p->state = TASK_WAKING
6247 *
6248 * Where __schedule() and ttwu() have matching control dependencies.
dbfb089d
PZ
6249 *
6250 * After this, schedule() must not care about p->state any more.
6251 */
bce4dc80 6252 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
2acca55e 6253
e33a9bba
TH
6254 if (prev->in_iowait) {
6255 atomic_inc(&rq->nr_iowait);
6256 delayacct_blkio_start();
6257 }
21aa9af0 6258 }
dd41f596 6259 switch_count = &prev->nvcsw;
1da177e4
LT
6260 }
6261
d8ac8971 6262 next = pick_next_task(rq, prev, &rf);
f26f9aff 6263 clear_tsk_need_resched(prev);
f27dde8d 6264 clear_preempt_need_resched();
c006fac5
PT
6265#ifdef CONFIG_SCHED_DEBUG
6266 rq->last_seen_need_resched_ns = 0;
6267#endif
1da177e4 6268
1da177e4 6269 if (likely(prev != next)) {
1da177e4 6270 rq->nr_switches++;
5311a98f
EB
6271 /*
6272 * RCU users of rcu_dereference(rq->curr) may not see
6273 * changes to task_struct made by pick_next_task().
6274 */
6275 RCU_INIT_POINTER(rq->curr, next);
22e4ebb9
MD
6276 /*
6277 * The membarrier system call requires each architecture
6278 * to have a full memory barrier after updating
306e0604
MD
6279 * rq->curr, before returning to user-space.
6280 *
6281 * Here are the schemes providing that barrier on the
6282 * various architectures:
6283 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
6284 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
6285 * - finish_lock_switch() for weakly-ordered
6286 * architectures where spin_unlock is a full barrier,
6287 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6288 * is a RELEASE barrier),
22e4ebb9 6289 */
1da177e4
LT
6290 ++*switch_count;
6291
af449901 6292 migrate_disable_switch(rq, prev);
b05e75d6
JW
6293 psi_sched_switch(prev, next, !task_on_rq_queued(prev));
6294
b4bfa3fc 6295 trace_sched_switch(sched_mode & SM_MASK_PREEMPT, prev, next);
d1ccc66d
IM
6296
6297 /* Also unlocks the rq: */
6298 rq = context_switch(rq, prev, next, &rf);
cbce1a68 6299 } else {
cb42c9a3 6300 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
1da177e4 6301
565790d2
PZ
6302 rq_unpin_lock(rq, &rf);
6303 __balance_callbacks(rq);
5cb9eaa3 6304 raw_spin_rq_unlock_irq(rq);
565790d2 6305 }
1da177e4 6306}
c259e01a 6307
9af6528e
PZ
6308void __noreturn do_task_dead(void)
6309{
d1ccc66d 6310 /* Causes final put_task_struct in finish_task_switch(): */
b5bf9a90 6311 set_special_state(TASK_DEAD);
d1ccc66d
IM
6312
6313 /* Tell freezer to ignore us: */
6314 current->flags |= PF_NOFREEZE;
6315
b4bfa3fc 6316 __schedule(SM_NONE);
9af6528e 6317 BUG();
d1ccc66d
IM
6318
6319 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
9af6528e 6320 for (;;)
d1ccc66d 6321 cpu_relax();
9af6528e
PZ
6322}
6323
9c40cef2
TG
6324static inline void sched_submit_work(struct task_struct *tsk)
6325{
c1cecf88
SAS
6326 unsigned int task_flags;
6327
b03fbd4f 6328 if (task_is_running(tsk))
9c40cef2 6329 return;
6d25be57 6330
c1cecf88 6331 task_flags = tsk->flags;
6d25be57 6332 /*
b945efcd
TG
6333 * If a worker goes to sleep, notify and ask workqueue whether it
6334 * wants to wake up a task to maintain concurrency.
6d25be57 6335 */
c1cecf88 6336 if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
c1cecf88 6337 if (task_flags & PF_WQ_WORKER)
771b53d0
JA
6338 wq_worker_sleeping(tsk);
6339 else
6340 io_wq_worker_sleeping(tsk);
6d25be57
TG
6341 }
6342
b0fdc013
SAS
6343 if (tsk_is_pi_blocked(tsk))
6344 return;
6345
9c40cef2
TG
6346 /*
6347 * If we are going to sleep and we have plugged IO queued,
6348 * make sure to submit it to avoid deadlocks.
6349 */
6350 if (blk_needs_flush_plug(tsk))
008f75a2 6351 blk_flush_plug(tsk->plug, true);
9c40cef2
TG
6352}
6353
6d25be57
TG
6354static void sched_update_worker(struct task_struct *tsk)
6355{
771b53d0
JA
6356 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6357 if (tsk->flags & PF_WQ_WORKER)
6358 wq_worker_running(tsk);
6359 else
6360 io_wq_worker_running(tsk);
6361 }
6d25be57
TG
6362}
6363
722a9f92 6364asmlinkage __visible void __sched schedule(void)
c259e01a 6365{
9c40cef2
TG
6366 struct task_struct *tsk = current;
6367
6368 sched_submit_work(tsk);
bfd9b2b5 6369 do {
b30f0e3f 6370 preempt_disable();
b4bfa3fc 6371 __schedule(SM_NONE);
b30f0e3f 6372 sched_preempt_enable_no_resched();
bfd9b2b5 6373 } while (need_resched());
6d25be57 6374 sched_update_worker(tsk);
c259e01a 6375}
1da177e4
LT
6376EXPORT_SYMBOL(schedule);
6377
8663effb
SRV
6378/*
6379 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6380 * state (have scheduled out non-voluntarily) by making sure that all
6381 * tasks have either left the run queue or have gone into user space.
6382 * As idle tasks do not do either, they must not ever be preempted
6383 * (schedule out non-voluntarily).
6384 *
6385 * schedule_idle() is similar to schedule_preempt_disable() except that it
6386 * never enables preemption because it does not call sched_submit_work().
6387 */
6388void __sched schedule_idle(void)
6389{
6390 /*
6391 * As this skips calling sched_submit_work(), which the idle task does
6392 * regardless because that function is a nop when the task is in a
6393 * TASK_RUNNING state, make sure this isn't used someplace that the
6394 * current task can be in any other state. Note, idle is always in the
6395 * TASK_RUNNING state.
6396 */
2f064a59 6397 WARN_ON_ONCE(current->__state);
8663effb 6398 do {
b4bfa3fc 6399 __schedule(SM_NONE);
8663effb
SRV
6400 } while (need_resched());
6401}
6402
6775de49 6403#if defined(CONFIG_CONTEXT_TRACKING) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_OFFSTACK)
722a9f92 6404asmlinkage __visible void __sched schedule_user(void)
20ab65e3
FW
6405{
6406 /*
6407 * If we come here after a random call to set_need_resched(),
6408 * or we have been woken up remotely but the IPI has not yet arrived,
6409 * we haven't yet exited the RCU idle mode. Do it here manually until
6410 * we find a better solution.
7cc78f8f
AL
6411 *
6412 * NB: There are buggy callers of this function. Ideally we
c467ea76 6413 * should warn if prev_state != CONTEXT_USER, but that will trigger
7cc78f8f 6414 * too frequently to make sense yet.
20ab65e3 6415 */
7cc78f8f 6416 enum ctx_state prev_state = exception_enter();
20ab65e3 6417 schedule();
7cc78f8f 6418 exception_exit(prev_state);
20ab65e3
FW
6419}
6420#endif
6421
c5491ea7
TG
6422/**
6423 * schedule_preempt_disabled - called with preemption disabled
6424 *
6425 * Returns with preemption disabled. Note: preempt_count must be 1
6426 */
6427void __sched schedule_preempt_disabled(void)
6428{
ba74c144 6429 sched_preempt_enable_no_resched();
c5491ea7
TG
6430 schedule();
6431 preempt_disable();
6432}
6433
6991436c
TG
6434#ifdef CONFIG_PREEMPT_RT
6435void __sched notrace schedule_rtlock(void)
6436{
6437 do {
6438 preempt_disable();
6439 __schedule(SM_RTLOCK_WAIT);
6440 sched_preempt_enable_no_resched();
6441 } while (need_resched());
6442}
6443NOKPROBE_SYMBOL(schedule_rtlock);
6444#endif
6445
06b1f808 6446static void __sched notrace preempt_schedule_common(void)
a18b5d01
FW
6447{
6448 do {
47252cfb
SR
6449 /*
6450 * Because the function tracer can trace preempt_count_sub()
6451 * and it also uses preempt_enable/disable_notrace(), if
6452 * NEED_RESCHED is set, the preempt_enable_notrace() called
6453 * by the function tracer will call this function again and
6454 * cause infinite recursion.
6455 *
6456 * Preemption must be disabled here before the function
6457 * tracer can trace. Break up preempt_disable() into two
6458 * calls. One to disable preemption without fear of being
6459 * traced. The other to still record the preemption latency,
6460 * which can also be traced by the function tracer.
6461 */
499d7955 6462 preempt_disable_notrace();
47252cfb 6463 preempt_latency_start(1);
b4bfa3fc 6464 __schedule(SM_PREEMPT);
47252cfb 6465 preempt_latency_stop(1);
499d7955 6466 preempt_enable_no_resched_notrace();
a18b5d01
FW
6467
6468 /*
6469 * Check again in case we missed a preemption opportunity
6470 * between schedule and now.
6471 */
a18b5d01
FW
6472 } while (need_resched());
6473}
6474
c1a280b6 6475#ifdef CONFIG_PREEMPTION
1da177e4 6476/*
a49b4f40
VS
6477 * This is the entry point to schedule() from in-kernel preemption
6478 * off of preempt_enable.
1da177e4 6479 */
722a9f92 6480asmlinkage __visible void __sched notrace preempt_schedule(void)
1da177e4 6481{
1da177e4
LT
6482 /*
6483 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 6484 * we do not want to preempt the current task. Just return..
1da177e4 6485 */
fbb00b56 6486 if (likely(!preemptible()))
1da177e4 6487 return;
a18b5d01 6488 preempt_schedule_common();
1da177e4 6489}
376e2424 6490NOKPROBE_SYMBOL(preempt_schedule);
1da177e4 6491EXPORT_SYMBOL(preempt_schedule);
009f60e2 6492
2c9a98d3 6493#ifdef CONFIG_PREEMPT_DYNAMIC
99cf983c 6494#if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8a69fe0b
MR
6495#ifndef preempt_schedule_dynamic_enabled
6496#define preempt_schedule_dynamic_enabled preempt_schedule
6497#define preempt_schedule_dynamic_disabled NULL
6498#endif
6499DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
ef72661e 6500EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
99cf983c
MR
6501#elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6502static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
6503void __sched notrace dynamic_preempt_schedule(void)
6504{
6505 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
6506 return;
6507 preempt_schedule();
6508}
6509NOKPROBE_SYMBOL(dynamic_preempt_schedule);
6510EXPORT_SYMBOL(dynamic_preempt_schedule);
6511#endif
2c9a98d3 6512#endif
2c9a98d3 6513
009f60e2 6514/**
4eaca0a8 6515 * preempt_schedule_notrace - preempt_schedule called by tracing
009f60e2
ON
6516 *
6517 * The tracing infrastructure uses preempt_enable_notrace to prevent
6518 * recursion and tracing preempt enabling caused by the tracing
6519 * infrastructure itself. But as tracing can happen in areas coming
6520 * from userspace or just about to enter userspace, a preempt enable
6521 * can occur before user_exit() is called. This will cause the scheduler
6522 * to be called when the system is still in usermode.
6523 *
6524 * To prevent this, the preempt_enable_notrace will use this function
6525 * instead of preempt_schedule() to exit user context if needed before
6526 * calling the scheduler.
6527 */
4eaca0a8 6528asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
009f60e2
ON
6529{
6530 enum ctx_state prev_ctx;
6531
6532 if (likely(!preemptible()))
6533 return;
6534
6535 do {
47252cfb
SR
6536 /*
6537 * Because the function tracer can trace preempt_count_sub()
6538 * and it also uses preempt_enable/disable_notrace(), if
6539 * NEED_RESCHED is set, the preempt_enable_notrace() called
6540 * by the function tracer will call this function again and
6541 * cause infinite recursion.
6542 *
6543 * Preemption must be disabled here before the function
6544 * tracer can trace. Break up preempt_disable() into two
6545 * calls. One to disable preemption without fear of being
6546 * traced. The other to still record the preemption latency,
6547 * which can also be traced by the function tracer.
6548 */
3d8f74dd 6549 preempt_disable_notrace();
47252cfb 6550 preempt_latency_start(1);
009f60e2
ON
6551 /*
6552 * Needs preempt disabled in case user_exit() is traced
6553 * and the tracer calls preempt_enable_notrace() causing
6554 * an infinite recursion.
6555 */
6556 prev_ctx = exception_enter();
b4bfa3fc 6557 __schedule(SM_PREEMPT);
009f60e2
ON
6558 exception_exit(prev_ctx);
6559
47252cfb 6560 preempt_latency_stop(1);
3d8f74dd 6561 preempt_enable_no_resched_notrace();
009f60e2
ON
6562 } while (need_resched());
6563}
4eaca0a8 6564EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
009f60e2 6565
2c9a98d3 6566#ifdef CONFIG_PREEMPT_DYNAMIC
99cf983c 6567#if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8a69fe0b
MR
6568#ifndef preempt_schedule_notrace_dynamic_enabled
6569#define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace
6570#define preempt_schedule_notrace_dynamic_disabled NULL
6571#endif
6572DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
ef72661e 6573EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
99cf983c
MR
6574#elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6575static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
6576void __sched notrace dynamic_preempt_schedule_notrace(void)
6577{
6578 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
6579 return;
6580 preempt_schedule_notrace();
6581}
6582NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
6583EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
6584#endif
2c9a98d3
PZI
6585#endif
6586
c1a280b6 6587#endif /* CONFIG_PREEMPTION */
1da177e4
LT
6588
6589/*
a49b4f40 6590 * This is the entry point to schedule() from kernel preemption
1da177e4
LT
6591 * off of irq context.
6592 * Note, that this is called and return with irqs disabled. This will
6593 * protect us against recursive calling from irq.
6594 */
722a9f92 6595asmlinkage __visible void __sched preempt_schedule_irq(void)
1da177e4 6596{
b22366cd 6597 enum ctx_state prev_state;
6478d880 6598
2ed6e34f 6599 /* Catch callers which need to be fixed */
f27dde8d 6600 BUG_ON(preempt_count() || !irqs_disabled());
1da177e4 6601
b22366cd
FW
6602 prev_state = exception_enter();
6603
3a5c359a 6604 do {
3d8f74dd 6605 preempt_disable();
3a5c359a 6606 local_irq_enable();
b4bfa3fc 6607 __schedule(SM_PREEMPT);
3a5c359a 6608 local_irq_disable();
3d8f74dd 6609 sched_preempt_enable_no_resched();
5ed0cec0 6610 } while (need_resched());
b22366cd
FW
6611
6612 exception_exit(prev_state);
1da177e4
LT
6613}
6614
ac6424b9 6615int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
95cdf3b7 6616 void *key)
1da177e4 6617{
062d3f95 6618 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
63859d4f 6619 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 6620}
1da177e4
LT
6621EXPORT_SYMBOL(default_wake_function);
6622
f558c2b8
PZ
6623static void __setscheduler_prio(struct task_struct *p, int prio)
6624{
6625 if (dl_prio(prio))
6626 p->sched_class = &dl_sched_class;
6627 else if (rt_prio(prio))
6628 p->sched_class = &rt_sched_class;
6629 else
6630 p->sched_class = &fair_sched_class;
6631
6632 p->prio = prio;
6633}
6634
b29739f9
IM
6635#ifdef CONFIG_RT_MUTEXES
6636
acd58620
PZ
6637static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
6638{
6639 if (pi_task)
6640 prio = min(prio, pi_task->prio);
6641
6642 return prio;
6643}
6644
6645static inline int rt_effective_prio(struct task_struct *p, int prio)
6646{
6647 struct task_struct *pi_task = rt_mutex_get_top_task(p);
6648
6649 return __rt_effective_prio(pi_task, prio);
6650}
6651
b29739f9
IM
6652/*
6653 * rt_mutex_setprio - set the current priority of a task
acd58620
PZ
6654 * @p: task to boost
6655 * @pi_task: donor task
b29739f9
IM
6656 *
6657 * This function changes the 'effective' priority of a task. It does
6658 * not touch ->normal_prio like __setscheduler().
6659 *
c365c292
TG
6660 * Used by the rt_mutex code to implement priority inheritance
6661 * logic. Call site only calls if the priority of the task changed.
b29739f9 6662 */
acd58620 6663void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
b29739f9 6664{
acd58620 6665 int prio, oldprio, queued, running, queue_flag =
7a57f32a 6666 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
83ab0aa0 6667 const struct sched_class *prev_class;
eb580751
PZ
6668 struct rq_flags rf;
6669 struct rq *rq;
b29739f9 6670
acd58620
PZ
6671 /* XXX used to be waiter->prio, not waiter->task->prio */
6672 prio = __rt_effective_prio(pi_task, p->normal_prio);
6673
6674 /*
6675 * If nothing changed; bail early.
6676 */
6677 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
6678 return;
b29739f9 6679
eb580751 6680 rq = __task_rq_lock(p, &rf);
80f5c1b8 6681 update_rq_clock(rq);
acd58620
PZ
6682 /*
6683 * Set under pi_lock && rq->lock, such that the value can be used under
6684 * either lock.
6685 *
6686 * Note that there is loads of tricky to make this pointer cache work
6687 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
6688 * ensure a task is de-boosted (pi_task is set to NULL) before the
6689 * task is allowed to run again (and can exit). This ensures the pointer
b19a888c 6690 * points to a blocked task -- which guarantees the task is present.
acd58620
PZ
6691 */
6692 p->pi_top_task = pi_task;
6693
6694 /*
6695 * For FIFO/RR we only need to set prio, if that matches we're done.
6696 */
6697 if (prio == p->prio && !dl_prio(prio))
6698 goto out_unlock;
b29739f9 6699
1c4dd99b
TG
6700 /*
6701 * Idle task boosting is a nono in general. There is one
6702 * exception, when PREEMPT_RT and NOHZ is active:
6703 *
6704 * The idle task calls get_next_timer_interrupt() and holds
6705 * the timer wheel base->lock on the CPU and another CPU wants
6706 * to access the timer (probably to cancel it). We can safely
6707 * ignore the boosting request, as the idle CPU runs this code
6708 * with interrupts disabled and will complete the lock
6709 * protected section without being interrupted. So there is no
6710 * real need to boost.
6711 */
6712 if (unlikely(p == rq->idle)) {
6713 WARN_ON(p != rq->curr);
6714 WARN_ON(p->pi_blocked_on);
6715 goto out_unlock;
6716 }
6717
b91473ff 6718 trace_sched_pi_setprio(p, pi_task);
d5f9f942 6719 oldprio = p->prio;
ff77e468
PZ
6720
6721 if (oldprio == prio)
6722 queue_flag &= ~DEQUEUE_MOVE;
6723
83ab0aa0 6724 prev_class = p->sched_class;
da0c1e65 6725 queued = task_on_rq_queued(p);
051a1d1a 6726 running = task_current(rq, p);
da0c1e65 6727 if (queued)
ff77e468 6728 dequeue_task(rq, p, queue_flag);
0e1f3483 6729 if (running)
f3cd1c4e 6730 put_prev_task(rq, p);
dd41f596 6731
2d3d891d
DF
6732 /*
6733 * Boosting condition are:
6734 * 1. -rt task is running and holds mutex A
6735 * --> -dl task blocks on mutex A
6736 *
6737 * 2. -dl task is running and holds mutex A
6738 * --> -dl task blocks on mutex A and could preempt the
6739 * running task
6740 */
6741 if (dl_prio(prio)) {
466af29b 6742 if (!dl_prio(p->normal_prio) ||
740797ce
JL
6743 (pi_task && dl_prio(pi_task->prio) &&
6744 dl_entity_preempt(&pi_task->dl, &p->dl))) {
2279f540 6745 p->dl.pi_se = pi_task->dl.pi_se;
ff77e468 6746 queue_flag |= ENQUEUE_REPLENISH;
2279f540
JL
6747 } else {
6748 p->dl.pi_se = &p->dl;
6749 }
2d3d891d
DF
6750 } else if (rt_prio(prio)) {
6751 if (dl_prio(oldprio))
2279f540 6752 p->dl.pi_se = &p->dl;
2d3d891d 6753 if (oldprio < prio)
ff77e468 6754 queue_flag |= ENQUEUE_HEAD;
2d3d891d
DF
6755 } else {
6756 if (dl_prio(oldprio))
2279f540 6757 p->dl.pi_se = &p->dl;
746db944
BS
6758 if (rt_prio(oldprio))
6759 p->rt.timeout = 0;
2d3d891d 6760 }
dd41f596 6761
f558c2b8 6762 __setscheduler_prio(p, prio);
b29739f9 6763
da0c1e65 6764 if (queued)
ff77e468 6765 enqueue_task(rq, p, queue_flag);
a399d233 6766 if (running)
03b7fad1 6767 set_next_task(rq, p);
cb469845 6768
da7a735e 6769 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 6770out_unlock:
d1ccc66d
IM
6771 /* Avoid rq from going away on us: */
6772 preempt_disable();
4c9a4bc8 6773
565790d2
PZ
6774 rq_unpin_lock(rq, &rf);
6775 __balance_callbacks(rq);
5cb9eaa3 6776 raw_spin_rq_unlock(rq);
565790d2 6777
4c9a4bc8 6778 preempt_enable();
b29739f9 6779}
acd58620
PZ
6780#else
6781static inline int rt_effective_prio(struct task_struct *p, int prio)
6782{
6783 return prio;
6784}
b29739f9 6785#endif
d50dde5a 6786
36c8b586 6787void set_user_nice(struct task_struct *p, long nice)
1da177e4 6788{
49bd21ef 6789 bool queued, running;
53a23364 6790 int old_prio;
eb580751 6791 struct rq_flags rf;
70b97a7f 6792 struct rq *rq;
1da177e4 6793
75e45d51 6794 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
1da177e4
LT
6795 return;
6796 /*
6797 * We have to be careful, if called from sys_setpriority(),
6798 * the task might be in the middle of scheduling on another CPU.
6799 */
eb580751 6800 rq = task_rq_lock(p, &rf);
2fb8d367
PZ
6801 update_rq_clock(rq);
6802
1da177e4
LT
6803 /*
6804 * The RT priorities are set via sched_setscheduler(), but we still
6805 * allow the 'normal' nice value to be set - but as expected
b19a888c 6806 * it won't have any effect on scheduling until the task is
aab03e05 6807 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
1da177e4 6808 */
aab03e05 6809 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
1da177e4
LT
6810 p->static_prio = NICE_TO_PRIO(nice);
6811 goto out_unlock;
6812 }
da0c1e65 6813 queued = task_on_rq_queued(p);
49bd21ef 6814 running = task_current(rq, p);
da0c1e65 6815 if (queued)
7a57f32a 6816 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
49bd21ef
PZ
6817 if (running)
6818 put_prev_task(rq, p);
1da177e4 6819
1da177e4 6820 p->static_prio = NICE_TO_PRIO(nice);
9059393e 6821 set_load_weight(p, true);
b29739f9
IM
6822 old_prio = p->prio;
6823 p->prio = effective_prio(p);
1da177e4 6824
5443a0be 6825 if (queued)
7134b3e9 6826 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
49bd21ef 6827 if (running)
03b7fad1 6828 set_next_task(rq, p);
5443a0be
FW
6829
6830 /*
6831 * If the task increased its priority or is running and
6832 * lowered its priority, then reschedule its CPU:
6833 */
6834 p->sched_class->prio_changed(rq, p, old_prio);
6835
1da177e4 6836out_unlock:
eb580751 6837 task_rq_unlock(rq, p, &rf);
1da177e4 6838}
1da177e4
LT
6839EXPORT_SYMBOL(set_user_nice);
6840
e43379f1
MM
6841/*
6842 * can_nice - check if a task can reduce its nice value
6843 * @p: task
6844 * @nice: nice value
6845 */
36c8b586 6846int can_nice(const struct task_struct *p, const int nice)
e43379f1 6847{
d1ccc66d 6848 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
7aa2c016 6849 int nice_rlim = nice_to_rlimit(nice);
48f24c4d 6850
78d7d407 6851 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
6852 capable(CAP_SYS_NICE));
6853}
6854
1da177e4
LT
6855#ifdef __ARCH_WANT_SYS_NICE
6856
6857/*
6858 * sys_nice - change the priority of the current process.
6859 * @increment: priority increment
6860 *
6861 * sys_setpriority is a more generic, but much slower function that
6862 * does similar things.
6863 */
5add95d4 6864SYSCALL_DEFINE1(nice, int, increment)
1da177e4 6865{
48f24c4d 6866 long nice, retval;
1da177e4
LT
6867
6868 /*
6869 * Setpriority might change our priority at the same moment.
6870 * We don't have to worry. Conceptually one call occurs first
6871 * and we have a single winner.
6872 */
a9467fa3 6873 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
d0ea0268 6874 nice = task_nice(current) + increment;
1da177e4 6875
a9467fa3 6876 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
e43379f1
MM
6877 if (increment < 0 && !can_nice(current, nice))
6878 return -EPERM;
6879
1da177e4
LT
6880 retval = security_task_setnice(current, nice);
6881 if (retval)
6882 return retval;
6883
6884 set_user_nice(current, nice);
6885 return 0;
6886}
6887
6888#endif
6889
6890/**
6891 * task_prio - return the priority value of a given task.
6892 * @p: the task in question.
6893 *
e69f6186 6894 * Return: The priority value as seen by users in /proc.
c541bb78
DE
6895 *
6896 * sched policy return value kernel prio user prio/nice
6897 *
6898 * normal, batch, idle [0 ... 39] [100 ... 139] 0/[-20 ... 19]
6899 * fifo, rr [-2 ... -100] [98 ... 0] [1 ... 99]
6900 * deadline -101 -1 0
1da177e4 6901 */
36c8b586 6902int task_prio(const struct task_struct *p)
1da177e4
LT
6903{
6904 return p->prio - MAX_RT_PRIO;
6905}
6906
1da177e4 6907/**
d1ccc66d 6908 * idle_cpu - is a given CPU idle currently?
1da177e4 6909 * @cpu: the processor in question.
e69f6186
YB
6910 *
6911 * Return: 1 if the CPU is currently idle. 0 otherwise.
1da177e4
LT
6912 */
6913int idle_cpu(int cpu)
6914{
908a3283
TG
6915 struct rq *rq = cpu_rq(cpu);
6916
6917 if (rq->curr != rq->idle)
6918 return 0;
6919
6920 if (rq->nr_running)
6921 return 0;
6922
6923#ifdef CONFIG_SMP
126c2092 6924 if (rq->ttwu_pending)
908a3283
TG
6925 return 0;
6926#endif
6927
6928 return 1;
1da177e4
LT
6929}
6930
943d355d
RJ
6931/**
6932 * available_idle_cpu - is a given CPU idle for enqueuing work.
6933 * @cpu: the CPU in question.
6934 *
6935 * Return: 1 if the CPU is currently idle. 0 otherwise.
6936 */
6937int available_idle_cpu(int cpu)
6938{
6939 if (!idle_cpu(cpu))
6940 return 0;
6941
247f2f6f
RJ
6942 if (vcpu_is_preempted(cpu))
6943 return 0;
6944
908a3283 6945 return 1;
1da177e4
LT
6946}
6947
1da177e4 6948/**
d1ccc66d 6949 * idle_task - return the idle task for a given CPU.
1da177e4 6950 * @cpu: the processor in question.
e69f6186 6951 *
d1ccc66d 6952 * Return: The idle task for the CPU @cpu.
1da177e4 6953 */
36c8b586 6954struct task_struct *idle_task(int cpu)
1da177e4
LT
6955{
6956 return cpu_rq(cpu)->idle;
6957}
6958
7d6a905f
VK
6959#ifdef CONFIG_SMP
6960/*
6961 * This function computes an effective utilization for the given CPU, to be
6962 * used for frequency selection given the linear relation: f = u * f_max.
6963 *
6964 * The scheduler tracks the following metrics:
6965 *
6966 * cpu_util_{cfs,rt,dl,irq}()
6967 * cpu_bw_dl()
6968 *
6969 * Where the cfs,rt and dl util numbers are tracked with the same metric and
6970 * synchronized windows and are thus directly comparable.
6971 *
6972 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
6973 * which excludes things like IRQ and steal-time. These latter are then accrued
6974 * in the irq utilization.
6975 *
6976 * The DL bandwidth number otoh is not a measured metric but a value computed
6977 * based on the task model parameters and gives the minimal utilization
6978 * required to meet deadlines.
6979 */
a5418be9
VK
6980unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
6981 unsigned long max, enum cpu_util_type type,
7d6a905f
VK
6982 struct task_struct *p)
6983{
6984 unsigned long dl_util, util, irq;
6985 struct rq *rq = cpu_rq(cpu);
6986
6987 if (!uclamp_is_used() &&
6988 type == FREQUENCY_UTIL && rt_rq_is_runnable(&rq->rt)) {
6989 return max;
6990 }
6991
6992 /*
6993 * Early check to see if IRQ/steal time saturates the CPU, can be
6994 * because of inaccuracies in how we track these -- see
6995 * update_irq_load_avg().
6996 */
6997 irq = cpu_util_irq(rq);
6998 if (unlikely(irq >= max))
6999 return max;
7000
7001 /*
7002 * Because the time spend on RT/DL tasks is visible as 'lost' time to
7003 * CFS tasks and we use the same metric to track the effective
7004 * utilization (PELT windows are synchronized) we can directly add them
7005 * to obtain the CPU's actual utilization.
7006 *
7007 * CFS and RT utilization can be boosted or capped, depending on
7008 * utilization clamp constraints requested by currently RUNNABLE
7009 * tasks.
7010 * When there are no CFS RUNNABLE tasks, clamps are released and
7011 * frequency will be gracefully reduced with the utilization decay.
7012 */
7013 util = util_cfs + cpu_util_rt(rq);
7014 if (type == FREQUENCY_UTIL)
7015 util = uclamp_rq_util_with(rq, util, p);
7016
7017 dl_util = cpu_util_dl(rq);
7018
7019 /*
7020 * For frequency selection we do not make cpu_util_dl() a permanent part
7021 * of this sum because we want to use cpu_bw_dl() later on, but we need
7022 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
7023 * that we select f_max when there is no idle time.
7024 *
7025 * NOTE: numerical errors or stop class might cause us to not quite hit
7026 * saturation when we should -- something for later.
7027 */
7028 if (util + dl_util >= max)
7029 return max;
7030
7031 /*
7032 * OTOH, for energy computation we need the estimated running time, so
7033 * include util_dl and ignore dl_bw.
7034 */
7035 if (type == ENERGY_UTIL)
7036 util += dl_util;
7037
7038 /*
7039 * There is still idle time; further improve the number by using the
7040 * irq metric. Because IRQ/steal time is hidden from the task clock we
7041 * need to scale the task numbers:
7042 *
7043 * max - irq
7044 * U' = irq + --------- * U
7045 * max
7046 */
7047 util = scale_irq_capacity(util, irq, max);
7048 util += irq;
7049
7050 /*
7051 * Bandwidth required by DEADLINE must always be granted while, for
7052 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
7053 * to gracefully reduce the frequency when no tasks show up for longer
7054 * periods of time.
7055 *
7056 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
7057 * bw_dl as requested freq. However, cpufreq is not yet ready for such
7058 * an interface. So, we only do the latter for now.
7059 */
7060 if (type == FREQUENCY_UTIL)
7061 util += cpu_bw_dl(rq);
7062
7063 return min(max, util);
7064}
a5418be9
VK
7065
7066unsigned long sched_cpu_util(int cpu, unsigned long max)
7067{
82762d2a 7068 return effective_cpu_util(cpu, cpu_util_cfs(cpu), max,
a5418be9
VK
7069 ENERGY_UTIL, NULL);
7070}
7d6a905f
VK
7071#endif /* CONFIG_SMP */
7072
1da177e4
LT
7073/**
7074 * find_process_by_pid - find a process with a matching PID value.
7075 * @pid: the pid in question.
e69f6186
YB
7076 *
7077 * The task of @pid, if found. %NULL otherwise.
1da177e4 7078 */
a9957449 7079static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 7080{
228ebcbe 7081 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
7082}
7083
c13db6b1
SR
7084/*
7085 * sched_setparam() passes in -1 for its policy, to let the functions
7086 * it calls know not to change it.
7087 */
7088#define SETPARAM_POLICY -1
7089
c365c292
TG
7090static void __setscheduler_params(struct task_struct *p,
7091 const struct sched_attr *attr)
1da177e4 7092{
d50dde5a
DF
7093 int policy = attr->sched_policy;
7094
c13db6b1 7095 if (policy == SETPARAM_POLICY)
39fd8fd2
PZ
7096 policy = p->policy;
7097
1da177e4 7098 p->policy = policy;
d50dde5a 7099
aab03e05
DF
7100 if (dl_policy(policy))
7101 __setparam_dl(p, attr);
39fd8fd2 7102 else if (fair_policy(policy))
d50dde5a
DF
7103 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
7104
39fd8fd2
PZ
7105 /*
7106 * __sched_setscheduler() ensures attr->sched_priority == 0 when
7107 * !rt_policy. Always setting this ensures that things like
7108 * getparam()/getattr() don't report silly values for !rt tasks.
7109 */
7110 p->rt_priority = attr->sched_priority;
383afd09 7111 p->normal_prio = normal_prio(p);
9059393e 7112 set_load_weight(p, true);
c365c292 7113}
39fd8fd2 7114
c69e8d9c 7115/*
d1ccc66d 7116 * Check the target process has a UID that matches the current process's:
c69e8d9c
DH
7117 */
7118static bool check_same_owner(struct task_struct *p)
7119{
7120 const struct cred *cred = current_cred(), *pcred;
7121 bool match;
7122
7123 rcu_read_lock();
7124 pcred = __task_cred(p);
9c806aa0
EB
7125 match = (uid_eq(cred->euid, pcred->euid) ||
7126 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
7127 rcu_read_unlock();
7128 return match;
7129}
7130
d50dde5a
DF
7131static int __sched_setscheduler(struct task_struct *p,
7132 const struct sched_attr *attr,
dbc7f069 7133 bool user, bool pi)
1da177e4 7134{
f558c2b8
PZ
7135 int oldpolicy = -1, policy = attr->sched_policy;
7136 int retval, oldprio, newprio, queued, running;
83ab0aa0 7137 const struct sched_class *prev_class;
565790d2 7138 struct callback_head *head;
eb580751 7139 struct rq_flags rf;
ca94c442 7140 int reset_on_fork;
7a57f32a 7141 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
eb580751 7142 struct rq *rq;
1da177e4 7143
896bbb25
SRV
7144 /* The pi code expects interrupts enabled */
7145 BUG_ON(pi && in_interrupt());
1da177e4 7146recheck:
d1ccc66d 7147 /* Double check policy once rq lock held: */
ca94c442
LP
7148 if (policy < 0) {
7149 reset_on_fork = p->sched_reset_on_fork;
1da177e4 7150 policy = oldpolicy = p->policy;
ca94c442 7151 } else {
7479f3c9 7152 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
ca94c442 7153
20f9cd2a 7154 if (!valid_policy(policy))
ca94c442
LP
7155 return -EINVAL;
7156 }
7157
794a56eb 7158 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
7479f3c9
PZ
7159 return -EINVAL;
7160
1da177e4
LT
7161 /*
7162 * Valid priorities for SCHED_FIFO and SCHED_RR are
ae18ad28 7163 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
dd41f596 7164 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4 7165 */
ae18ad28 7166 if (attr->sched_priority > MAX_RT_PRIO-1)
1da177e4 7167 return -EINVAL;
aab03e05
DF
7168 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
7169 (rt_policy(policy) != (attr->sched_priority != 0)))
1da177e4
LT
7170 return -EINVAL;
7171
37e4ab3f
OC
7172 /*
7173 * Allow unprivileged RT tasks to decrease priority:
7174 */
961ccddd 7175 if (user && !capable(CAP_SYS_NICE)) {
d50dde5a 7176 if (fair_policy(policy)) {
d0ea0268 7177 if (attr->sched_nice < task_nice(p) &&
eaad4513 7178 !can_nice(p, attr->sched_nice))
d50dde5a
DF
7179 return -EPERM;
7180 }
7181
e05606d3 7182 if (rt_policy(policy)) {
a44702e8
ON
7183 unsigned long rlim_rtprio =
7184 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909 7185
d1ccc66d 7186 /* Can't set/change the rt policy: */
8dc3e909
ON
7187 if (policy != p->policy && !rlim_rtprio)
7188 return -EPERM;
7189
d1ccc66d 7190 /* Can't increase priority: */
d50dde5a
DF
7191 if (attr->sched_priority > p->rt_priority &&
7192 attr->sched_priority > rlim_rtprio)
8dc3e909
ON
7193 return -EPERM;
7194 }
c02aa73b 7195
d44753b8
JL
7196 /*
7197 * Can't set/change SCHED_DEADLINE policy at all for now
7198 * (safest behavior); in the future we would like to allow
7199 * unprivileged DL tasks to increase their relative deadline
7200 * or reduce their runtime (both ways reducing utilization)
7201 */
7202 if (dl_policy(policy))
7203 return -EPERM;
7204
dd41f596 7205 /*
c02aa73b
DH
7206 * Treat SCHED_IDLE as nice 20. Only allow a switch to
7207 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 7208 */
1da1843f 7209 if (task_has_idle_policy(p) && !idle_policy(policy)) {
d0ea0268 7210 if (!can_nice(p, task_nice(p)))
c02aa73b
DH
7211 return -EPERM;
7212 }
5fe1d75f 7213
d1ccc66d 7214 /* Can't change other user's priorities: */
c69e8d9c 7215 if (!check_same_owner(p))
37e4ab3f 7216 return -EPERM;
ca94c442 7217
d1ccc66d 7218 /* Normal users shall not reset the sched_reset_on_fork flag: */
ca94c442
LP
7219 if (p->sched_reset_on_fork && !reset_on_fork)
7220 return -EPERM;
37e4ab3f 7221 }
1da177e4 7222
725aad24 7223 if (user) {
794a56eb
JL
7224 if (attr->sched_flags & SCHED_FLAG_SUGOV)
7225 return -EINVAL;
7226
b0ae1981 7227 retval = security_task_setscheduler(p);
725aad24
JF
7228 if (retval)
7229 return retval;
7230 }
7231
a509a7cd
PB
7232 /* Update task specific "requested" clamps */
7233 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
7234 retval = uclamp_validate(p, attr);
7235 if (retval)
7236 return retval;
7237 }
7238
710da3c8
JL
7239 if (pi)
7240 cpuset_read_lock();
7241
b29739f9 7242 /*
d1ccc66d 7243 * Make sure no PI-waiters arrive (or leave) while we are
b29739f9 7244 * changing the priority of the task:
0122ec5b 7245 *
25985edc 7246 * To be able to change p->policy safely, the appropriate
1da177e4
LT
7247 * runqueue lock must be held.
7248 */
eb580751 7249 rq = task_rq_lock(p, &rf);
80f5c1b8 7250 update_rq_clock(rq);
dc61b1d6 7251
34f971f6 7252 /*
d1ccc66d 7253 * Changing the policy of the stop threads its a very bad idea:
34f971f6
PZ
7254 */
7255 if (p == rq->stop) {
4b211f2b
MP
7256 retval = -EINVAL;
7257 goto unlock;
34f971f6
PZ
7258 }
7259
a51e9198 7260 /*
d6b1e911
TG
7261 * If not changing anything there's no need to proceed further,
7262 * but store a possible modification of reset_on_fork.
a51e9198 7263 */
d50dde5a 7264 if (unlikely(policy == p->policy)) {
d0ea0268 7265 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
d50dde5a
DF
7266 goto change;
7267 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
7268 goto change;
75381608 7269 if (dl_policy(policy) && dl_param_changed(p, attr))
aab03e05 7270 goto change;
a509a7cd
PB
7271 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
7272 goto change;
d50dde5a 7273
d6b1e911 7274 p->sched_reset_on_fork = reset_on_fork;
4b211f2b
MP
7275 retval = 0;
7276 goto unlock;
a51e9198 7277 }
d50dde5a 7278change:
a51e9198 7279
dc61b1d6 7280 if (user) {
332ac17e 7281#ifdef CONFIG_RT_GROUP_SCHED
dc61b1d6
PZ
7282 /*
7283 * Do not allow realtime tasks into groups that have no runtime
7284 * assigned.
7285 */
7286 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
7287 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
7288 !task_group_is_autogroup(task_group(p))) {
4b211f2b
MP
7289 retval = -EPERM;
7290 goto unlock;
dc61b1d6 7291 }
dc61b1d6 7292#endif
332ac17e 7293#ifdef CONFIG_SMP
794a56eb
JL
7294 if (dl_bandwidth_enabled() && dl_policy(policy) &&
7295 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
332ac17e 7296 cpumask_t *span = rq->rd->span;
332ac17e
DF
7297
7298 /*
7299 * Don't allow tasks with an affinity mask smaller than
7300 * the entire root_domain to become SCHED_DEADLINE. We
7301 * will also fail if there's no bandwidth available.
7302 */
3bd37062 7303 if (!cpumask_subset(span, p->cpus_ptr) ||
e4099a5e 7304 rq->rd->dl_bw.bw == 0) {
4b211f2b
MP
7305 retval = -EPERM;
7306 goto unlock;
332ac17e
DF
7307 }
7308 }
7309#endif
7310 }
dc61b1d6 7311
d1ccc66d 7312 /* Re-check policy now with rq lock held: */
1da177e4
LT
7313 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
7314 policy = oldpolicy = -1;
eb580751 7315 task_rq_unlock(rq, p, &rf);
710da3c8
JL
7316 if (pi)
7317 cpuset_read_unlock();
1da177e4
LT
7318 goto recheck;
7319 }
332ac17e
DF
7320
7321 /*
7322 * If setscheduling to SCHED_DEADLINE (or changing the parameters
7323 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
7324 * is available.
7325 */
06a76fe0 7326 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4b211f2b
MP
7327 retval = -EBUSY;
7328 goto unlock;
332ac17e
DF
7329 }
7330
c365c292
TG
7331 p->sched_reset_on_fork = reset_on_fork;
7332 oldprio = p->prio;
7333
f558c2b8 7334 newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
dbc7f069
PZ
7335 if (pi) {
7336 /*
7337 * Take priority boosted tasks into account. If the new
7338 * effective priority is unchanged, we just store the new
7339 * normal parameters and do not touch the scheduler class and
7340 * the runqueue. This will be done when the task deboost
7341 * itself.
7342 */
f558c2b8
PZ
7343 newprio = rt_effective_prio(p, newprio);
7344 if (newprio == oldprio)
ff77e468 7345 queue_flags &= ~DEQUEUE_MOVE;
c365c292
TG
7346 }
7347
da0c1e65 7348 queued = task_on_rq_queued(p);
051a1d1a 7349 running = task_current(rq, p);
da0c1e65 7350 if (queued)
ff77e468 7351 dequeue_task(rq, p, queue_flags);
0e1f3483 7352 if (running)
f3cd1c4e 7353 put_prev_task(rq, p);
f6b53205 7354
83ab0aa0 7355 prev_class = p->sched_class;
a509a7cd 7356
f558c2b8
PZ
7357 if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
7358 __setscheduler_params(p, attr);
7359 __setscheduler_prio(p, newprio);
7360 }
a509a7cd 7361 __setscheduler_uclamp(p, attr);
f6b53205 7362
da0c1e65 7363 if (queued) {
81a44c54
TG
7364 /*
7365 * We enqueue to tail when the priority of a task is
7366 * increased (user space view).
7367 */
ff77e468
PZ
7368 if (oldprio < p->prio)
7369 queue_flags |= ENQUEUE_HEAD;
1de64443 7370
ff77e468 7371 enqueue_task(rq, p, queue_flags);
81a44c54 7372 }
a399d233 7373 if (running)
03b7fad1 7374 set_next_task(rq, p);
cb469845 7375
da7a735e 7376 check_class_changed(rq, p, prev_class, oldprio);
d1ccc66d
IM
7377
7378 /* Avoid rq from going away on us: */
7379 preempt_disable();
565790d2 7380 head = splice_balance_callbacks(rq);
eb580751 7381 task_rq_unlock(rq, p, &rf);
b29739f9 7382
710da3c8
JL
7383 if (pi) {
7384 cpuset_read_unlock();
dbc7f069 7385 rt_mutex_adjust_pi(p);
710da3c8 7386 }
95e02ca9 7387
d1ccc66d 7388 /* Run balance callbacks after we've adjusted the PI chain: */
565790d2 7389 balance_callbacks(rq, head);
4c9a4bc8 7390 preempt_enable();
95e02ca9 7391
1da177e4 7392 return 0;
4b211f2b
MP
7393
7394unlock:
7395 task_rq_unlock(rq, p, &rf);
710da3c8
JL
7396 if (pi)
7397 cpuset_read_unlock();
4b211f2b 7398 return retval;
1da177e4 7399}
961ccddd 7400
7479f3c9
PZ
7401static int _sched_setscheduler(struct task_struct *p, int policy,
7402 const struct sched_param *param, bool check)
7403{
7404 struct sched_attr attr = {
7405 .sched_policy = policy,
7406 .sched_priority = param->sched_priority,
7407 .sched_nice = PRIO_TO_NICE(p->static_prio),
7408 };
7409
c13db6b1
SR
7410 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
7411 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7479f3c9
PZ
7412 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
7413 policy &= ~SCHED_RESET_ON_FORK;
7414 attr.sched_policy = policy;
7415 }
7416
dbc7f069 7417 return __sched_setscheduler(p, &attr, check, true);
7479f3c9 7418}
961ccddd
RR
7419/**
7420 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
7421 * @p: the task in question.
7422 * @policy: new policy.
7423 * @param: structure containing the new RT priority.
7424 *
7318d4cc
PZ
7425 * Use sched_set_fifo(), read its comment.
7426 *
e69f6186
YB
7427 * Return: 0 on success. An error code otherwise.
7428 *
961ccddd
RR
7429 * NOTE that the task may be already dead.
7430 */
7431int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 7432 const struct sched_param *param)
961ccddd 7433{
7479f3c9 7434 return _sched_setscheduler(p, policy, param, true);
961ccddd 7435}
1da177e4 7436
d50dde5a
DF
7437int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
7438{
dbc7f069 7439 return __sched_setscheduler(p, attr, true, true);
d50dde5a 7440}
d50dde5a 7441
794a56eb
JL
7442int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
7443{
7444 return __sched_setscheduler(p, attr, false, true);
7445}
1eb5dde6 7446EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
794a56eb 7447
961ccddd
RR
7448/**
7449 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
7450 * @p: the task in question.
7451 * @policy: new policy.
7452 * @param: structure containing the new RT priority.
7453 *
7454 * Just like sched_setscheduler, only don't bother checking if the
7455 * current context has permission. For example, this is needed in
7456 * stop_machine(): we create temporary high priority worker threads,
7457 * but our caller might not have that capability.
e69f6186
YB
7458 *
7459 * Return: 0 on success. An error code otherwise.
961ccddd
RR
7460 */
7461int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 7462 const struct sched_param *param)
961ccddd 7463{
7479f3c9 7464 return _sched_setscheduler(p, policy, param, false);
961ccddd
RR
7465}
7466
7318d4cc
PZ
7467/*
7468 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
7469 * incapable of resource management, which is the one thing an OS really should
7470 * be doing.
7471 *
7472 * This is of course the reason it is limited to privileged users only.
7473 *
7474 * Worse still; it is fundamentally impossible to compose static priority
7475 * workloads. You cannot take two correctly working static prio workloads
7476 * and smash them together and still expect them to work.
7477 *
7478 * For this reason 'all' FIFO tasks the kernel creates are basically at:
7479 *
7480 * MAX_RT_PRIO / 2
7481 *
7482 * The administrator _MUST_ configure the system, the kernel simply doesn't
7483 * know enough information to make a sensible choice.
7484 */
8b700983 7485void sched_set_fifo(struct task_struct *p)
7318d4cc
PZ
7486{
7487 struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
8b700983 7488 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7318d4cc
PZ
7489}
7490EXPORT_SYMBOL_GPL(sched_set_fifo);
7491
7492/*
7493 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
7494 */
8b700983 7495void sched_set_fifo_low(struct task_struct *p)
7318d4cc
PZ
7496{
7497 struct sched_param sp = { .sched_priority = 1 };
8b700983 7498 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7318d4cc
PZ
7499}
7500EXPORT_SYMBOL_GPL(sched_set_fifo_low);
7501
8b700983 7502void sched_set_normal(struct task_struct *p, int nice)
7318d4cc
PZ
7503{
7504 struct sched_attr attr = {
7505 .sched_policy = SCHED_NORMAL,
7506 .sched_nice = nice,
7507 };
8b700983 7508 WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
7318d4cc
PZ
7509}
7510EXPORT_SYMBOL_GPL(sched_set_normal);
961ccddd 7511
95cdf3b7
IM
7512static int
7513do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 7514{
1da177e4
LT
7515 struct sched_param lparam;
7516 struct task_struct *p;
36c8b586 7517 int retval;
1da177e4
LT
7518
7519 if (!param || pid < 0)
7520 return -EINVAL;
7521 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
7522 return -EFAULT;
5fe1d75f
ON
7523
7524 rcu_read_lock();
7525 retval = -ESRCH;
1da177e4 7526 p = find_process_by_pid(pid);
710da3c8
JL
7527 if (likely(p))
7528 get_task_struct(p);
5fe1d75f 7529 rcu_read_unlock();
36c8b586 7530
710da3c8
JL
7531 if (likely(p)) {
7532 retval = sched_setscheduler(p, policy, &lparam);
7533 put_task_struct(p);
7534 }
7535
1da177e4
LT
7536 return retval;
7537}
7538
d50dde5a
DF
7539/*
7540 * Mimics kernel/events/core.c perf_copy_attr().
7541 */
d1ccc66d 7542static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
d50dde5a
DF
7543{
7544 u32 size;
7545 int ret;
7546
d1ccc66d 7547 /* Zero the full structure, so that a short copy will be nice: */
d50dde5a
DF
7548 memset(attr, 0, sizeof(*attr));
7549
7550 ret = get_user(size, &uattr->size);
7551 if (ret)
7552 return ret;
7553
d1ccc66d
IM
7554 /* ABI compatibility quirk: */
7555 if (!size)
d50dde5a 7556 size = SCHED_ATTR_SIZE_VER0;
dff3a85f 7557 if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
d50dde5a
DF
7558 goto err_size;
7559
dff3a85f
AS
7560 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
7561 if (ret) {
7562 if (ret == -E2BIG)
7563 goto err_size;
7564 return ret;
d50dde5a
DF
7565 }
7566
a509a7cd
PB
7567 if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
7568 size < SCHED_ATTR_SIZE_VER1)
7569 return -EINVAL;
7570
d50dde5a 7571 /*
d1ccc66d 7572 * XXX: Do we want to be lenient like existing syscalls; or do we want
d50dde5a
DF
7573 * to be strict and return an error on out-of-bounds values?
7574 */
75e45d51 7575 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
d50dde5a 7576
e78c7bca 7577 return 0;
d50dde5a
DF
7578
7579err_size:
7580 put_user(sizeof(*attr), &uattr->size);
e78c7bca 7581 return -E2BIG;
d50dde5a
DF
7582}
7583
f4dddf90
QP
7584static void get_params(struct task_struct *p, struct sched_attr *attr)
7585{
7586 if (task_has_dl_policy(p))
7587 __getparam_dl(p, attr);
7588 else if (task_has_rt_policy(p))
7589 attr->sched_priority = p->rt_priority;
7590 else
7591 attr->sched_nice = task_nice(p);
7592}
7593
1da177e4
LT
7594/**
7595 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
7596 * @pid: the pid in question.
7597 * @policy: new policy.
7598 * @param: structure containing the new RT priority.
e69f6186
YB
7599 *
7600 * Return: 0 on success. An error code otherwise.
1da177e4 7601 */
d1ccc66d 7602SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
1da177e4 7603{
c21761f1
JB
7604 if (policy < 0)
7605 return -EINVAL;
7606
1da177e4
LT
7607 return do_sched_setscheduler(pid, policy, param);
7608}
7609
7610/**
7611 * sys_sched_setparam - set/change the RT priority of a thread
7612 * @pid: the pid in question.
7613 * @param: structure containing the new RT priority.
e69f6186
YB
7614 *
7615 * Return: 0 on success. An error code otherwise.
1da177e4 7616 */
5add95d4 7617SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 7618{
c13db6b1 7619 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
1da177e4
LT
7620}
7621
d50dde5a
DF
7622/**
7623 * sys_sched_setattr - same as above, but with extended sched_attr
7624 * @pid: the pid in question.
5778fccf 7625 * @uattr: structure containing the extended parameters.
db66d756 7626 * @flags: for future extension.
d50dde5a 7627 */
6d35ab48
PZ
7628SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
7629 unsigned int, flags)
d50dde5a
DF
7630{
7631 struct sched_attr attr;
7632 struct task_struct *p;
7633 int retval;
7634
6d35ab48 7635 if (!uattr || pid < 0 || flags)
d50dde5a
DF
7636 return -EINVAL;
7637
143cf23d
MK
7638 retval = sched_copy_attr(uattr, &attr);
7639 if (retval)
7640 return retval;
d50dde5a 7641
b14ed2c2 7642 if ((int)attr.sched_policy < 0)
dbdb2275 7643 return -EINVAL;
1d6362fa
PB
7644 if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
7645 attr.sched_policy = SETPARAM_POLICY;
d50dde5a
DF
7646
7647 rcu_read_lock();
7648 retval = -ESRCH;
7649 p = find_process_by_pid(pid);
a509a7cd
PB
7650 if (likely(p))
7651 get_task_struct(p);
d50dde5a
DF
7652 rcu_read_unlock();
7653
a509a7cd 7654 if (likely(p)) {
f4dddf90
QP
7655 if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
7656 get_params(p, &attr);
a509a7cd
PB
7657 retval = sched_setattr(p, &attr);
7658 put_task_struct(p);
7659 }
7660
d50dde5a
DF
7661 return retval;
7662}
7663
1da177e4
LT
7664/**
7665 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
7666 * @pid: the pid in question.
e69f6186
YB
7667 *
7668 * Return: On success, the policy of the thread. Otherwise, a negative error
7669 * code.
1da177e4 7670 */
5add95d4 7671SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 7672{
36c8b586 7673 struct task_struct *p;
3a5c359a 7674 int retval;
1da177e4
LT
7675
7676 if (pid < 0)
3a5c359a 7677 return -EINVAL;
1da177e4
LT
7678
7679 retval = -ESRCH;
5fe85be0 7680 rcu_read_lock();
1da177e4
LT
7681 p = find_process_by_pid(pid);
7682 if (p) {
7683 retval = security_task_getscheduler(p);
7684 if (!retval)
ca94c442
LP
7685 retval = p->policy
7686 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 7687 }
5fe85be0 7688 rcu_read_unlock();
1da177e4
LT
7689 return retval;
7690}
7691
7692/**
ca94c442 7693 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
7694 * @pid: the pid in question.
7695 * @param: structure containing the RT priority.
e69f6186
YB
7696 *
7697 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
7698 * code.
1da177e4 7699 */
5add95d4 7700SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 7701{
ce5f7f82 7702 struct sched_param lp = { .sched_priority = 0 };
36c8b586 7703 struct task_struct *p;
3a5c359a 7704 int retval;
1da177e4
LT
7705
7706 if (!param || pid < 0)
3a5c359a 7707 return -EINVAL;
1da177e4 7708
5fe85be0 7709 rcu_read_lock();
1da177e4
LT
7710 p = find_process_by_pid(pid);
7711 retval = -ESRCH;
7712 if (!p)
7713 goto out_unlock;
7714
7715 retval = security_task_getscheduler(p);
7716 if (retval)
7717 goto out_unlock;
7718
ce5f7f82
PZ
7719 if (task_has_rt_policy(p))
7720 lp.sched_priority = p->rt_priority;
5fe85be0 7721 rcu_read_unlock();
1da177e4
LT
7722
7723 /*
7724 * This one might sleep, we cannot do it with a spinlock held ...
7725 */
7726 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
7727
1da177e4
LT
7728 return retval;
7729
7730out_unlock:
5fe85be0 7731 rcu_read_unlock();
1da177e4
LT
7732 return retval;
7733}
7734
1251201c
IM
7735/*
7736 * Copy the kernel size attribute structure (which might be larger
7737 * than what user-space knows about) to user-space.
7738 *
7739 * Note that all cases are valid: user-space buffer can be larger or
7740 * smaller than the kernel-space buffer. The usual case is that both
7741 * have the same size.
7742 */
7743static int
7744sched_attr_copy_to_user(struct sched_attr __user *uattr,
7745 struct sched_attr *kattr,
7746 unsigned int usize)
d50dde5a 7747{
1251201c 7748 unsigned int ksize = sizeof(*kattr);
d50dde5a 7749
96d4f267 7750 if (!access_ok(uattr, usize))
d50dde5a
DF
7751 return -EFAULT;
7752
7753 /*
1251201c
IM
7754 * sched_getattr() ABI forwards and backwards compatibility:
7755 *
7756 * If usize == ksize then we just copy everything to user-space and all is good.
7757 *
7758 * If usize < ksize then we only copy as much as user-space has space for,
7759 * this keeps ABI compatibility as well. We skip the rest.
7760 *
7761 * If usize > ksize then user-space is using a newer version of the ABI,
7762 * which part the kernel doesn't know about. Just ignore it - tooling can
7763 * detect the kernel's knowledge of attributes from the attr->size value
7764 * which is set to ksize in this case.
d50dde5a 7765 */
1251201c 7766 kattr->size = min(usize, ksize);
d50dde5a 7767
1251201c 7768 if (copy_to_user(uattr, kattr, kattr->size))
d50dde5a
DF
7769 return -EFAULT;
7770
22400674 7771 return 0;
d50dde5a
DF
7772}
7773
7774/**
aab03e05 7775 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
d50dde5a 7776 * @pid: the pid in question.
5778fccf 7777 * @uattr: structure containing the extended parameters.
dff3a85f 7778 * @usize: sizeof(attr) for fwd/bwd comp.
db66d756 7779 * @flags: for future extension.
d50dde5a 7780 */
6d35ab48 7781SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
1251201c 7782 unsigned int, usize, unsigned int, flags)
d50dde5a 7783{
1251201c 7784 struct sched_attr kattr = { };
d50dde5a
DF
7785 struct task_struct *p;
7786 int retval;
7787
1251201c
IM
7788 if (!uattr || pid < 0 || usize > PAGE_SIZE ||
7789 usize < SCHED_ATTR_SIZE_VER0 || flags)
d50dde5a
DF
7790 return -EINVAL;
7791
7792 rcu_read_lock();
7793 p = find_process_by_pid(pid);
7794 retval = -ESRCH;
7795 if (!p)
7796 goto out_unlock;
7797
7798 retval = security_task_getscheduler(p);
7799 if (retval)
7800 goto out_unlock;
7801
1251201c 7802 kattr.sched_policy = p->policy;
7479f3c9 7803 if (p->sched_reset_on_fork)
1251201c 7804 kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
f4dddf90 7805 get_params(p, &kattr);
7ad721bf 7806 kattr.sched_flags &= SCHED_FLAG_ALL;
d50dde5a 7807
a509a7cd 7808#ifdef CONFIG_UCLAMP_TASK
13685c4a
QY
7809 /*
7810 * This could race with another potential updater, but this is fine
7811 * because it'll correctly read the old or the new value. We don't need
7812 * to guarantee who wins the race as long as it doesn't return garbage.
7813 */
1251201c
IM
7814 kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
7815 kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
a509a7cd
PB
7816#endif
7817
d50dde5a
DF
7818 rcu_read_unlock();
7819
1251201c 7820 return sched_attr_copy_to_user(uattr, &kattr, usize);
d50dde5a
DF
7821
7822out_unlock:
7823 rcu_read_unlock();
7824 return retval;
7825}
7826
234b8ab6
WD
7827#ifdef CONFIG_SMP
7828int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
1da177e4 7829{
234b8ab6
WD
7830 int ret = 0;
7831
7832 /*
7833 * If the task isn't a deadline task or admission control is
7834 * disabled then we don't care about affinity changes.
7835 */
7836 if (!task_has_dl_policy(p) || !dl_bandwidth_enabled())
7837 return 0;
7838
7839 /*
7840 * Since bandwidth control happens on root_domain basis,
7841 * if admission test is enabled, we only admit -deadline
7842 * tasks allowed to run on all the CPUs in the task's
7843 * root_domain.
7844 */
7845 rcu_read_lock();
7846 if (!cpumask_subset(task_rq(p)->rd->span, mask))
7847 ret = -EBUSY;
7848 rcu_read_unlock();
7849 return ret;
7850}
7851#endif
7852
db3b02ae
WD
7853static int
7854__sched_setaffinity(struct task_struct *p, const struct cpumask *mask)
1da177e4 7855{
36c8b586 7856 int retval;
5a16f3d3 7857 cpumask_var_t cpus_allowed, new_mask;
1da177e4 7858
db3b02ae
WD
7859 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL))
7860 return -ENOMEM;
1da177e4 7861
5a16f3d3
RR
7862 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
7863 retval = -ENOMEM;
7864 goto out_free_cpus_allowed;
7865 }
e4099a5e
PZ
7866
7867 cpuset_cpus_allowed(p, cpus_allowed);
db3b02ae 7868 cpumask_and(new_mask, mask, cpus_allowed);
e4099a5e 7869
234b8ab6
WD
7870 retval = dl_task_check_affinity(p, new_mask);
7871 if (retval)
7872 goto out_free_new_mask;
49246274 7873again:
07ec77a1 7874 retval = __set_cpus_allowed_ptr(p, new_mask, SCA_CHECK | SCA_USER);
db3b02ae
WD
7875 if (retval)
7876 goto out_free_new_mask;
1da177e4 7877
db3b02ae
WD
7878 cpuset_cpus_allowed(p, cpus_allowed);
7879 if (!cpumask_subset(new_mask, cpus_allowed)) {
7880 /*
7881 * We must have raced with a concurrent cpuset update.
7882 * Just reset the cpumask to the cpuset's cpus_allowed.
7883 */
7884 cpumask_copy(new_mask, cpus_allowed);
7885 goto again;
8707d8b8 7886 }
db3b02ae 7887
16303ab2 7888out_free_new_mask:
5a16f3d3
RR
7889 free_cpumask_var(new_mask);
7890out_free_cpus_allowed:
7891 free_cpumask_var(cpus_allowed);
db3b02ae
WD
7892 return retval;
7893}
7894
7895long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
7896{
36c8b586
IM
7897 struct task_struct *p;
7898 int retval;
1da177e4 7899
23f5d142 7900 rcu_read_lock();
1da177e4
LT
7901
7902 p = find_process_by_pid(pid);
7903 if (!p) {
23f5d142 7904 rcu_read_unlock();
1da177e4
LT
7905 return -ESRCH;
7906 }
7907
23f5d142 7908 /* Prevent p going away */
1da177e4 7909 get_task_struct(p);
23f5d142 7910 rcu_read_unlock();
1da177e4 7911
14a40ffc
TH
7912 if (p->flags & PF_NO_SETAFFINITY) {
7913 retval = -EINVAL;
7914 goto out_put_task;
7915 }
db3b02ae 7916
4c44aaaf
EB
7917 if (!check_same_owner(p)) {
7918 rcu_read_lock();
7919 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
7920 rcu_read_unlock();
db3b02ae
WD
7921 retval = -EPERM;
7922 goto out_put_task;
4c44aaaf
EB
7923 }
7924 rcu_read_unlock();
7925 }
1da177e4 7926
b0ae1981 7927 retval = security_task_setscheduler(p);
e7834f8f 7928 if (retval)
db3b02ae 7929 goto out_put_task;
1da177e4 7930
db3b02ae 7931 retval = __sched_setaffinity(p, in_mask);
5a16f3d3 7932out_put_task:
1da177e4 7933 put_task_struct(p);
1da177e4
LT
7934 return retval;
7935}
7936
7937static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 7938 struct cpumask *new_mask)
1da177e4 7939{
96f874e2
RR
7940 if (len < cpumask_size())
7941 cpumask_clear(new_mask);
7942 else if (len > cpumask_size())
7943 len = cpumask_size();
7944
1da177e4
LT
7945 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
7946}
7947
7948/**
d1ccc66d 7949 * sys_sched_setaffinity - set the CPU affinity of a process
1da177e4
LT
7950 * @pid: pid of the process
7951 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 7952 * @user_mask_ptr: user-space pointer to the new CPU mask
e69f6186
YB
7953 *
7954 * Return: 0 on success. An error code otherwise.
1da177e4 7955 */
5add95d4
HC
7956SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
7957 unsigned long __user *, user_mask_ptr)
1da177e4 7958{
5a16f3d3 7959 cpumask_var_t new_mask;
1da177e4
LT
7960 int retval;
7961
5a16f3d3
RR
7962 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
7963 return -ENOMEM;
1da177e4 7964
5a16f3d3
RR
7965 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
7966 if (retval == 0)
7967 retval = sched_setaffinity(pid, new_mask);
7968 free_cpumask_var(new_mask);
7969 return retval;
1da177e4
LT
7970}
7971
96f874e2 7972long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 7973{
36c8b586 7974 struct task_struct *p;
31605683 7975 unsigned long flags;
1da177e4 7976 int retval;
1da177e4 7977
23f5d142 7978 rcu_read_lock();
1da177e4
LT
7979
7980 retval = -ESRCH;
7981 p = find_process_by_pid(pid);
7982 if (!p)
7983 goto out_unlock;
7984
e7834f8f
DQ
7985 retval = security_task_getscheduler(p);
7986 if (retval)
7987 goto out_unlock;
7988
013fdb80 7989 raw_spin_lock_irqsave(&p->pi_lock, flags);
3bd37062 7990 cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
013fdb80 7991 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
7992
7993out_unlock:
23f5d142 7994 rcu_read_unlock();
1da177e4 7995
9531b62f 7996 return retval;
1da177e4
LT
7997}
7998
7999/**
d1ccc66d 8000 * sys_sched_getaffinity - get the CPU affinity of a process
1da177e4
LT
8001 * @pid: pid of the process
8002 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 8003 * @user_mask_ptr: user-space pointer to hold the current CPU mask
e69f6186 8004 *
599b4840
ZW
8005 * Return: size of CPU mask copied to user_mask_ptr on success. An
8006 * error code otherwise.
1da177e4 8007 */
5add95d4
HC
8008SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
8009 unsigned long __user *, user_mask_ptr)
1da177e4
LT
8010{
8011 int ret;
f17c8607 8012 cpumask_var_t mask;
1da177e4 8013
84fba5ec 8014 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
8015 return -EINVAL;
8016 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
8017 return -EINVAL;
8018
f17c8607
RR
8019 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
8020 return -ENOMEM;
1da177e4 8021
f17c8607
RR
8022 ret = sched_getaffinity(pid, mask);
8023 if (ret == 0) {
4de373a1 8024 unsigned int retlen = min(len, cpumask_size());
cd3d8031
KM
8025
8026 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
8027 ret = -EFAULT;
8028 else
cd3d8031 8029 ret = retlen;
f17c8607
RR
8030 }
8031 free_cpumask_var(mask);
1da177e4 8032
f17c8607 8033 return ret;
1da177e4
LT
8034}
8035
7d4dd4f1 8036static void do_sched_yield(void)
1da177e4 8037{
8a8c69c3
PZ
8038 struct rq_flags rf;
8039 struct rq *rq;
8040
246b3b33 8041 rq = this_rq_lock_irq(&rf);
1da177e4 8042
ae92882e 8043 schedstat_inc(rq->yld_count);
4530d7ab 8044 current->sched_class->yield_task(rq);
1da177e4 8045
8a8c69c3 8046 preempt_disable();
345a957f 8047 rq_unlock_irq(rq, &rf);
ba74c144 8048 sched_preempt_enable_no_resched();
1da177e4
LT
8049
8050 schedule();
7d4dd4f1 8051}
1da177e4 8052
59a74b15
MCC
8053/**
8054 * sys_sched_yield - yield the current processor to other threads.
8055 *
8056 * This function yields the current CPU to other tasks. If there are no
8057 * other threads running on this CPU then this function will return.
8058 *
8059 * Return: 0.
8060 */
7d4dd4f1
DB
8061SYSCALL_DEFINE0(sched_yield)
8062{
8063 do_sched_yield();
1da177e4
LT
8064 return 0;
8065}
8066
b965f1dd
PZI
8067#if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
8068int __sched __cond_resched(void)
1da177e4 8069{
fe32d3cd 8070 if (should_resched(0)) {
a18b5d01 8071 preempt_schedule_common();
1da177e4
LT
8072 return 1;
8073 }
50895825
FW
8074 /*
8075 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
8076 * whether the current CPU is in an RCU read-side critical section,
8077 * so the tick can report quiescent states even for CPUs looping
8078 * in kernel context. In contrast, in non-preemptible kernels,
8079 * RCU readers leave no in-memory hints, which means that CPU-bound
8080 * processes executing in kernel context might never report an
8081 * RCU quiescent state. Therefore, the following code causes
8082 * cond_resched() to report a quiescent state, but only when RCU
8083 * is in urgent need of one.
8084 */
b965f1dd 8085#ifndef CONFIG_PREEMPT_RCU
f79c3ad6 8086 rcu_all_qs();
b965f1dd 8087#endif
1da177e4
LT
8088 return 0;
8089}
b965f1dd
PZI
8090EXPORT_SYMBOL(__cond_resched);
8091#endif
8092
8093#ifdef CONFIG_PREEMPT_DYNAMIC
99cf983c 8094#if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8a69fe0b
MR
8095#define cond_resched_dynamic_enabled __cond_resched
8096#define cond_resched_dynamic_disabled ((void *)&__static_call_return0)
b965f1dd 8097DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
ef72661e 8098EXPORT_STATIC_CALL_TRAMP(cond_resched);
b965f1dd 8099
8a69fe0b
MR
8100#define might_resched_dynamic_enabled __cond_resched
8101#define might_resched_dynamic_disabled ((void *)&__static_call_return0)
b965f1dd 8102DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
ef72661e 8103EXPORT_STATIC_CALL_TRAMP(might_resched);
99cf983c
MR
8104#elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8105static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
8106int __sched dynamic_cond_resched(void)
8107{
8108 if (!static_branch_unlikely(&sk_dynamic_cond_resched))
8109 return 0;
8110 return __cond_resched();
8111}
8112EXPORT_SYMBOL(dynamic_cond_resched);
8113
8114static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
8115int __sched dynamic_might_resched(void)
8116{
8117 if (!static_branch_unlikely(&sk_dynamic_might_resched))
8118 return 0;
8119 return __cond_resched();
8120}
8121EXPORT_SYMBOL(dynamic_might_resched);
8122#endif
35a773a0 8123#endif
1da177e4
LT
8124
8125/*
613afbf8 8126 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
8127 * call schedule, and on return reacquire the lock.
8128 *
c1a280b6 8129 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
1da177e4
LT
8130 * operations here to prevent schedule() from being called twice (once via
8131 * spin_unlock(), once by hand).
8132 */
613afbf8 8133int __cond_resched_lock(spinlock_t *lock)
1da177e4 8134{
fe32d3cd 8135 int resched = should_resched(PREEMPT_LOCK_OFFSET);
6df3cecb
JK
8136 int ret = 0;
8137
f607c668
PZ
8138 lockdep_assert_held(lock);
8139
4a81e832 8140 if (spin_needbreak(lock) || resched) {
1da177e4 8141 spin_unlock(lock);
d86ee480 8142 if (resched)
a18b5d01 8143 preempt_schedule_common();
95c354fe
NP
8144 else
8145 cpu_relax();
6df3cecb 8146 ret = 1;
1da177e4 8147 spin_lock(lock);
1da177e4 8148 }
6df3cecb 8149 return ret;
1da177e4 8150}
613afbf8 8151EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 8152
f3d4b4b1
BG
8153int __cond_resched_rwlock_read(rwlock_t *lock)
8154{
8155 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8156 int ret = 0;
8157
8158 lockdep_assert_held_read(lock);
8159
8160 if (rwlock_needbreak(lock) || resched) {
8161 read_unlock(lock);
8162 if (resched)
8163 preempt_schedule_common();
8164 else
8165 cpu_relax();
8166 ret = 1;
8167 read_lock(lock);
8168 }
8169 return ret;
8170}
8171EXPORT_SYMBOL(__cond_resched_rwlock_read);
8172
8173int __cond_resched_rwlock_write(rwlock_t *lock)
8174{
8175 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8176 int ret = 0;
8177
8178 lockdep_assert_held_write(lock);
8179
8180 if (rwlock_needbreak(lock) || resched) {
8181 write_unlock(lock);
8182 if (resched)
8183 preempt_schedule_common();
8184 else
8185 cpu_relax();
8186 ret = 1;
8187 write_lock(lock);
8188 }
8189 return ret;
8190}
8191EXPORT_SYMBOL(__cond_resched_rwlock_write);
8192
4c748558
MR
8193#ifdef CONFIG_PREEMPT_DYNAMIC
8194
33c64734 8195#ifdef CONFIG_GENERIC_ENTRY
4c748558 8196#include <linux/entry-common.h>
33c64734 8197#endif
4c748558
MR
8198
8199/*
8200 * SC:cond_resched
8201 * SC:might_resched
8202 * SC:preempt_schedule
8203 * SC:preempt_schedule_notrace
8204 * SC:irqentry_exit_cond_resched
8205 *
8206 *
8207 * NONE:
8208 * cond_resched <- __cond_resched
8209 * might_resched <- RET0
8210 * preempt_schedule <- NOP
8211 * preempt_schedule_notrace <- NOP
8212 * irqentry_exit_cond_resched <- NOP
8213 *
8214 * VOLUNTARY:
8215 * cond_resched <- __cond_resched
8216 * might_resched <- __cond_resched
8217 * preempt_schedule <- NOP
8218 * preempt_schedule_notrace <- NOP
8219 * irqentry_exit_cond_resched <- NOP
8220 *
8221 * FULL:
8222 * cond_resched <- RET0
8223 * might_resched <- RET0
8224 * preempt_schedule <- preempt_schedule
8225 * preempt_schedule_notrace <- preempt_schedule_notrace
8226 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
8227 */
8228
8229enum {
8230 preempt_dynamic_undefined = -1,
8231 preempt_dynamic_none,
8232 preempt_dynamic_voluntary,
8233 preempt_dynamic_full,
8234};
8235
8236int preempt_dynamic_mode = preempt_dynamic_undefined;
8237
8238int sched_dynamic_mode(const char *str)
8239{
8240 if (!strcmp(str, "none"))
8241 return preempt_dynamic_none;
8242
8243 if (!strcmp(str, "voluntary"))
8244 return preempt_dynamic_voluntary;
8245
8246 if (!strcmp(str, "full"))
8247 return preempt_dynamic_full;
8248
8249 return -EINVAL;
8250}
8251
99cf983c 8252#if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8a69fe0b
MR
8253#define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled)
8254#define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled)
99cf983c
MR
8255#elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8256#define preempt_dynamic_enable(f) static_key_enable(&sk_dynamic_##f.key)
8257#define preempt_dynamic_disable(f) static_key_disable(&sk_dynamic_##f.key)
8258#else
8259#error "Unsupported PREEMPT_DYNAMIC mechanism"
8260#endif
8a69fe0b 8261
4c748558
MR
8262void sched_dynamic_update(int mode)
8263{
8264 /*
8265 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
8266 * the ZERO state, which is invalid.
8267 */
8a69fe0b
MR
8268 preempt_dynamic_enable(cond_resched);
8269 preempt_dynamic_enable(might_resched);
8270 preempt_dynamic_enable(preempt_schedule);
8271 preempt_dynamic_enable(preempt_schedule_notrace);
8272 preempt_dynamic_enable(irqentry_exit_cond_resched);
4c748558
MR
8273
8274 switch (mode) {
8275 case preempt_dynamic_none:
8a69fe0b
MR
8276 preempt_dynamic_enable(cond_resched);
8277 preempt_dynamic_disable(might_resched);
8278 preempt_dynamic_disable(preempt_schedule);
8279 preempt_dynamic_disable(preempt_schedule_notrace);
8280 preempt_dynamic_disable(irqentry_exit_cond_resched);
4c748558
MR
8281 pr_info("Dynamic Preempt: none\n");
8282 break;
8283
8284 case preempt_dynamic_voluntary:
8a69fe0b
MR
8285 preempt_dynamic_enable(cond_resched);
8286 preempt_dynamic_enable(might_resched);
8287 preempt_dynamic_disable(preempt_schedule);
8288 preempt_dynamic_disable(preempt_schedule_notrace);
8289 preempt_dynamic_disable(irqentry_exit_cond_resched);
4c748558
MR
8290 pr_info("Dynamic Preempt: voluntary\n");
8291 break;
8292
8293 case preempt_dynamic_full:
8a69fe0b
MR
8294 preempt_dynamic_disable(cond_resched);
8295 preempt_dynamic_disable(might_resched);
8296 preempt_dynamic_enable(preempt_schedule);
8297 preempt_dynamic_enable(preempt_schedule_notrace);
8298 preempt_dynamic_enable(irqentry_exit_cond_resched);
4c748558
MR
8299 pr_info("Dynamic Preempt: full\n");
8300 break;
8301 }
8302
8303 preempt_dynamic_mode = mode;
8304}
8305
8306static int __init setup_preempt_mode(char *str)
8307{
8308 int mode = sched_dynamic_mode(str);
8309 if (mode < 0) {
8310 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
8311 return 0;
8312 }
8313
8314 sched_dynamic_update(mode);
8315 return 1;
8316}
8317__setup("preempt=", setup_preempt_mode);
8318
8319static void __init preempt_dynamic_init(void)
8320{
8321 if (preempt_dynamic_mode == preempt_dynamic_undefined) {
8322 if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
8323 sched_dynamic_update(preempt_dynamic_none);
8324 } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
8325 sched_dynamic_update(preempt_dynamic_voluntary);
8326 } else {
8327 /* Default static call setting, nothing to do */
8328 WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
8329 preempt_dynamic_mode = preempt_dynamic_full;
8330 pr_info("Dynamic Preempt: full\n");
8331 }
8332 }
8333}
8334
8335#else /* !CONFIG_PREEMPT_DYNAMIC */
8336
8337static inline void preempt_dynamic_init(void) { }
8338
8339#endif /* #ifdef CONFIG_PREEMPT_DYNAMIC */
8340
1da177e4
LT
8341/**
8342 * yield - yield the current processor to other threads.
8343 *
8e3fabfd
PZ
8344 * Do not ever use this function, there's a 99% chance you're doing it wrong.
8345 *
8346 * The scheduler is at all times free to pick the calling task as the most
8347 * eligible task to run, if removing the yield() call from your code breaks
b19a888c 8348 * it, it's already broken.
8e3fabfd
PZ
8349 *
8350 * Typical broken usage is:
8351 *
8352 * while (!event)
d1ccc66d 8353 * yield();
8e3fabfd
PZ
8354 *
8355 * where one assumes that yield() will let 'the other' process run that will
8356 * make event true. If the current task is a SCHED_FIFO task that will never
8357 * happen. Never use yield() as a progress guarantee!!
8358 *
8359 * If you want to use yield() to wait for something, use wait_event().
8360 * If you want to use yield() to be 'nice' for others, use cond_resched().
8361 * If you still want to use yield(), do not!
1da177e4
LT
8362 */
8363void __sched yield(void)
8364{
8365 set_current_state(TASK_RUNNING);
7d4dd4f1 8366 do_sched_yield();
1da177e4 8367}
1da177e4
LT
8368EXPORT_SYMBOL(yield);
8369
d95f4122
MG
8370/**
8371 * yield_to - yield the current processor to another thread in
8372 * your thread group, or accelerate that thread toward the
8373 * processor it's on.
16addf95
RD
8374 * @p: target task
8375 * @preempt: whether task preemption is allowed or not
d95f4122
MG
8376 *
8377 * It's the caller's job to ensure that the target task struct
8378 * can't go away on us before we can do any checks.
8379 *
e69f6186 8380 * Return:
7b270f60
PZ
8381 * true (>0) if we indeed boosted the target task.
8382 * false (0) if we failed to boost the target.
8383 * -ESRCH if there's no task to yield to.
d95f4122 8384 */
fa93384f 8385int __sched yield_to(struct task_struct *p, bool preempt)
d95f4122
MG
8386{
8387 struct task_struct *curr = current;
8388 struct rq *rq, *p_rq;
8389 unsigned long flags;
c3c18640 8390 int yielded = 0;
d95f4122
MG
8391
8392 local_irq_save(flags);
8393 rq = this_rq();
8394
8395again:
8396 p_rq = task_rq(p);
7b270f60
PZ
8397 /*
8398 * If we're the only runnable task on the rq and target rq also
8399 * has only one task, there's absolutely no point in yielding.
8400 */
8401 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
8402 yielded = -ESRCH;
8403 goto out_irq;
8404 }
8405
d95f4122 8406 double_rq_lock(rq, p_rq);
39e24d8f 8407 if (task_rq(p) != p_rq) {
d95f4122
MG
8408 double_rq_unlock(rq, p_rq);
8409 goto again;
8410 }
8411
8412 if (!curr->sched_class->yield_to_task)
7b270f60 8413 goto out_unlock;
d95f4122
MG
8414
8415 if (curr->sched_class != p->sched_class)
7b270f60 8416 goto out_unlock;
d95f4122 8417
b03fbd4f 8418 if (task_running(p_rq, p) || !task_is_running(p))
7b270f60 8419 goto out_unlock;
d95f4122 8420
0900acf2 8421 yielded = curr->sched_class->yield_to_task(rq, p);
6d1cafd8 8422 if (yielded) {
ae92882e 8423 schedstat_inc(rq->yld_count);
6d1cafd8
VP
8424 /*
8425 * Make p's CPU reschedule; pick_next_entity takes care of
8426 * fairness.
8427 */
8428 if (preempt && rq != p_rq)
8875125e 8429 resched_curr(p_rq);
6d1cafd8 8430 }
d95f4122 8431
7b270f60 8432out_unlock:
d95f4122 8433 double_rq_unlock(rq, p_rq);
7b270f60 8434out_irq:
d95f4122
MG
8435 local_irq_restore(flags);
8436
7b270f60 8437 if (yielded > 0)
d95f4122
MG
8438 schedule();
8439
8440 return yielded;
8441}
8442EXPORT_SYMBOL_GPL(yield_to);
8443
10ab5643
TH
8444int io_schedule_prepare(void)
8445{
8446 int old_iowait = current->in_iowait;
8447
8448 current->in_iowait = 1;
008f75a2
CH
8449 if (current->plug)
8450 blk_flush_plug(current->plug, true);
10ab5643
TH
8451
8452 return old_iowait;
8453}
8454
8455void io_schedule_finish(int token)
8456{
8457 current->in_iowait = token;
8458}
8459
1da177e4 8460/*
41a2d6cf 8461 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 8462 * that process accounting knows that this is a task in IO wait state.
1da177e4 8463 */
1da177e4
LT
8464long __sched io_schedule_timeout(long timeout)
8465{
10ab5643 8466 int token;
1da177e4
LT
8467 long ret;
8468
10ab5643 8469 token = io_schedule_prepare();
1da177e4 8470 ret = schedule_timeout(timeout);
10ab5643 8471 io_schedule_finish(token);
9cff8ade 8472
1da177e4
LT
8473 return ret;
8474}
9cff8ade 8475EXPORT_SYMBOL(io_schedule_timeout);
1da177e4 8476
e3b929b0 8477void __sched io_schedule(void)
10ab5643
TH
8478{
8479 int token;
8480
8481 token = io_schedule_prepare();
8482 schedule();
8483 io_schedule_finish(token);
8484}
8485EXPORT_SYMBOL(io_schedule);
8486
1da177e4
LT
8487/**
8488 * sys_sched_get_priority_max - return maximum RT priority.
8489 * @policy: scheduling class.
8490 *
e69f6186
YB
8491 * Return: On success, this syscall returns the maximum
8492 * rt_priority that can be used by a given scheduling class.
8493 * On failure, a negative error code is returned.
1da177e4 8494 */
5add95d4 8495SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
8496{
8497 int ret = -EINVAL;
8498
8499 switch (policy) {
8500 case SCHED_FIFO:
8501 case SCHED_RR:
ae18ad28 8502 ret = MAX_RT_PRIO-1;
1da177e4 8503 break;
aab03e05 8504 case SCHED_DEADLINE:
1da177e4 8505 case SCHED_NORMAL:
b0a9499c 8506 case SCHED_BATCH:
dd41f596 8507 case SCHED_IDLE:
1da177e4
LT
8508 ret = 0;
8509 break;
8510 }
8511 return ret;
8512}
8513
8514/**
8515 * sys_sched_get_priority_min - return minimum RT priority.
8516 * @policy: scheduling class.
8517 *
e69f6186
YB
8518 * Return: On success, this syscall returns the minimum
8519 * rt_priority that can be used by a given scheduling class.
8520 * On failure, a negative error code is returned.
1da177e4 8521 */
5add95d4 8522SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
8523{
8524 int ret = -EINVAL;
8525
8526 switch (policy) {
8527 case SCHED_FIFO:
8528 case SCHED_RR:
8529 ret = 1;
8530 break;
aab03e05 8531 case SCHED_DEADLINE:
1da177e4 8532 case SCHED_NORMAL:
b0a9499c 8533 case SCHED_BATCH:
dd41f596 8534 case SCHED_IDLE:
1da177e4
LT
8535 ret = 0;
8536 }
8537 return ret;
8538}
8539
abca5fc5 8540static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
1da177e4 8541{
36c8b586 8542 struct task_struct *p;
a4ec24b4 8543 unsigned int time_slice;
eb580751 8544 struct rq_flags rf;
dba091b9 8545 struct rq *rq;
3a5c359a 8546 int retval;
1da177e4
LT
8547
8548 if (pid < 0)
3a5c359a 8549 return -EINVAL;
1da177e4
LT
8550
8551 retval = -ESRCH;
1a551ae7 8552 rcu_read_lock();
1da177e4
LT
8553 p = find_process_by_pid(pid);
8554 if (!p)
8555 goto out_unlock;
8556
8557 retval = security_task_getscheduler(p);
8558 if (retval)
8559 goto out_unlock;
8560
eb580751 8561 rq = task_rq_lock(p, &rf);
a57beec5
PZ
8562 time_slice = 0;
8563 if (p->sched_class->get_rr_interval)
8564 time_slice = p->sched_class->get_rr_interval(rq, p);
eb580751 8565 task_rq_unlock(rq, p, &rf);
a4ec24b4 8566
1a551ae7 8567 rcu_read_unlock();
abca5fc5
AV
8568 jiffies_to_timespec64(time_slice, t);
8569 return 0;
3a5c359a 8570
1da177e4 8571out_unlock:
1a551ae7 8572 rcu_read_unlock();
1da177e4
LT
8573 return retval;
8574}
8575
2064a5ab
RD
8576/**
8577 * sys_sched_rr_get_interval - return the default timeslice of a process.
8578 * @pid: pid of the process.
8579 * @interval: userspace pointer to the timeslice value.
8580 *
8581 * this syscall writes the default timeslice value of a given process
8582 * into the user-space timespec buffer. A value of '0' means infinity.
8583 *
8584 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
8585 * an error code.
8586 */
abca5fc5 8587SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
474b9c77 8588 struct __kernel_timespec __user *, interval)
abca5fc5
AV
8589{
8590 struct timespec64 t;
8591 int retval = sched_rr_get_interval(pid, &t);
8592
8593 if (retval == 0)
8594 retval = put_timespec64(&t, interval);
8595
8596 return retval;
8597}
8598
474b9c77 8599#ifdef CONFIG_COMPAT_32BIT_TIME
8dabe724
AB
8600SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
8601 struct old_timespec32 __user *, interval)
abca5fc5
AV
8602{
8603 struct timespec64 t;
8604 int retval = sched_rr_get_interval(pid, &t);
8605
8606 if (retval == 0)
9afc5eee 8607 retval = put_old_timespec32(&t, interval);
abca5fc5
AV
8608 return retval;
8609}
8610#endif
8611
82a1fcb9 8612void sched_show_task(struct task_struct *p)
1da177e4 8613{
1da177e4 8614 unsigned long free = 0;
4e79752c 8615 int ppid;
c930b2c0 8616
38200502
TH
8617 if (!try_get_task_stack(p))
8618 return;
20435d84 8619
cc172ff3 8620 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
20435d84 8621
b03fbd4f 8622 if (task_is_running(p))
cc172ff3 8623 pr_cont(" running task ");
1da177e4 8624#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 8625 free = stack_not_used(p);
1da177e4 8626#endif
a90e984c 8627 ppid = 0;
4e79752c 8628 rcu_read_lock();
a90e984c
ON
8629 if (pid_alive(p))
8630 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4e79752c 8631 rcu_read_unlock();
cc172ff3
LZ
8632 pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
8633 free, task_pid_nr(p), ppid,
0569b245 8634 read_task_thread_flags(p));
1da177e4 8635
3d1cb205 8636 print_worker_info(KERN_INFO, p);
a8b62fd0 8637 print_stop_info(KERN_INFO, p);
9cb8f069 8638 show_stack(p, NULL, KERN_INFO);
38200502 8639 put_task_stack(p);
1da177e4 8640}
0032f4e8 8641EXPORT_SYMBOL_GPL(sched_show_task);
1da177e4 8642
5d68cc95
PZ
8643static inline bool
8644state_filter_match(unsigned long state_filter, struct task_struct *p)
8645{
2f064a59
PZ
8646 unsigned int state = READ_ONCE(p->__state);
8647
5d68cc95
PZ
8648 /* no filter, everything matches */
8649 if (!state_filter)
8650 return true;
8651
8652 /* filter, but doesn't match */
2f064a59 8653 if (!(state & state_filter))
5d68cc95
PZ
8654 return false;
8655
8656 /*
8657 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
8658 * TASK_KILLABLE).
8659 */
2f064a59 8660 if (state_filter == TASK_UNINTERRUPTIBLE && state == TASK_IDLE)
5d68cc95
PZ
8661 return false;
8662
8663 return true;
8664}
8665
8666
2f064a59 8667void show_state_filter(unsigned int state_filter)
1da177e4 8668{
36c8b586 8669 struct task_struct *g, *p;
1da177e4 8670
510f5acc 8671 rcu_read_lock();
5d07f420 8672 for_each_process_thread(g, p) {
1da177e4
LT
8673 /*
8674 * reset the NMI-timeout, listing all files on a slow
25985edc 8675 * console might take a lot of time:
57675cb9
AR
8676 * Also, reset softlockup watchdogs on all CPUs, because
8677 * another CPU might be blocked waiting for us to process
8678 * an IPI.
1da177e4
LT
8679 */
8680 touch_nmi_watchdog();
57675cb9 8681 touch_all_softlockup_watchdogs();
5d68cc95 8682 if (state_filter_match(state_filter, p))
82a1fcb9 8683 sched_show_task(p);
5d07f420 8684 }
1da177e4 8685
dd41f596 8686#ifdef CONFIG_SCHED_DEBUG
fb90a6e9
RV
8687 if (!state_filter)
8688 sysrq_sched_debug_show();
dd41f596 8689#endif
510f5acc 8690 rcu_read_unlock();
e59e2ae2
IM
8691 /*
8692 * Only show locks if all tasks are dumped:
8693 */
93335a21 8694 if (!state_filter)
e59e2ae2 8695 debug_show_all_locks();
1da177e4
LT
8696}
8697
f340c0d1
IM
8698/**
8699 * init_idle - set up an idle thread for a given CPU
8700 * @idle: task in question
d1ccc66d 8701 * @cpu: CPU the idle task belongs to
f340c0d1
IM
8702 *
8703 * NOTE: this function does not set the idle thread's NEED_RESCHED
8704 * flag, to make booting more robust.
8705 */
f1a0a376 8706void __init init_idle(struct task_struct *idle, int cpu)
1da177e4 8707{
70b97a7f 8708 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
8709 unsigned long flags;
8710
ff51ff84
PZ
8711 __sched_fork(0, idle);
8712
25834c73 8713 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5cb9eaa3 8714 raw_spin_rq_lock(rq);
5cbd54ef 8715
2f064a59 8716 idle->__state = TASK_RUNNING;
dd41f596 8717 idle->se.exec_start = sched_clock();
00b89fe0
VS
8718 /*
8719 * PF_KTHREAD should already be set at this point; regardless, make it
8720 * look like a proper per-CPU kthread.
8721 */
8722 idle->flags |= PF_IDLE | PF_KTHREAD | PF_NO_SETAFFINITY;
8723 kthread_set_per_cpu(idle, cpu);
dd41f596 8724
de9b8f5d
PZ
8725#ifdef CONFIG_SMP
8726 /*
b19a888c 8727 * It's possible that init_idle() gets called multiple times on a task,
de9b8f5d
PZ
8728 * in that case do_set_cpus_allowed() will not do the right thing.
8729 *
8730 * And since this is boot we can forgo the serialization.
8731 */
9cfc3e18 8732 set_cpus_allowed_common(idle, cpumask_of(cpu), 0);
de9b8f5d 8733#endif
6506cf6c
PZ
8734 /*
8735 * We're having a chicken and egg problem, even though we are
d1ccc66d 8736 * holding rq->lock, the CPU isn't yet set to this CPU so the
6506cf6c
PZ
8737 * lockdep check in task_group() will fail.
8738 *
8739 * Similar case to sched_fork(). / Alternatively we could
8740 * use task_rq_lock() here and obtain the other rq->lock.
8741 *
8742 * Silence PROVE_RCU
8743 */
8744 rcu_read_lock();
dd41f596 8745 __set_task_cpu(idle, cpu);
6506cf6c 8746 rcu_read_unlock();
1da177e4 8747
5311a98f
EB
8748 rq->idle = idle;
8749 rcu_assign_pointer(rq->curr, idle);
da0c1e65 8750 idle->on_rq = TASK_ON_RQ_QUEUED;
de9b8f5d 8751#ifdef CONFIG_SMP
3ca7a440 8752 idle->on_cpu = 1;
4866cde0 8753#endif
5cb9eaa3 8754 raw_spin_rq_unlock(rq);
25834c73 8755 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
1da177e4
LT
8756
8757 /* Set the preempt count _outside_ the spinlocks! */
01028747 8758 init_idle_preempt_count(idle, cpu);
55cd5340 8759
dd41f596
IM
8760 /*
8761 * The idle tasks have their own, simple scheduling class:
8762 */
8763 idle->sched_class = &idle_sched_class;
868baf07 8764 ftrace_graph_init_idle_task(idle, cpu);
45eacc69 8765 vtime_init_idle(idle, cpu);
de9b8f5d 8766#ifdef CONFIG_SMP
f1c6f1a7
CE
8767 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
8768#endif
19978ca6
IM
8769}
8770
e1d4eeec
NP
8771#ifdef CONFIG_SMP
8772
f82f8042
JL
8773int cpuset_cpumask_can_shrink(const struct cpumask *cur,
8774 const struct cpumask *trial)
8775{
06a76fe0 8776 int ret = 1;
f82f8042 8777
1087ad4e 8778 if (cpumask_empty(cur))
bb2bc55a
MG
8779 return ret;
8780
06a76fe0 8781 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
f82f8042
JL
8782
8783 return ret;
8784}
8785
7f51412a
JL
8786int task_can_attach(struct task_struct *p,
8787 const struct cpumask *cs_cpus_allowed)
8788{
8789 int ret = 0;
8790
8791 /*
8792 * Kthreads which disallow setaffinity shouldn't be moved
d1ccc66d 8793 * to a new cpuset; we don't want to change their CPU
7f51412a
JL
8794 * affinity and isolating such threads by their set of
8795 * allowed nodes is unnecessary. Thus, cpusets are not
8796 * applicable for such threads. This prevents checking for
8797 * success of set_cpus_allowed_ptr() on all attached tasks
3bd37062 8798 * before cpus_mask may be changed.
7f51412a
JL
8799 */
8800 if (p->flags & PF_NO_SETAFFINITY) {
8801 ret = -EINVAL;
8802 goto out;
8803 }
8804
7f51412a 8805 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
06a76fe0
NP
8806 cs_cpus_allowed))
8807 ret = dl_task_can_attach(p, cs_cpus_allowed);
7f51412a 8808
7f51412a
JL
8809out:
8810 return ret;
8811}
8812
f2cb1360 8813bool sched_smp_initialized __read_mostly;
e26fbffd 8814
e6628d5b
MG
8815#ifdef CONFIG_NUMA_BALANCING
8816/* Migrate current task p to target_cpu */
8817int migrate_task_to(struct task_struct *p, int target_cpu)
8818{
8819 struct migration_arg arg = { p, target_cpu };
8820 int curr_cpu = task_cpu(p);
8821
8822 if (curr_cpu == target_cpu)
8823 return 0;
8824
3bd37062 8825 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
e6628d5b
MG
8826 return -EINVAL;
8827
8828 /* TODO: This is not properly updating schedstats */
8829
286549dc 8830 trace_sched_move_numa(p, curr_cpu, target_cpu);
e6628d5b
MG
8831 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
8832}
0ec8aa00
PZ
8833
8834/*
8835 * Requeue a task on a given node and accurately track the number of NUMA
8836 * tasks on the runqueues
8837 */
8838void sched_setnuma(struct task_struct *p, int nid)
8839{
da0c1e65 8840 bool queued, running;
eb580751
PZ
8841 struct rq_flags rf;
8842 struct rq *rq;
0ec8aa00 8843
eb580751 8844 rq = task_rq_lock(p, &rf);
da0c1e65 8845 queued = task_on_rq_queued(p);
0ec8aa00
PZ
8846 running = task_current(rq, p);
8847
da0c1e65 8848 if (queued)
1de64443 8849 dequeue_task(rq, p, DEQUEUE_SAVE);
0ec8aa00 8850 if (running)
f3cd1c4e 8851 put_prev_task(rq, p);
0ec8aa00
PZ
8852
8853 p->numa_preferred_nid = nid;
0ec8aa00 8854
da0c1e65 8855 if (queued)
7134b3e9 8856 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 8857 if (running)
03b7fad1 8858 set_next_task(rq, p);
eb580751 8859 task_rq_unlock(rq, p, &rf);
0ec8aa00 8860}
5cc389bc 8861#endif /* CONFIG_NUMA_BALANCING */
f7b4cddc 8862
1da177e4 8863#ifdef CONFIG_HOTPLUG_CPU
054b9108 8864/*
d1ccc66d 8865 * Ensure that the idle task is using init_mm right before its CPU goes
48c5ccae 8866 * offline.
054b9108 8867 */
48c5ccae 8868void idle_task_exit(void)
1da177e4 8869{
48c5ccae 8870 struct mm_struct *mm = current->active_mm;
e76bd8d9 8871
48c5ccae 8872 BUG_ON(cpu_online(smp_processor_id()));
bf2c59fc 8873 BUG_ON(current != this_rq()->idle);
e76bd8d9 8874
a53efe5f 8875 if (mm != &init_mm) {
252d2a41 8876 switch_mm(mm, &init_mm, current);
a53efe5f
MS
8877 finish_arch_post_lock_switch();
8878 }
bf2c59fc
PZ
8879
8880 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
1da177e4
LT
8881}
8882
2558aacf 8883static int __balance_push_cpu_stop(void *arg)
1da177e4 8884{
2558aacf
PZ
8885 struct task_struct *p = arg;
8886 struct rq *rq = this_rq();
8887 struct rq_flags rf;
8888 int cpu;
1da177e4 8889
2558aacf
PZ
8890 raw_spin_lock_irq(&p->pi_lock);
8891 rq_lock(rq, &rf);
3f1d2a31 8892
2558aacf
PZ
8893 update_rq_clock(rq);
8894
8895 if (task_rq(p) == rq && task_on_rq_queued(p)) {
8896 cpu = select_fallback_rq(rq->cpu, p);
8897 rq = __migrate_task(rq, &rf, p, cpu);
10e7071b 8898 }
3f1d2a31 8899
2558aacf
PZ
8900 rq_unlock(rq, &rf);
8901 raw_spin_unlock_irq(&p->pi_lock);
8902
8903 put_task_struct(p);
8904
8905 return 0;
10e7071b 8906}
3f1d2a31 8907
2558aacf
PZ
8908static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
8909
48f24c4d 8910/*
2558aacf 8911 * Ensure we only run per-cpu kthreads once the CPU goes !active.
b5c44773
PZ
8912 *
8913 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
8914 * effective when the hotplug motion is down.
1da177e4 8915 */
2558aacf 8916static void balance_push(struct rq *rq)
1da177e4 8917{
2558aacf
PZ
8918 struct task_struct *push_task = rq->curr;
8919
5cb9eaa3 8920 lockdep_assert_rq_held(rq);
b5c44773 8921
ae792702
PZ
8922 /*
8923 * Ensure the thing is persistent until balance_push_set(.on = false);
8924 */
8925 rq->balance_callback = &balance_push_callback;
1da177e4 8926
b5c44773 8927 /*
868ad33b
TG
8928 * Only active while going offline and when invoked on the outgoing
8929 * CPU.
b5c44773 8930 */
868ad33b 8931 if (!cpu_dying(rq->cpu) || rq != this_rq())
b5c44773
PZ
8932 return;
8933
1da177e4 8934 /*
2558aacf
PZ
8935 * Both the cpu-hotplug and stop task are in this case and are
8936 * required to complete the hotplug process.
1da177e4 8937 */
00b89fe0 8938 if (kthread_is_per_cpu(push_task) ||
5ba2ffba
PZ
8939 is_migration_disabled(push_task)) {
8940
f2469a1f
TG
8941 /*
8942 * If this is the idle task on the outgoing CPU try to wake
8943 * up the hotplug control thread which might wait for the
8944 * last task to vanish. The rcuwait_active() check is
8945 * accurate here because the waiter is pinned on this CPU
8946 * and can't obviously be running in parallel.
3015ef4b
TG
8947 *
8948 * On RT kernels this also has to check whether there are
8949 * pinned and scheduled out tasks on the runqueue. They
8950 * need to leave the migrate disabled section first.
f2469a1f 8951 */
3015ef4b
TG
8952 if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
8953 rcuwait_active(&rq->hotplug_wait)) {
5cb9eaa3 8954 raw_spin_rq_unlock(rq);
f2469a1f 8955 rcuwait_wake_up(&rq->hotplug_wait);
5cb9eaa3 8956 raw_spin_rq_lock(rq);
f2469a1f 8957 }
2558aacf 8958 return;
f2469a1f 8959 }
48f24c4d 8960
2558aacf 8961 get_task_struct(push_task);
77bd3970 8962 /*
2558aacf
PZ
8963 * Temporarily drop rq->lock such that we can wake-up the stop task.
8964 * Both preemption and IRQs are still disabled.
77bd3970 8965 */
5cb9eaa3 8966 raw_spin_rq_unlock(rq);
2558aacf
PZ
8967 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
8968 this_cpu_ptr(&push_work));
8969 /*
8970 * At this point need_resched() is true and we'll take the loop in
8971 * schedule(). The next pick is obviously going to be the stop task
5ba2ffba 8972 * which kthread_is_per_cpu() and will push this task away.
2558aacf 8973 */
5cb9eaa3 8974 raw_spin_rq_lock(rq);
2558aacf 8975}
77bd3970 8976
2558aacf
PZ
8977static void balance_push_set(int cpu, bool on)
8978{
8979 struct rq *rq = cpu_rq(cpu);
8980 struct rq_flags rf;
48c5ccae 8981
2558aacf 8982 rq_lock_irqsave(rq, &rf);
22f667c9
PZ
8983 if (on) {
8984 WARN_ON_ONCE(rq->balance_callback);
ae792702 8985 rq->balance_callback = &balance_push_callback;
22f667c9 8986 } else if (rq->balance_callback == &balance_push_callback) {
ae792702 8987 rq->balance_callback = NULL;
22f667c9 8988 }
2558aacf
PZ
8989 rq_unlock_irqrestore(rq, &rf);
8990}
e692ab53 8991
f2469a1f
TG
8992/*
8993 * Invoked from a CPUs hotplug control thread after the CPU has been marked
8994 * inactive. All tasks which are not per CPU kernel threads are either
8995 * pushed off this CPU now via balance_push() or placed on a different CPU
8996 * during wakeup. Wait until the CPU is quiescent.
8997 */
8998static void balance_hotplug_wait(void)
8999{
9000 struct rq *rq = this_rq();
5473e0cc 9001
3015ef4b
TG
9002 rcuwait_wait_event(&rq->hotplug_wait,
9003 rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
f2469a1f
TG
9004 TASK_UNINTERRUPTIBLE);
9005}
5473e0cc 9006
2558aacf 9007#else
dce48a84 9008
2558aacf
PZ
9009static inline void balance_push(struct rq *rq)
9010{
dce48a84 9011}
dce48a84 9012
2558aacf
PZ
9013static inline void balance_push_set(int cpu, bool on)
9014{
9015}
9016
f2469a1f
TG
9017static inline void balance_hotplug_wait(void)
9018{
dce48a84 9019}
f2469a1f 9020
1da177e4
LT
9021#endif /* CONFIG_HOTPLUG_CPU */
9022
f2cb1360 9023void set_rq_online(struct rq *rq)
1f11eb6a
GH
9024{
9025 if (!rq->online) {
9026 const struct sched_class *class;
9027
c6c4927b 9028 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
9029 rq->online = 1;
9030
9031 for_each_class(class) {
9032 if (class->rq_online)
9033 class->rq_online(rq);
9034 }
9035 }
9036}
9037
f2cb1360 9038void set_rq_offline(struct rq *rq)
1f11eb6a
GH
9039{
9040 if (rq->online) {
9041 const struct sched_class *class;
9042
9043 for_each_class(class) {
9044 if (class->rq_offline)
9045 class->rq_offline(rq);
9046 }
9047
c6c4927b 9048 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
9049 rq->online = 0;
9050 }
9051}
9052
d1ccc66d
IM
9053/*
9054 * used to mark begin/end of suspend/resume:
9055 */
9056static int num_cpus_frozen;
d35be8ba 9057
1da177e4 9058/*
3a101d05
TH
9059 * Update cpusets according to cpu_active mask. If cpusets are
9060 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
9061 * around partition_sched_domains().
d35be8ba
SB
9062 *
9063 * If we come here as part of a suspend/resume, don't touch cpusets because we
9064 * want to restore it back to its original state upon resume anyway.
1da177e4 9065 */
40190a78 9066static void cpuset_cpu_active(void)
e761b772 9067{
40190a78 9068 if (cpuhp_tasks_frozen) {
d35be8ba
SB
9069 /*
9070 * num_cpus_frozen tracks how many CPUs are involved in suspend
9071 * resume sequence. As long as this is not the last online
9072 * operation in the resume sequence, just build a single sched
9073 * domain, ignoring cpusets.
9074 */
50e76632
PZ
9075 partition_sched_domains(1, NULL, NULL);
9076 if (--num_cpus_frozen)
135fb3e1 9077 return;
d35be8ba
SB
9078 /*
9079 * This is the last CPU online operation. So fall through and
9080 * restore the original sched domains by considering the
9081 * cpuset configurations.
9082 */
50e76632 9083 cpuset_force_rebuild();
3a101d05 9084 }
30e03acd 9085 cpuset_update_active_cpus();
3a101d05 9086}
e761b772 9087
40190a78 9088static int cpuset_cpu_inactive(unsigned int cpu)
3a101d05 9089{
40190a78 9090 if (!cpuhp_tasks_frozen) {
06a76fe0 9091 if (dl_cpu_busy(cpu))
135fb3e1 9092 return -EBUSY;
30e03acd 9093 cpuset_update_active_cpus();
135fb3e1 9094 } else {
d35be8ba
SB
9095 num_cpus_frozen++;
9096 partition_sched_domains(1, NULL, NULL);
e761b772 9097 }
135fb3e1 9098 return 0;
e761b772 9099}
e761b772 9100
40190a78 9101int sched_cpu_activate(unsigned int cpu)
135fb3e1 9102{
7d976699 9103 struct rq *rq = cpu_rq(cpu);
8a8c69c3 9104 struct rq_flags rf;
7d976699 9105
22f667c9 9106 /*
b5c44773
PZ
9107 * Clear the balance_push callback and prepare to schedule
9108 * regular tasks.
22f667c9 9109 */
2558aacf
PZ
9110 balance_push_set(cpu, false);
9111
ba2591a5
PZ
9112#ifdef CONFIG_SCHED_SMT
9113 /*
c5511d03 9114 * When going up, increment the number of cores with SMT present.
ba2591a5 9115 */
c5511d03
PZI
9116 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9117 static_branch_inc_cpuslocked(&sched_smt_present);
ba2591a5 9118#endif
40190a78 9119 set_cpu_active(cpu, true);
135fb3e1 9120
40190a78 9121 if (sched_smp_initialized) {
0fb3978b 9122 sched_update_numa(cpu, true);
135fb3e1 9123 sched_domains_numa_masks_set(cpu);
40190a78 9124 cpuset_cpu_active();
e761b772 9125 }
7d976699
TG
9126
9127 /*
9128 * Put the rq online, if not already. This happens:
9129 *
9130 * 1) In the early boot process, because we build the real domains
d1ccc66d 9131 * after all CPUs have been brought up.
7d976699
TG
9132 *
9133 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
9134 * domains.
9135 */
8a8c69c3 9136 rq_lock_irqsave(rq, &rf);
7d976699
TG
9137 if (rq->rd) {
9138 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9139 set_rq_online(rq);
9140 }
8a8c69c3 9141 rq_unlock_irqrestore(rq, &rf);
7d976699 9142
40190a78 9143 return 0;
135fb3e1
TG
9144}
9145
40190a78 9146int sched_cpu_deactivate(unsigned int cpu)
135fb3e1 9147{
120455c5
PZ
9148 struct rq *rq = cpu_rq(cpu);
9149 struct rq_flags rf;
135fb3e1
TG
9150 int ret;
9151
e0b257c3
AMB
9152 /*
9153 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
9154 * load balancing when not active
9155 */
9156 nohz_balance_exit_idle(rq);
9157
40190a78 9158 set_cpu_active(cpu, false);
741ba80f
PZ
9159
9160 /*
9161 * From this point forward, this CPU will refuse to run any task that
9162 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
9163 * push those tasks away until this gets cleared, see
9164 * sched_cpu_dying().
9165 */
975707f2
PZ
9166 balance_push_set(cpu, true);
9167
b2454caa 9168 /*
975707f2
PZ
9169 * We've cleared cpu_active_mask / set balance_push, wait for all
9170 * preempt-disabled and RCU users of this state to go away such that
9171 * all new such users will observe it.
b2454caa 9172 *
5ba2ffba
PZ
9173 * Specifically, we rely on ttwu to no longer target this CPU, see
9174 * ttwu_queue_cond() and is_cpu_allowed().
9175 *
b2454caa
PZ
9176 * Do sync before park smpboot threads to take care the rcu boost case.
9177 */
309ba859 9178 synchronize_rcu();
40190a78 9179
120455c5
PZ
9180 rq_lock_irqsave(rq, &rf);
9181 if (rq->rd) {
9182 update_rq_clock(rq);
9183 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9184 set_rq_offline(rq);
9185 }
9186 rq_unlock_irqrestore(rq, &rf);
9187
c5511d03
PZI
9188#ifdef CONFIG_SCHED_SMT
9189 /*
9190 * When going down, decrement the number of cores with SMT present.
9191 */
9192 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9193 static_branch_dec_cpuslocked(&sched_smt_present);
3c474b32
PZ
9194
9195 sched_core_cpu_deactivate(cpu);
c5511d03
PZI
9196#endif
9197
40190a78
TG
9198 if (!sched_smp_initialized)
9199 return 0;
9200
0fb3978b 9201 sched_update_numa(cpu, false);
40190a78
TG
9202 ret = cpuset_cpu_inactive(cpu);
9203 if (ret) {
2558aacf 9204 balance_push_set(cpu, false);
40190a78 9205 set_cpu_active(cpu, true);
0fb3978b 9206 sched_update_numa(cpu, true);
40190a78 9207 return ret;
135fb3e1 9208 }
40190a78
TG
9209 sched_domains_numa_masks_clear(cpu);
9210 return 0;
135fb3e1
TG
9211}
9212
94baf7a5
TG
9213static void sched_rq_cpu_starting(unsigned int cpu)
9214{
9215 struct rq *rq = cpu_rq(cpu);
9216
9217 rq->calc_load_update = calc_load_update;
94baf7a5
TG
9218 update_max_interval();
9219}
9220
135fb3e1
TG
9221int sched_cpu_starting(unsigned int cpu)
9222{
9edeaea1 9223 sched_core_cpu_starting(cpu);
94baf7a5 9224 sched_rq_cpu_starting(cpu);
d84b3131 9225 sched_tick_start(cpu);
135fb3e1 9226 return 0;
e761b772 9227}
e761b772 9228
f2785ddb 9229#ifdef CONFIG_HOTPLUG_CPU
1cf12e08
TG
9230
9231/*
9232 * Invoked immediately before the stopper thread is invoked to bring the
9233 * CPU down completely. At this point all per CPU kthreads except the
9234 * hotplug thread (current) and the stopper thread (inactive) have been
9235 * either parked or have been unbound from the outgoing CPU. Ensure that
9236 * any of those which might be on the way out are gone.
9237 *
9238 * If after this point a bound task is being woken on this CPU then the
9239 * responsible hotplug callback has failed to do it's job.
9240 * sched_cpu_dying() will catch it with the appropriate fireworks.
9241 */
9242int sched_cpu_wait_empty(unsigned int cpu)
9243{
9244 balance_hotplug_wait();
9245 return 0;
9246}
9247
9248/*
9249 * Since this CPU is going 'away' for a while, fold any nr_active delta we
9250 * might have. Called from the CPU stopper task after ensuring that the
9251 * stopper is the last running task on the CPU, so nr_active count is
9252 * stable. We need to take the teardown thread which is calling this into
9253 * account, so we hand in adjust = 1 to the load calculation.
9254 *
9255 * Also see the comment "Global load-average calculations".
9256 */
9257static void calc_load_migrate(struct rq *rq)
9258{
9259 long delta = calc_load_fold_active(rq, 1);
9260
9261 if (delta)
9262 atomic_long_add(delta, &calc_load_tasks);
9263}
9264
36c6e17b
VS
9265static void dump_rq_tasks(struct rq *rq, const char *loglvl)
9266{
9267 struct task_struct *g, *p;
9268 int cpu = cpu_of(rq);
9269
5cb9eaa3 9270 lockdep_assert_rq_held(rq);
36c6e17b
VS
9271
9272 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
9273 for_each_process_thread(g, p) {
9274 if (task_cpu(p) != cpu)
9275 continue;
9276
9277 if (!task_on_rq_queued(p))
9278 continue;
9279
9280 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
9281 }
9282}
9283
f2785ddb
TG
9284int sched_cpu_dying(unsigned int cpu)
9285{
9286 struct rq *rq = cpu_rq(cpu);
8a8c69c3 9287 struct rq_flags rf;
f2785ddb
TG
9288
9289 /* Handle pending wakeups and then migrate everything off */
d84b3131 9290 sched_tick_stop(cpu);
8a8c69c3
PZ
9291
9292 rq_lock_irqsave(rq, &rf);
36c6e17b
VS
9293 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
9294 WARN(true, "Dying CPU not properly vacated!");
9295 dump_rq_tasks(rq, KERN_WARNING);
9296 }
8a8c69c3
PZ
9297 rq_unlock_irqrestore(rq, &rf);
9298
f2785ddb
TG
9299 calc_load_migrate(rq);
9300 update_max_interval();
e5ef27d0 9301 hrtick_clear(rq);
3c474b32 9302 sched_core_cpu_dying(cpu);
f2785ddb
TG
9303 return 0;
9304}
9305#endif
9306
1da177e4
LT
9307void __init sched_init_smp(void)
9308{
0fb3978b 9309 sched_init_numa(NUMA_NO_NODE);
cb83b629 9310
6acce3ef
PZ
9311 /*
9312 * There's no userspace yet to cause hotplug operations; hence all the
d1ccc66d 9313 * CPU masks are stable and all blatant races in the below code cannot
b5a4e2bb 9314 * happen.
6acce3ef 9315 */
712555ee 9316 mutex_lock(&sched_domains_mutex);
8d5dc512 9317 sched_init_domains(cpu_active_mask);
712555ee 9318 mutex_unlock(&sched_domains_mutex);
e761b772 9319
5c1e1767 9320 /* Move init over to a non-isolated CPU */
04d4e665 9321 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
5c1e1767 9322 BUG();
15faafc6 9323 current->flags &= ~PF_NO_SETAFFINITY;
19978ca6 9324 sched_init_granularity();
4212823f 9325
0e3900e6 9326 init_sched_rt_class();
1baca4ce 9327 init_sched_dl_class();
1b568f0a 9328
e26fbffd 9329 sched_smp_initialized = true;
1da177e4 9330}
e26fbffd
TG
9331
9332static int __init migration_init(void)
9333{
77a5352b 9334 sched_cpu_starting(smp_processor_id());
e26fbffd 9335 return 0;
1da177e4 9336}
e26fbffd
TG
9337early_initcall(migration_init);
9338
1da177e4
LT
9339#else
9340void __init sched_init_smp(void)
9341{
19978ca6 9342 sched_init_granularity();
1da177e4
LT
9343}
9344#endif /* CONFIG_SMP */
9345
9346int in_sched_functions(unsigned long addr)
9347{
1da177e4
LT
9348 return in_lock_functions(addr) ||
9349 (addr >= (unsigned long)__sched_text_start
9350 && addr < (unsigned long)__sched_text_end);
9351}
9352
029632fb 9353#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
9354/*
9355 * Default task group.
9356 * Every task in system belongs to this group at bootup.
9357 */
029632fb 9358struct task_group root_task_group;
35cf4e50 9359LIST_HEAD(task_groups);
b0367629
WL
9360
9361/* Cacheline aligned slab cache for task_group */
9362static struct kmem_cache *task_group_cache __read_mostly;
052f1dc7 9363#endif
6f505b16 9364
e6252c3e 9365DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
10e2f1ac 9366DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
6f505b16 9367
1da177e4
LT
9368void __init sched_init(void)
9369{
a1dc0446 9370 unsigned long ptr = 0;
55627e3c 9371 int i;
434d53b0 9372
c3a340f7
SRV
9373 /* Make sure the linker didn't screw up */
9374 BUG_ON(&idle_sched_class + 1 != &fair_sched_class ||
9375 &fair_sched_class + 1 != &rt_sched_class ||
9376 &rt_sched_class + 1 != &dl_sched_class);
9377#ifdef CONFIG_SMP
9378 BUG_ON(&dl_sched_class + 1 != &stop_sched_class);
9379#endif
9380
5822a454 9381 wait_bit_init();
9dcb8b68 9382
434d53b0 9383#ifdef CONFIG_FAIR_GROUP_SCHED
a1dc0446 9384 ptr += 2 * nr_cpu_ids * sizeof(void **);
434d53b0
MT
9385#endif
9386#ifdef CONFIG_RT_GROUP_SCHED
a1dc0446 9387 ptr += 2 * nr_cpu_ids * sizeof(void **);
434d53b0 9388#endif
a1dc0446
QC
9389 if (ptr) {
9390 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
434d53b0
MT
9391
9392#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 9393 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
9394 ptr += nr_cpu_ids * sizeof(void **);
9395
07e06b01 9396 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 9397 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 9398
b1d1779e
WY
9399 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
9400 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6d6bc0ad 9401#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 9402#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 9403 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
9404 ptr += nr_cpu_ids * sizeof(void **);
9405
07e06b01 9406 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
9407 ptr += nr_cpu_ids * sizeof(void **);
9408
6d6bc0ad 9409#endif /* CONFIG_RT_GROUP_SCHED */
b74e6278 9410 }
df7c8e84 9411#ifdef CONFIG_CPUMASK_OFFSTACK
b74e6278
AT
9412 for_each_possible_cpu(i) {
9413 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
9414 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
10e2f1ac
PZ
9415 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
9416 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
434d53b0 9417 }
b74e6278 9418#endif /* CONFIG_CPUMASK_OFFSTACK */
dd41f596 9419
d1ccc66d
IM
9420 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
9421 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
332ac17e 9422
57d885fe
GH
9423#ifdef CONFIG_SMP
9424 init_defrootdomain();
9425#endif
9426
d0b27fa7 9427#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 9428 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 9429 global_rt_period(), global_rt_runtime());
6d6bc0ad 9430#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 9431
7c941438 9432#ifdef CONFIG_CGROUP_SCHED
b0367629
WL
9433 task_group_cache = KMEM_CACHE(task_group, 0);
9434
07e06b01
YZ
9435 list_add(&root_task_group.list, &task_groups);
9436 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 9437 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 9438 autogroup_init(&init_task);
7c941438 9439#endif /* CONFIG_CGROUP_SCHED */
6f505b16 9440
0a945022 9441 for_each_possible_cpu(i) {
70b97a7f 9442 struct rq *rq;
1da177e4
LT
9443
9444 rq = cpu_rq(i);
5cb9eaa3 9445 raw_spin_lock_init(&rq->__lock);
7897986b 9446 rq->nr_running = 0;
dce48a84
TG
9447 rq->calc_load_active = 0;
9448 rq->calc_load_update = jiffies + LOAD_FREQ;
acb5a9ba 9449 init_cfs_rq(&rq->cfs);
07c54f7a
AV
9450 init_rt_rq(&rq->rt);
9451 init_dl_rq(&rq->dl);
dd41f596 9452#ifdef CONFIG_FAIR_GROUP_SCHED
6f505b16 9453 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9c2791f9 9454 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
354d60c2 9455 /*
d1ccc66d 9456 * How much CPU bandwidth does root_task_group get?
354d60c2
DG
9457 *
9458 * In case of task-groups formed thr' the cgroup filesystem, it
d1ccc66d
IM
9459 * gets 100% of the CPU resources in the system. This overall
9460 * system CPU resource is divided among the tasks of
07e06b01 9461 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
9462 * based on each entity's (task or task-group's) weight
9463 * (se->load.weight).
9464 *
07e06b01 9465 * In other words, if root_task_group has 10 tasks of weight
354d60c2 9466 * 1024) and two child groups A0 and A1 (of weight 1024 each),
d1ccc66d 9467 * then A0's share of the CPU resource is:
354d60c2 9468 *
0d905bca 9469 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 9470 *
07e06b01
YZ
9471 * We achieve this by letting root_task_group's tasks sit
9472 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 9473 */
07e06b01 9474 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
9475#endif /* CONFIG_FAIR_GROUP_SCHED */
9476
9477 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 9478#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 9479 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 9480#endif
1da177e4 9481#ifdef CONFIG_SMP
41c7ce9a 9482 rq->sd = NULL;
57d885fe 9483 rq->rd = NULL;
ca6d75e6 9484 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
b5c44773 9485 rq->balance_callback = &balance_push_callback;
1da177e4 9486 rq->active_balance = 0;
dd41f596 9487 rq->next_balance = jiffies;
1da177e4 9488 rq->push_cpu = 0;
0a2966b4 9489 rq->cpu = i;
1f11eb6a 9490 rq->online = 0;
eae0c9df
MG
9491 rq->idle_stamp = 0;
9492 rq->avg_idle = 2*sysctl_sched_migration_cost;
94aafc3e
PZ
9493 rq->wake_stamp = jiffies;
9494 rq->wake_avg_idle = rq->avg_idle;
9bd721c5 9495 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
367456c7
PZ
9496
9497 INIT_LIST_HEAD(&rq->cfs_tasks);
9498
dc938520 9499 rq_attach_root(rq, &def_root_domain);
3451d024 9500#ifdef CONFIG_NO_HZ_COMMON
e022e0d3 9501 rq->last_blocked_load_update_tick = jiffies;
a22e47a4 9502 atomic_set(&rq->nohz_flags, 0);
90b5363a 9503
545b8c8d 9504 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
83cd4fe2 9505#endif
f2469a1f
TG
9506#ifdef CONFIG_HOTPLUG_CPU
9507 rcuwait_init(&rq->hotplug_wait);
83cd4fe2 9508#endif
9fd81dd5 9509#endif /* CONFIG_SMP */
77a021be 9510 hrtick_rq_init(rq);
1da177e4 9511 atomic_set(&rq->nr_iowait, 0);
9edeaea1
PZ
9512
9513#ifdef CONFIG_SCHED_CORE
3c474b32 9514 rq->core = rq;
539f6512 9515 rq->core_pick = NULL;
9edeaea1 9516 rq->core_enabled = 0;
539f6512 9517 rq->core_tree = RB_ROOT;
4feee7d1
JD
9518 rq->core_forceidle_count = 0;
9519 rq->core_forceidle_occupation = 0;
9520 rq->core_forceidle_start = 0;
539f6512
PZ
9521
9522 rq->core_cookie = 0UL;
9edeaea1 9523#endif
1da177e4
LT
9524 }
9525
9059393e 9526 set_load_weight(&init_task, false);
b50f60ce 9527
1da177e4
LT
9528 /*
9529 * The boot idle thread does lazy MMU switching as well:
9530 */
f1f10076 9531 mmgrab(&init_mm);
1da177e4
LT
9532 enter_lazy_tlb(&init_mm, current);
9533
40966e31
EB
9534 /*
9535 * The idle task doesn't need the kthread struct to function, but it
9536 * is dressed up as a per-CPU kthread and thus needs to play the part
9537 * if we want to avoid special-casing it in code that deals with per-CPU
9538 * kthreads.
9539 */
dd621ee0 9540 WARN_ON(!set_kthread_struct(current));
40966e31 9541
1da177e4
LT
9542 /*
9543 * Make us the idle thread. Technically, schedule() should not be
9544 * called from this thread, however somewhere below it might be,
9545 * but because we are the idle thread, we just pick up running again
9546 * when this runqueue becomes "idle".
9547 */
9548 init_idle(current, smp_processor_id());
dce48a84
TG
9549
9550 calc_load_update = jiffies + LOAD_FREQ;
9551
bf4d83f6 9552#ifdef CONFIG_SMP
29d5e047 9553 idle_thread_set_boot_cpu();
b5c44773 9554 balance_push_set(smp_processor_id(), false);
029632fb
PZ
9555#endif
9556 init_sched_fair_class();
6a7b3dc3 9557
eb414681
JW
9558 psi_init();
9559
69842cba
PB
9560 init_uclamp();
9561
c597bfdd
FW
9562 preempt_dynamic_init();
9563
6892b75e 9564 scheduler_running = 1;
1da177e4
LT
9565}
9566
d902db1e 9567#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2 9568
42a38756 9569void __might_sleep(const char *file, int line)
1da177e4 9570{
d6c23bb3 9571 unsigned int state = get_current_state();
8eb23b9f
PZ
9572 /*
9573 * Blocking primitives will set (and therefore destroy) current->state,
9574 * since we will exit with TASK_RUNNING make sure we enter with it,
9575 * otherwise we will destroy state.
9576 */
d6c23bb3 9577 WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
8eb23b9f 9578 "do not call blocking ops when !TASK_RUNNING; "
d6c23bb3 9579 "state=%x set at [<%p>] %pS\n", state,
8eb23b9f 9580 (void *)current->task_state_change,
00845eb9 9581 (void *)current->task_state_change);
8eb23b9f 9582
42a38756 9583 __might_resched(file, line, 0);
3427445a
PZ
9584}
9585EXPORT_SYMBOL(__might_sleep);
9586
8d713b69
TG
9587static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
9588{
9589 if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
9590 return;
9591
9592 if (preempt_count() == preempt_offset)
9593 return;
9594
9595 pr_err("Preemption disabled at:");
9596 print_ip_sym(KERN_ERR, ip);
9597}
9598
50e081b9
TG
9599static inline bool resched_offsets_ok(unsigned int offsets)
9600{
9601 unsigned int nested = preempt_count();
9602
9603 nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
9604
9605 return nested == offsets;
9606}
9607
9608void __might_resched(const char *file, int line, unsigned int offsets)
1da177e4 9609{
d1ccc66d
IM
9610 /* Ratelimiting timestamp: */
9611 static unsigned long prev_jiffy;
9612
d1c6d149 9613 unsigned long preempt_disable_ip;
1da177e4 9614
d1ccc66d
IM
9615 /* WARN_ON_ONCE() by default, no rate limit required: */
9616 rcu_sleep_check();
9617
50e081b9 9618 if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
312364f3 9619 !is_idle_task(current) && !current->non_block_count) ||
1c3c5eab
TG
9620 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
9621 oops_in_progress)
aef745fc 9622 return;
1c3c5eab 9623
aef745fc
IM
9624 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9625 return;
9626 prev_jiffy = jiffies;
9627
d1ccc66d 9628 /* Save this before calling printk(), since that will clobber it: */
d1c6d149
VN
9629 preempt_disable_ip = get_preempt_disable_ip(current);
9630
a45ed302
TG
9631 pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
9632 file, line);
9633 pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
9634 in_atomic(), irqs_disabled(), current->non_block_count,
9635 current->pid, current->comm);
8d713b69 9636 pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
50e081b9 9637 offsets & MIGHT_RESCHED_PREEMPT_MASK);
8d713b69
TG
9638
9639 if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
50e081b9
TG
9640 pr_err("RCU nest depth: %d, expected: %u\n",
9641 rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
8d713b69 9642 }
aef745fc 9643
a8b686b3 9644 if (task_stack_end_corrupted(current))
a45ed302 9645 pr_emerg("Thread overran stack, or stack corrupted\n");
a8b686b3 9646
aef745fc
IM
9647 debug_show_held_locks(current);
9648 if (irqs_disabled())
9649 print_irqtrace_events(current);
8d713b69 9650
50e081b9
TG
9651 print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
9652 preempt_disable_ip);
8d713b69 9653
aef745fc 9654 dump_stack();
f0b22e39 9655 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
1da177e4 9656}
874f670e 9657EXPORT_SYMBOL(__might_resched);
568f1967
PZ
9658
9659void __cant_sleep(const char *file, int line, int preempt_offset)
9660{
9661 static unsigned long prev_jiffy;
9662
9663 if (irqs_disabled())
9664 return;
9665
9666 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9667 return;
9668
9669 if (preempt_count() > preempt_offset)
9670 return;
9671
9672 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9673 return;
9674 prev_jiffy = jiffies;
9675
9676 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
9677 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9678 in_atomic(), irqs_disabled(),
9679 current->pid, current->comm);
9680
9681 debug_show_held_locks(current);
9682 dump_stack();
9683 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9684}
9685EXPORT_SYMBOL_GPL(__cant_sleep);
74d862b6
TG
9686
9687#ifdef CONFIG_SMP
9688void __cant_migrate(const char *file, int line)
9689{
9690 static unsigned long prev_jiffy;
9691
9692 if (irqs_disabled())
9693 return;
9694
9695 if (is_migration_disabled(current))
9696 return;
9697
9698 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9699 return;
9700
9701 if (preempt_count() > 0)
9702 return;
9703
9704 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9705 return;
9706 prev_jiffy = jiffies;
9707
9708 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
9709 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
9710 in_atomic(), irqs_disabled(), is_migration_disabled(current),
9711 current->pid, current->comm);
9712
9713 debug_show_held_locks(current);
9714 dump_stack();
9715 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9716}
9717EXPORT_SYMBOL_GPL(__cant_migrate);
9718#endif
1da177e4
LT
9719#endif
9720
9721#ifdef CONFIG_MAGIC_SYSRQ
dbc7f069 9722void normalize_rt_tasks(void)
3a5e4dc1 9723{
dbc7f069 9724 struct task_struct *g, *p;
d50dde5a
DF
9725 struct sched_attr attr = {
9726 .sched_policy = SCHED_NORMAL,
9727 };
1da177e4 9728
3472eaa1 9729 read_lock(&tasklist_lock);
5d07f420 9730 for_each_process_thread(g, p) {
178be793
IM
9731 /*
9732 * Only normalize user tasks:
9733 */
3472eaa1 9734 if (p->flags & PF_KTHREAD)
178be793
IM
9735 continue;
9736
4fa8d299 9737 p->se.exec_start = 0;
ceeadb83
YS
9738 schedstat_set(p->stats.wait_start, 0);
9739 schedstat_set(p->stats.sleep_start, 0);
9740 schedstat_set(p->stats.block_start, 0);
dd41f596 9741
aab03e05 9742 if (!dl_task(p) && !rt_task(p)) {
dd41f596
IM
9743 /*
9744 * Renice negative nice level userspace
9745 * tasks back to 0:
9746 */
3472eaa1 9747 if (task_nice(p) < 0)
dd41f596 9748 set_user_nice(p, 0);
1da177e4 9749 continue;
dd41f596 9750 }
1da177e4 9751
dbc7f069 9752 __sched_setscheduler(p, &attr, false, false);
5d07f420 9753 }
3472eaa1 9754 read_unlock(&tasklist_lock);
1da177e4
LT
9755}
9756
9757#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 9758
67fc4e0c 9759#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 9760/*
67fc4e0c 9761 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
9762 *
9763 * They can only be called when the whole system has been
9764 * stopped - every CPU needs to be quiescent, and no scheduling
9765 * activity can take place. Using them for anything else would
9766 * be a serious bug, and as a result, they aren't even visible
9767 * under any other configuration.
9768 */
9769
9770/**
d1ccc66d 9771 * curr_task - return the current task for a given CPU.
1df5c10a
LT
9772 * @cpu: the processor in question.
9773 *
9774 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
e69f6186
YB
9775 *
9776 * Return: The current task for @cpu.
1df5c10a 9777 */
36c8b586 9778struct task_struct *curr_task(int cpu)
1df5c10a
LT
9779{
9780 return cpu_curr(cpu);
9781}
9782
67fc4e0c
JW
9783#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
9784
9785#ifdef CONFIG_IA64
1df5c10a 9786/**
5feeb783 9787 * ia64_set_curr_task - set the current task for a given CPU.
1df5c10a
LT
9788 * @cpu: the processor in question.
9789 * @p: the task pointer to set.
9790 *
9791 * Description: This function must only be used when non-maskable interrupts
41a2d6cf 9792 * are serviced on a separate stack. It allows the architecture to switch the
d1ccc66d 9793 * notion of the current task on a CPU in a non-blocking manner. This function
1df5c10a
LT
9794 * must be called with all CPU's synchronized, and interrupts disabled, the
9795 * and caller must save the original value of the current task (see
9796 * curr_task() above) and restore that value before reenabling interrupts and
9797 * re-starting the system.
9798 *
9799 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9800 */
a458ae2e 9801void ia64_set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
9802{
9803 cpu_curr(cpu) = p;
9804}
9805
9806#endif
29f59db3 9807
7c941438 9808#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
9809/* task_group_lock serializes the addition/removal of task groups */
9810static DEFINE_SPINLOCK(task_group_lock);
9811
2480c093
PB
9812static inline void alloc_uclamp_sched_group(struct task_group *tg,
9813 struct task_group *parent)
9814{
9815#ifdef CONFIG_UCLAMP_TASK_GROUP
0413d7f3 9816 enum uclamp_id clamp_id;
2480c093
PB
9817
9818 for_each_clamp_id(clamp_id) {
9819 uclamp_se_set(&tg->uclamp_req[clamp_id],
9820 uclamp_none(clamp_id), false);
0b60ba2d 9821 tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
2480c093
PB
9822 }
9823#endif
9824}
9825
2f5177f0 9826static void sched_free_group(struct task_group *tg)
bccbe08a
PZ
9827{
9828 free_fair_sched_group(tg);
9829 free_rt_sched_group(tg);
e9aa1dd1 9830 autogroup_free(tg);
b0367629 9831 kmem_cache_free(task_group_cache, tg);
bccbe08a
PZ
9832}
9833
b027789e
MK
9834static void sched_free_group_rcu(struct rcu_head *rcu)
9835{
9836 sched_free_group(container_of(rcu, struct task_group, rcu));
9837}
9838
9839static void sched_unregister_group(struct task_group *tg)
9840{
9841 unregister_fair_sched_group(tg);
9842 unregister_rt_sched_group(tg);
9843 /*
9844 * We have to wait for yet another RCU grace period to expire, as
9845 * print_cfs_stats() might run concurrently.
9846 */
9847 call_rcu(&tg->rcu, sched_free_group_rcu);
9848}
9849
bccbe08a 9850/* allocate runqueue etc for a new task group */
ec7dc8ac 9851struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
9852{
9853 struct task_group *tg;
bccbe08a 9854
b0367629 9855 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
bccbe08a
PZ
9856 if (!tg)
9857 return ERR_PTR(-ENOMEM);
9858
ec7dc8ac 9859 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
9860 goto err;
9861
ec7dc8ac 9862 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
9863 goto err;
9864
2480c093
PB
9865 alloc_uclamp_sched_group(tg, parent);
9866
ace783b9
LZ
9867 return tg;
9868
9869err:
2f5177f0 9870 sched_free_group(tg);
ace783b9
LZ
9871 return ERR_PTR(-ENOMEM);
9872}
9873
9874void sched_online_group(struct task_group *tg, struct task_group *parent)
9875{
9876 unsigned long flags;
9877
8ed36996 9878 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 9879 list_add_rcu(&tg->list, &task_groups);
f473aa5e 9880
d1ccc66d
IM
9881 /* Root should already exist: */
9882 WARN_ON(!parent);
f473aa5e
PZ
9883
9884 tg->parent = parent;
f473aa5e 9885 INIT_LIST_HEAD(&tg->children);
09f2724a 9886 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 9887 spin_unlock_irqrestore(&task_group_lock, flags);
8663e24d
PZ
9888
9889 online_fair_sched_group(tg);
29f59db3
SV
9890}
9891
9b5b7751 9892/* rcu callback to free various structures associated with a task group */
b027789e 9893static void sched_unregister_group_rcu(struct rcu_head *rhp)
29f59db3 9894{
d1ccc66d 9895 /* Now it should be safe to free those cfs_rqs: */
b027789e 9896 sched_unregister_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
9897}
9898
4cf86d77 9899void sched_destroy_group(struct task_group *tg)
ace783b9 9900{
d1ccc66d 9901 /* Wait for possible concurrent references to cfs_rqs complete: */
b027789e 9902 call_rcu(&tg->rcu, sched_unregister_group_rcu);
ace783b9
LZ
9903}
9904
b027789e 9905void sched_release_group(struct task_group *tg)
29f59db3 9906{
8ed36996 9907 unsigned long flags;
29f59db3 9908
b027789e
MK
9909 /*
9910 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
9911 * sched_cfs_period_timer()).
9912 *
9913 * For this to be effective, we have to wait for all pending users of
9914 * this task group to leave their RCU critical section to ensure no new
9915 * user will see our dying task group any more. Specifically ensure
9916 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
9917 *
9918 * We therefore defer calling unregister_fair_sched_group() to
9919 * sched_unregister_group() which is guarantied to get called only after the
9920 * current RCU grace period has expired.
9921 */
3d4b47b4 9922 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 9923 list_del_rcu(&tg->list);
f473aa5e 9924 list_del_rcu(&tg->siblings);
8ed36996 9925 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
9926}
9927
ea86cb4b 9928static void sched_change_group(struct task_struct *tsk, int type)
29f59db3 9929{
8323f26c 9930 struct task_group *tg;
29f59db3 9931
f7b8a47d
KT
9932 /*
9933 * All callers are synchronized by task_rq_lock(); we do not use RCU
9934 * which is pointless here. Thus, we pass "true" to task_css_check()
9935 * to prevent lockdep warnings.
9936 */
9937 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8323f26c
PZ
9938 struct task_group, css);
9939 tg = autogroup_task_group(tsk, tg);
9940 tsk->sched_task_group = tg;
9941
810b3817 9942#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
9943 if (tsk->sched_class->task_change_group)
9944 tsk->sched_class->task_change_group(tsk, type);
b2b5ce02 9945 else
810b3817 9946#endif
b2b5ce02 9947 set_task_rq(tsk, task_cpu(tsk));
ea86cb4b
VG
9948}
9949
9950/*
9951 * Change task's runqueue when it moves between groups.
9952 *
9953 * The caller of this function should have put the task in its new group by
9954 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
9955 * its new group.
9956 */
9957void sched_move_task(struct task_struct *tsk)
9958{
7a57f32a
PZ
9959 int queued, running, queue_flags =
9960 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
ea86cb4b
VG
9961 struct rq_flags rf;
9962 struct rq *rq;
9963
9964 rq = task_rq_lock(tsk, &rf);
1b1d6225 9965 update_rq_clock(rq);
ea86cb4b
VG
9966
9967 running = task_current(rq, tsk);
9968 queued = task_on_rq_queued(tsk);
9969
9970 if (queued)
7a57f32a 9971 dequeue_task(rq, tsk, queue_flags);
bb3bac2c 9972 if (running)
ea86cb4b
VG
9973 put_prev_task(rq, tsk);
9974
9975 sched_change_group(tsk, TASK_MOVE_GROUP);
810b3817 9976
da0c1e65 9977 if (queued)
7a57f32a 9978 enqueue_task(rq, tsk, queue_flags);
2a4b03ff 9979 if (running) {
03b7fad1 9980 set_next_task(rq, tsk);
2a4b03ff
VG
9981 /*
9982 * After changing group, the running task may have joined a
9983 * throttled one but it's still the running task. Trigger a
9984 * resched to make sure that task can still run.
9985 */
9986 resched_curr(rq);
9987 }
29f59db3 9988
eb580751 9989 task_rq_unlock(rq, tsk, &rf);
29f59db3 9990}
68318b8e 9991
a7c6d554 9992static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
68318b8e 9993{
a7c6d554 9994 return css ? container_of(css, struct task_group, css) : NULL;
68318b8e
SV
9995}
9996
eb95419b
TH
9997static struct cgroup_subsys_state *
9998cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
68318b8e 9999{
eb95419b
TH
10000 struct task_group *parent = css_tg(parent_css);
10001 struct task_group *tg;
68318b8e 10002
eb95419b 10003 if (!parent) {
68318b8e 10004 /* This is early initialization for the top cgroup */
07e06b01 10005 return &root_task_group.css;
68318b8e
SV
10006 }
10007
ec7dc8ac 10008 tg = sched_create_group(parent);
68318b8e
SV
10009 if (IS_ERR(tg))
10010 return ERR_PTR(-ENOMEM);
10011
68318b8e
SV
10012 return &tg->css;
10013}
10014
96b77745
KK
10015/* Expose task group only after completing cgroup initialization */
10016static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
10017{
10018 struct task_group *tg = css_tg(css);
10019 struct task_group *parent = css_tg(css->parent);
10020
10021 if (parent)
10022 sched_online_group(tg, parent);
7226017a
QY
10023
10024#ifdef CONFIG_UCLAMP_TASK_GROUP
10025 /* Propagate the effective uclamp value for the new group */
93b73858
QY
10026 mutex_lock(&uclamp_mutex);
10027 rcu_read_lock();
7226017a 10028 cpu_util_update_eff(css);
93b73858
QY
10029 rcu_read_unlock();
10030 mutex_unlock(&uclamp_mutex);
7226017a
QY
10031#endif
10032
96b77745
KK
10033 return 0;
10034}
10035
2f5177f0 10036static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
ace783b9 10037{
eb95419b 10038 struct task_group *tg = css_tg(css);
ace783b9 10039
b027789e 10040 sched_release_group(tg);
ace783b9
LZ
10041}
10042
eb95419b 10043static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
68318b8e 10044{
eb95419b 10045 struct task_group *tg = css_tg(css);
68318b8e 10046
2f5177f0
PZ
10047 /*
10048 * Relies on the RCU grace period between css_released() and this.
10049 */
b027789e 10050 sched_unregister_group(tg);
ace783b9
LZ
10051}
10052
ea86cb4b
VG
10053/*
10054 * This is called before wake_up_new_task(), therefore we really only
10055 * have to set its group bits, all the other stuff does not apply.
10056 */
b53202e6 10057static void cpu_cgroup_fork(struct task_struct *task)
eeb61e53 10058{
ea86cb4b
VG
10059 struct rq_flags rf;
10060 struct rq *rq;
10061
10062 rq = task_rq_lock(task, &rf);
10063
80f5c1b8 10064 update_rq_clock(rq);
ea86cb4b
VG
10065 sched_change_group(task, TASK_SET_GROUP);
10066
10067 task_rq_unlock(rq, task, &rf);
eeb61e53
KT
10068}
10069
1f7dd3e5 10070static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
68318b8e 10071{
bb9d97b6 10072 struct task_struct *task;
1f7dd3e5 10073 struct cgroup_subsys_state *css;
7dc603c9 10074 int ret = 0;
bb9d97b6 10075
1f7dd3e5 10076 cgroup_taskset_for_each(task, css, tset) {
b68aa230 10077#ifdef CONFIG_RT_GROUP_SCHED
eb95419b 10078 if (!sched_rt_can_attach(css_tg(css), task))
bb9d97b6 10079 return -EINVAL;
b68aa230 10080#endif
7dc603c9 10081 /*
b19a888c 10082 * Serialize against wake_up_new_task() such that if it's
7dc603c9
PZ
10083 * running, we're sure to observe its full state.
10084 */
10085 raw_spin_lock_irq(&task->pi_lock);
10086 /*
10087 * Avoid calling sched_move_task() before wake_up_new_task()
10088 * has happened. This would lead to problems with PELT, due to
10089 * move wanting to detach+attach while we're not attached yet.
10090 */
2f064a59 10091 if (READ_ONCE(task->__state) == TASK_NEW)
7dc603c9
PZ
10092 ret = -EINVAL;
10093 raw_spin_unlock_irq(&task->pi_lock);
10094
10095 if (ret)
10096 break;
bb9d97b6 10097 }
7dc603c9 10098 return ret;
be367d09 10099}
68318b8e 10100
1f7dd3e5 10101static void cpu_cgroup_attach(struct cgroup_taskset *tset)
68318b8e 10102{
bb9d97b6 10103 struct task_struct *task;
1f7dd3e5 10104 struct cgroup_subsys_state *css;
bb9d97b6 10105
1f7dd3e5 10106 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 10107 sched_move_task(task);
68318b8e
SV
10108}
10109
2480c093 10110#ifdef CONFIG_UCLAMP_TASK_GROUP
0b60ba2d
PB
10111static void cpu_util_update_eff(struct cgroup_subsys_state *css)
10112{
10113 struct cgroup_subsys_state *top_css = css;
10114 struct uclamp_se *uc_parent = NULL;
10115 struct uclamp_se *uc_se = NULL;
10116 unsigned int eff[UCLAMP_CNT];
0413d7f3 10117 enum uclamp_id clamp_id;
0b60ba2d
PB
10118 unsigned int clamps;
10119
93b73858
QY
10120 lockdep_assert_held(&uclamp_mutex);
10121 SCHED_WARN_ON(!rcu_read_lock_held());
10122
0b60ba2d
PB
10123 css_for_each_descendant_pre(css, top_css) {
10124 uc_parent = css_tg(css)->parent
10125 ? css_tg(css)->parent->uclamp : NULL;
10126
10127 for_each_clamp_id(clamp_id) {
10128 /* Assume effective clamps matches requested clamps */
10129 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
10130 /* Cap effective clamps with parent's effective clamps */
10131 if (uc_parent &&
10132 eff[clamp_id] > uc_parent[clamp_id].value) {
10133 eff[clamp_id] = uc_parent[clamp_id].value;
10134 }
10135 }
10136 /* Ensure protection is always capped by limit */
10137 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
10138
10139 /* Propagate most restrictive effective clamps */
10140 clamps = 0x0;
10141 uc_se = css_tg(css)->uclamp;
10142 for_each_clamp_id(clamp_id) {
10143 if (eff[clamp_id] == uc_se[clamp_id].value)
10144 continue;
10145 uc_se[clamp_id].value = eff[clamp_id];
10146 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
10147 clamps |= (0x1 << clamp_id);
10148 }
babbe170 10149 if (!clamps) {
0b60ba2d 10150 css = css_rightmost_descendant(css);
babbe170
PB
10151 continue;
10152 }
10153
10154 /* Immediately update descendants RUNNABLE tasks */
0213b708 10155 uclamp_update_active_tasks(css);
0b60ba2d
PB
10156 }
10157}
2480c093
PB
10158
10159/*
10160 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
10161 * C expression. Since there is no way to convert a macro argument (N) into a
10162 * character constant, use two levels of macros.
10163 */
10164#define _POW10(exp) ((unsigned int)1e##exp)
10165#define POW10(exp) _POW10(exp)
10166
10167struct uclamp_request {
10168#define UCLAMP_PERCENT_SHIFT 2
10169#define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
10170 s64 percent;
10171 u64 util;
10172 int ret;
10173};
10174
10175static inline struct uclamp_request
10176capacity_from_percent(char *buf)
10177{
10178 struct uclamp_request req = {
10179 .percent = UCLAMP_PERCENT_SCALE,
10180 .util = SCHED_CAPACITY_SCALE,
10181 .ret = 0,
10182 };
10183
10184 buf = strim(buf);
10185 if (strcmp(buf, "max")) {
10186 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
10187 &req.percent);
10188 if (req.ret)
10189 return req;
b562d140 10190 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
2480c093
PB
10191 req.ret = -ERANGE;
10192 return req;
10193 }
10194
10195 req.util = req.percent << SCHED_CAPACITY_SHIFT;
10196 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
10197 }
10198
10199 return req;
10200}
10201
10202static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
10203 size_t nbytes, loff_t off,
10204 enum uclamp_id clamp_id)
10205{
10206 struct uclamp_request req;
10207 struct task_group *tg;
10208
10209 req = capacity_from_percent(buf);
10210 if (req.ret)
10211 return req.ret;
10212
46609ce2
QY
10213 static_branch_enable(&sched_uclamp_used);
10214
2480c093
PB
10215 mutex_lock(&uclamp_mutex);
10216 rcu_read_lock();
10217
10218 tg = css_tg(of_css(of));
10219 if (tg->uclamp_req[clamp_id].value != req.util)
10220 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
10221
10222 /*
10223 * Because of not recoverable conversion rounding we keep track of the
10224 * exact requested value
10225 */
10226 tg->uclamp_pct[clamp_id] = req.percent;
10227
0b60ba2d
PB
10228 /* Update effective clamps to track the most restrictive value */
10229 cpu_util_update_eff(of_css(of));
10230
2480c093
PB
10231 rcu_read_unlock();
10232 mutex_unlock(&uclamp_mutex);
10233
10234 return nbytes;
10235}
10236
10237static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
10238 char *buf, size_t nbytes,
10239 loff_t off)
10240{
10241 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
10242}
10243
10244static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
10245 char *buf, size_t nbytes,
10246 loff_t off)
10247{
10248 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
10249}
10250
10251static inline void cpu_uclamp_print(struct seq_file *sf,
10252 enum uclamp_id clamp_id)
10253{
10254 struct task_group *tg;
10255 u64 util_clamp;
10256 u64 percent;
10257 u32 rem;
10258
10259 rcu_read_lock();
10260 tg = css_tg(seq_css(sf));
10261 util_clamp = tg->uclamp_req[clamp_id].value;
10262 rcu_read_unlock();
10263
10264 if (util_clamp == SCHED_CAPACITY_SCALE) {
10265 seq_puts(sf, "max\n");
10266 return;
10267 }
10268
10269 percent = tg->uclamp_pct[clamp_id];
10270 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
10271 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
10272}
10273
10274static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
10275{
10276 cpu_uclamp_print(sf, UCLAMP_MIN);
10277 return 0;
10278}
10279
10280static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
10281{
10282 cpu_uclamp_print(sf, UCLAMP_MAX);
10283 return 0;
10284}
10285#endif /* CONFIG_UCLAMP_TASK_GROUP */
10286
052f1dc7 10287#ifdef CONFIG_FAIR_GROUP_SCHED
182446d0
TH
10288static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
10289 struct cftype *cftype, u64 shareval)
68318b8e 10290{
5b61d50a
KK
10291 if (shareval > scale_load_down(ULONG_MAX))
10292 shareval = MAX_SHARES;
182446d0 10293 return sched_group_set_shares(css_tg(css), scale_load(shareval));
68318b8e
SV
10294}
10295
182446d0
TH
10296static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
10297 struct cftype *cft)
68318b8e 10298{
182446d0 10299 struct task_group *tg = css_tg(css);
68318b8e 10300
c8b28116 10301 return (u64) scale_load_down(tg->shares);
68318b8e 10302}
ab84d31e
PT
10303
10304#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
10305static DEFINE_MUTEX(cfs_constraints_mutex);
10306
ab84d31e 10307const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
b1546edc 10308static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
d505b8af
HC
10309/* More than 203 days if BW_SHIFT equals 20. */
10310static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
ab84d31e 10311
a790de99
PT
10312static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
10313
f4183717
HC
10314static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
10315 u64 burst)
ab84d31e 10316{
56f570e5 10317 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 10318 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
10319
10320 if (tg == &root_task_group)
10321 return -EINVAL;
10322
10323 /*
10324 * Ensure we have at some amount of bandwidth every period. This is
10325 * to prevent reaching a state of large arrears when throttled via
10326 * entity_tick() resulting in prolonged exit starvation.
10327 */
10328 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
10329 return -EINVAL;
10330
10331 /*
3b03706f 10332 * Likewise, bound things on the other side by preventing insane quota
ab84d31e
PT
10333 * periods. This also allows us to normalize in computing quota
10334 * feasibility.
10335 */
10336 if (period > max_cfs_quota_period)
10337 return -EINVAL;
10338
d505b8af
HC
10339 /*
10340 * Bound quota to defend quota against overflow during bandwidth shift.
10341 */
10342 if (quota != RUNTIME_INF && quota > max_cfs_runtime)
10343 return -EINVAL;
10344
f4183717
HC
10345 if (quota != RUNTIME_INF && (burst > quota ||
10346 burst + quota > max_cfs_runtime))
10347 return -EINVAL;
10348
0e59bdae
KT
10349 /*
10350 * Prevent race between setting of cfs_rq->runtime_enabled and
10351 * unthrottle_offline_cfs_rqs().
10352 */
746f5ea9 10353 cpus_read_lock();
a790de99
PT
10354 mutex_lock(&cfs_constraints_mutex);
10355 ret = __cfs_schedulable(tg, period, quota);
10356 if (ret)
10357 goto out_unlock;
10358
58088ad0 10359 runtime_enabled = quota != RUNTIME_INF;
56f570e5 10360 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
1ee14e6c
BS
10361 /*
10362 * If we need to toggle cfs_bandwidth_used, off->on must occur
10363 * before making related changes, and on->off must occur afterwards
10364 */
10365 if (runtime_enabled && !runtime_was_enabled)
10366 cfs_bandwidth_usage_inc();
ab84d31e
PT
10367 raw_spin_lock_irq(&cfs_b->lock);
10368 cfs_b->period = ns_to_ktime(period);
10369 cfs_b->quota = quota;
f4183717 10370 cfs_b->burst = burst;
58088ad0 10371
a9cf55b2 10372 __refill_cfs_bandwidth_runtime(cfs_b);
d1ccc66d
IM
10373
10374 /* Restart the period timer (if active) to handle new period expiry: */
77a4d1a1
PZ
10375 if (runtime_enabled)
10376 start_cfs_bandwidth(cfs_b);
d1ccc66d 10377
ab84d31e
PT
10378 raw_spin_unlock_irq(&cfs_b->lock);
10379
0e59bdae 10380 for_each_online_cpu(i) {
ab84d31e 10381 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 10382 struct rq *rq = cfs_rq->rq;
8a8c69c3 10383 struct rq_flags rf;
ab84d31e 10384
8a8c69c3 10385 rq_lock_irq(rq, &rf);
58088ad0 10386 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 10387 cfs_rq->runtime_remaining = 0;
671fd9da 10388
029632fb 10389 if (cfs_rq->throttled)
671fd9da 10390 unthrottle_cfs_rq(cfs_rq);
8a8c69c3 10391 rq_unlock_irq(rq, &rf);
ab84d31e 10392 }
1ee14e6c
BS
10393 if (runtime_was_enabled && !runtime_enabled)
10394 cfs_bandwidth_usage_dec();
a790de99
PT
10395out_unlock:
10396 mutex_unlock(&cfs_constraints_mutex);
746f5ea9 10397 cpus_read_unlock();
ab84d31e 10398
a790de99 10399 return ret;
ab84d31e
PT
10400}
10401
b1546edc 10402static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
ab84d31e 10403{
f4183717 10404 u64 quota, period, burst;
ab84d31e 10405
029632fb 10406 period = ktime_to_ns(tg->cfs_bandwidth.period);
f4183717 10407 burst = tg->cfs_bandwidth.burst;
ab84d31e
PT
10408 if (cfs_quota_us < 0)
10409 quota = RUNTIME_INF;
1a8b4540 10410 else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
ab84d31e 10411 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
1a8b4540
KK
10412 else
10413 return -EINVAL;
ab84d31e 10414
f4183717 10415 return tg_set_cfs_bandwidth(tg, period, quota, burst);
ab84d31e
PT
10416}
10417
b1546edc 10418static long tg_get_cfs_quota(struct task_group *tg)
ab84d31e
PT
10419{
10420 u64 quota_us;
10421
029632fb 10422 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
10423 return -1;
10424
029632fb 10425 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
10426 do_div(quota_us, NSEC_PER_USEC);
10427
10428 return quota_us;
10429}
10430
b1546edc 10431static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
ab84d31e 10432{
f4183717 10433 u64 quota, period, burst;
ab84d31e 10434
1a8b4540
KK
10435 if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
10436 return -EINVAL;
10437
ab84d31e 10438 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 10439 quota = tg->cfs_bandwidth.quota;
f4183717 10440 burst = tg->cfs_bandwidth.burst;
ab84d31e 10441
f4183717 10442 return tg_set_cfs_bandwidth(tg, period, quota, burst);
ab84d31e
PT
10443}
10444
b1546edc 10445static long tg_get_cfs_period(struct task_group *tg)
ab84d31e
PT
10446{
10447 u64 cfs_period_us;
10448
029632fb 10449 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
10450 do_div(cfs_period_us, NSEC_PER_USEC);
10451
10452 return cfs_period_us;
10453}
10454
f4183717
HC
10455static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
10456{
10457 u64 quota, period, burst;
10458
10459 if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
10460 return -EINVAL;
10461
10462 burst = (u64)cfs_burst_us * NSEC_PER_USEC;
10463 period = ktime_to_ns(tg->cfs_bandwidth.period);
10464 quota = tg->cfs_bandwidth.quota;
10465
10466 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10467}
10468
10469static long tg_get_cfs_burst(struct task_group *tg)
10470{
10471 u64 burst_us;
10472
10473 burst_us = tg->cfs_bandwidth.burst;
10474 do_div(burst_us, NSEC_PER_USEC);
10475
10476 return burst_us;
10477}
10478
182446d0
TH
10479static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
10480 struct cftype *cft)
ab84d31e 10481{
182446d0 10482 return tg_get_cfs_quota(css_tg(css));
ab84d31e
PT
10483}
10484
182446d0
TH
10485static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
10486 struct cftype *cftype, s64 cfs_quota_us)
ab84d31e 10487{
182446d0 10488 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
ab84d31e
PT
10489}
10490
182446d0
TH
10491static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
10492 struct cftype *cft)
ab84d31e 10493{
182446d0 10494 return tg_get_cfs_period(css_tg(css));
ab84d31e
PT
10495}
10496
182446d0
TH
10497static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
10498 struct cftype *cftype, u64 cfs_period_us)
ab84d31e 10499{
182446d0 10500 return tg_set_cfs_period(css_tg(css), cfs_period_us);
ab84d31e
PT
10501}
10502
f4183717
HC
10503static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
10504 struct cftype *cft)
10505{
10506 return tg_get_cfs_burst(css_tg(css));
10507}
10508
10509static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
10510 struct cftype *cftype, u64 cfs_burst_us)
10511{
10512 return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
10513}
10514
a790de99
PT
10515struct cfs_schedulable_data {
10516 struct task_group *tg;
10517 u64 period, quota;
10518};
10519
10520/*
10521 * normalize group quota/period to be quota/max_period
10522 * note: units are usecs
10523 */
10524static u64 normalize_cfs_quota(struct task_group *tg,
10525 struct cfs_schedulable_data *d)
10526{
10527 u64 quota, period;
10528
10529 if (tg == d->tg) {
10530 period = d->period;
10531 quota = d->quota;
10532 } else {
10533 period = tg_get_cfs_period(tg);
10534 quota = tg_get_cfs_quota(tg);
10535 }
10536
10537 /* note: these should typically be equivalent */
10538 if (quota == RUNTIME_INF || quota == -1)
10539 return RUNTIME_INF;
10540
10541 return to_ratio(period, quota);
10542}
10543
10544static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
10545{
10546 struct cfs_schedulable_data *d = data;
029632fb 10547 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
10548 s64 quota = 0, parent_quota = -1;
10549
10550 if (!tg->parent) {
10551 quota = RUNTIME_INF;
10552 } else {
029632fb 10553 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
10554
10555 quota = normalize_cfs_quota(tg, d);
9c58c79a 10556 parent_quota = parent_b->hierarchical_quota;
a790de99
PT
10557
10558 /*
c53593e5
TH
10559 * Ensure max(child_quota) <= parent_quota. On cgroup2,
10560 * always take the min. On cgroup1, only inherit when no
d1ccc66d 10561 * limit is set:
a790de99 10562 */
c53593e5
TH
10563 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
10564 quota = min(quota, parent_quota);
10565 } else {
10566 if (quota == RUNTIME_INF)
10567 quota = parent_quota;
10568 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
10569 return -EINVAL;
10570 }
a790de99 10571 }
9c58c79a 10572 cfs_b->hierarchical_quota = quota;
a790de99
PT
10573
10574 return 0;
10575}
10576
10577static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
10578{
8277434e 10579 int ret;
a790de99
PT
10580 struct cfs_schedulable_data data = {
10581 .tg = tg,
10582 .period = period,
10583 .quota = quota,
10584 };
10585
10586 if (quota != RUNTIME_INF) {
10587 do_div(data.period, NSEC_PER_USEC);
10588 do_div(data.quota, NSEC_PER_USEC);
10589 }
10590
8277434e
PT
10591 rcu_read_lock();
10592 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
10593 rcu_read_unlock();
10594
10595 return ret;
a790de99 10596}
e8da1b18 10597
a1f7164c 10598static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
e8da1b18 10599{
2da8ca82 10600 struct task_group *tg = css_tg(seq_css(sf));
029632fb 10601 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18 10602
44ffc75b
TH
10603 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
10604 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
10605 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
e8da1b18 10606
3d6c50c2 10607 if (schedstat_enabled() && tg != &root_task_group) {
ceeadb83 10608 struct sched_statistics *stats;
3d6c50c2
YW
10609 u64 ws = 0;
10610 int i;
10611
ceeadb83
YS
10612 for_each_possible_cpu(i) {
10613 stats = __schedstats_from_se(tg->se[i]);
10614 ws += schedstat_val(stats->wait_sum);
10615 }
3d6c50c2
YW
10616
10617 seq_printf(sf, "wait_sum %llu\n", ws);
10618 }
10619
bcb1704a
HC
10620 seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
10621 seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
10622
e8da1b18
NR
10623 return 0;
10624}
ab84d31e 10625#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 10626#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 10627
052f1dc7 10628#ifdef CONFIG_RT_GROUP_SCHED
182446d0
TH
10629static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
10630 struct cftype *cft, s64 val)
6f505b16 10631{
182446d0 10632 return sched_group_set_rt_runtime(css_tg(css), val);
6f505b16
PZ
10633}
10634
182446d0
TH
10635static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
10636 struct cftype *cft)
6f505b16 10637{
182446d0 10638 return sched_group_rt_runtime(css_tg(css));
6f505b16 10639}
d0b27fa7 10640
182446d0
TH
10641static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
10642 struct cftype *cftype, u64 rt_period_us)
d0b27fa7 10643{
182446d0 10644 return sched_group_set_rt_period(css_tg(css), rt_period_us);
d0b27fa7
PZ
10645}
10646
182446d0
TH
10647static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
10648 struct cftype *cft)
d0b27fa7 10649{
182446d0 10650 return sched_group_rt_period(css_tg(css));
d0b27fa7 10651}
6d6bc0ad 10652#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 10653
30400039
JD
10654#ifdef CONFIG_FAIR_GROUP_SCHED
10655static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
10656 struct cftype *cft)
10657{
10658 return css_tg(css)->idle;
10659}
10660
10661static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
10662 struct cftype *cft, s64 idle)
10663{
10664 return sched_group_set_idle(css_tg(css), idle);
10665}
10666#endif
10667
a1f7164c 10668static struct cftype cpu_legacy_files[] = {
052f1dc7 10669#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
10670 {
10671 .name = "shares",
f4c753b7
PM
10672 .read_u64 = cpu_shares_read_u64,
10673 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 10674 },
30400039
JD
10675 {
10676 .name = "idle",
10677 .read_s64 = cpu_idle_read_s64,
10678 .write_s64 = cpu_idle_write_s64,
10679 },
052f1dc7 10680#endif
ab84d31e
PT
10681#ifdef CONFIG_CFS_BANDWIDTH
10682 {
10683 .name = "cfs_quota_us",
10684 .read_s64 = cpu_cfs_quota_read_s64,
10685 .write_s64 = cpu_cfs_quota_write_s64,
10686 },
10687 {
10688 .name = "cfs_period_us",
10689 .read_u64 = cpu_cfs_period_read_u64,
10690 .write_u64 = cpu_cfs_period_write_u64,
10691 },
f4183717
HC
10692 {
10693 .name = "cfs_burst_us",
10694 .read_u64 = cpu_cfs_burst_read_u64,
10695 .write_u64 = cpu_cfs_burst_write_u64,
10696 },
e8da1b18
NR
10697 {
10698 .name = "stat",
a1f7164c 10699 .seq_show = cpu_cfs_stat_show,
e8da1b18 10700 },
ab84d31e 10701#endif
052f1dc7 10702#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 10703 {
9f0c1e56 10704 .name = "rt_runtime_us",
06ecb27c
PM
10705 .read_s64 = cpu_rt_runtime_read,
10706 .write_s64 = cpu_rt_runtime_write,
6f505b16 10707 },
d0b27fa7
PZ
10708 {
10709 .name = "rt_period_us",
f4c753b7
PM
10710 .read_u64 = cpu_rt_period_read_uint,
10711 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 10712 },
2480c093
PB
10713#endif
10714#ifdef CONFIG_UCLAMP_TASK_GROUP
10715 {
10716 .name = "uclamp.min",
10717 .flags = CFTYPE_NOT_ON_ROOT,
10718 .seq_show = cpu_uclamp_min_show,
10719 .write = cpu_uclamp_min_write,
10720 },
10721 {
10722 .name = "uclamp.max",
10723 .flags = CFTYPE_NOT_ON_ROOT,
10724 .seq_show = cpu_uclamp_max_show,
10725 .write = cpu_uclamp_max_write,
10726 },
052f1dc7 10727#endif
d1ccc66d 10728 { } /* Terminate */
68318b8e
SV
10729};
10730
d41bf8c9
TH
10731static int cpu_extra_stat_show(struct seq_file *sf,
10732 struct cgroup_subsys_state *css)
0d593634 10733{
0d593634
TH
10734#ifdef CONFIG_CFS_BANDWIDTH
10735 {
d41bf8c9 10736 struct task_group *tg = css_tg(css);
0d593634 10737 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
bcb1704a 10738 u64 throttled_usec, burst_usec;
0d593634
TH
10739
10740 throttled_usec = cfs_b->throttled_time;
10741 do_div(throttled_usec, NSEC_PER_USEC);
bcb1704a
HC
10742 burst_usec = cfs_b->burst_time;
10743 do_div(burst_usec, NSEC_PER_USEC);
0d593634
TH
10744
10745 seq_printf(sf, "nr_periods %d\n"
10746 "nr_throttled %d\n"
bcb1704a
HC
10747 "throttled_usec %llu\n"
10748 "nr_bursts %d\n"
10749 "burst_usec %llu\n",
0d593634 10750 cfs_b->nr_periods, cfs_b->nr_throttled,
bcb1704a 10751 throttled_usec, cfs_b->nr_burst, burst_usec);
0d593634
TH
10752 }
10753#endif
10754 return 0;
10755}
10756
10757#ifdef CONFIG_FAIR_GROUP_SCHED
10758static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
10759 struct cftype *cft)
10760{
10761 struct task_group *tg = css_tg(css);
10762 u64 weight = scale_load_down(tg->shares);
10763
10764 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
10765}
10766
10767static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
10768 struct cftype *cft, u64 weight)
10769{
10770 /*
10771 * cgroup weight knobs should use the common MIN, DFL and MAX
10772 * values which are 1, 100 and 10000 respectively. While it loses
10773 * a bit of range on both ends, it maps pretty well onto the shares
10774 * value used by scheduler and the round-trip conversions preserve
10775 * the original value over the entire range.
10776 */
10777 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
10778 return -ERANGE;
10779
10780 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
10781
10782 return sched_group_set_shares(css_tg(css), scale_load(weight));
10783}
10784
10785static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
10786 struct cftype *cft)
10787{
10788 unsigned long weight = scale_load_down(css_tg(css)->shares);
10789 int last_delta = INT_MAX;
10790 int prio, delta;
10791
10792 /* find the closest nice value to the current weight */
10793 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
10794 delta = abs(sched_prio_to_weight[prio] - weight);
10795 if (delta >= last_delta)
10796 break;
10797 last_delta = delta;
10798 }
10799
10800 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
10801}
10802
10803static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
10804 struct cftype *cft, s64 nice)
10805{
10806 unsigned long weight;
7281c8de 10807 int idx;
0d593634
TH
10808
10809 if (nice < MIN_NICE || nice > MAX_NICE)
10810 return -ERANGE;
10811
7281c8de
PZ
10812 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
10813 idx = array_index_nospec(idx, 40);
10814 weight = sched_prio_to_weight[idx];
10815
0d593634
TH
10816 return sched_group_set_shares(css_tg(css), scale_load(weight));
10817}
10818#endif
10819
10820static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
10821 long period, long quota)
10822{
10823 if (quota < 0)
10824 seq_puts(sf, "max");
10825 else
10826 seq_printf(sf, "%ld", quota);
10827
10828 seq_printf(sf, " %ld\n", period);
10829}
10830
10831/* caller should put the current value in *@periodp before calling */
10832static int __maybe_unused cpu_period_quota_parse(char *buf,
10833 u64 *periodp, u64 *quotap)
10834{
10835 char tok[21]; /* U64_MAX */
10836
4c47acd8 10837 if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
0d593634
TH
10838 return -EINVAL;
10839
10840 *periodp *= NSEC_PER_USEC;
10841
10842 if (sscanf(tok, "%llu", quotap))
10843 *quotap *= NSEC_PER_USEC;
10844 else if (!strcmp(tok, "max"))
10845 *quotap = RUNTIME_INF;
10846 else
10847 return -EINVAL;
10848
10849 return 0;
10850}
10851
10852#ifdef CONFIG_CFS_BANDWIDTH
10853static int cpu_max_show(struct seq_file *sf, void *v)
10854{
10855 struct task_group *tg = css_tg(seq_css(sf));
10856
10857 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
10858 return 0;
10859}
10860
10861static ssize_t cpu_max_write(struct kernfs_open_file *of,
10862 char *buf, size_t nbytes, loff_t off)
10863{
10864 struct task_group *tg = css_tg(of_css(of));
10865 u64 period = tg_get_cfs_period(tg);
f4183717 10866 u64 burst = tg_get_cfs_burst(tg);
0d593634
TH
10867 u64 quota;
10868 int ret;
10869
10870 ret = cpu_period_quota_parse(buf, &period, &quota);
10871 if (!ret)
f4183717 10872 ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
0d593634
TH
10873 return ret ?: nbytes;
10874}
10875#endif
10876
10877static struct cftype cpu_files[] = {
0d593634
TH
10878#ifdef CONFIG_FAIR_GROUP_SCHED
10879 {
10880 .name = "weight",
10881 .flags = CFTYPE_NOT_ON_ROOT,
10882 .read_u64 = cpu_weight_read_u64,
10883 .write_u64 = cpu_weight_write_u64,
10884 },
10885 {
10886 .name = "weight.nice",
10887 .flags = CFTYPE_NOT_ON_ROOT,
10888 .read_s64 = cpu_weight_nice_read_s64,
10889 .write_s64 = cpu_weight_nice_write_s64,
10890 },
30400039
JD
10891 {
10892 .name = "idle",
10893 .flags = CFTYPE_NOT_ON_ROOT,
10894 .read_s64 = cpu_idle_read_s64,
10895 .write_s64 = cpu_idle_write_s64,
10896 },
0d593634
TH
10897#endif
10898#ifdef CONFIG_CFS_BANDWIDTH
10899 {
10900 .name = "max",
10901 .flags = CFTYPE_NOT_ON_ROOT,
10902 .seq_show = cpu_max_show,
10903 .write = cpu_max_write,
10904 },
f4183717
HC
10905 {
10906 .name = "max.burst",
10907 .flags = CFTYPE_NOT_ON_ROOT,
10908 .read_u64 = cpu_cfs_burst_read_u64,
10909 .write_u64 = cpu_cfs_burst_write_u64,
10910 },
2480c093
PB
10911#endif
10912#ifdef CONFIG_UCLAMP_TASK_GROUP
10913 {
10914 .name = "uclamp.min",
10915 .flags = CFTYPE_NOT_ON_ROOT,
10916 .seq_show = cpu_uclamp_min_show,
10917 .write = cpu_uclamp_min_write,
10918 },
10919 {
10920 .name = "uclamp.max",
10921 .flags = CFTYPE_NOT_ON_ROOT,
10922 .seq_show = cpu_uclamp_max_show,
10923 .write = cpu_uclamp_max_write,
10924 },
0d593634
TH
10925#endif
10926 { } /* terminate */
10927};
10928
073219e9 10929struct cgroup_subsys cpu_cgrp_subsys = {
92fb9748 10930 .css_alloc = cpu_cgroup_css_alloc,
96b77745 10931 .css_online = cpu_cgroup_css_online,
2f5177f0 10932 .css_released = cpu_cgroup_css_released,
92fb9748 10933 .css_free = cpu_cgroup_css_free,
d41bf8c9 10934 .css_extra_stat_show = cpu_extra_stat_show,
eeb61e53 10935 .fork = cpu_cgroup_fork,
bb9d97b6
TH
10936 .can_attach = cpu_cgroup_can_attach,
10937 .attach = cpu_cgroup_attach,
a1f7164c 10938 .legacy_cftypes = cpu_legacy_files,
0d593634 10939 .dfl_cftypes = cpu_files,
b38e42e9 10940 .early_init = true,
0d593634 10941 .threaded = true,
68318b8e
SV
10942};
10943
052f1dc7 10944#endif /* CONFIG_CGROUP_SCHED */
d842de87 10945
b637a328
PM
10946void dump_cpu_task(int cpu)
10947{
10948 pr_info("Task dump for CPU %d:\n", cpu);
10949 sched_show_task(cpu_curr(cpu));
10950}
ed82b8a1
AK
10951
10952/*
10953 * Nice levels are multiplicative, with a gentle 10% change for every
10954 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
10955 * nice 1, it will get ~10% less CPU time than another CPU-bound task
10956 * that remained on nice 0.
10957 *
10958 * The "10% effect" is relative and cumulative: from _any_ nice level,
10959 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
10960 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
10961 * If a task goes up by ~10% and another task goes down by ~10% then
10962 * the relative distance between them is ~25%.)
10963 */
10964const int sched_prio_to_weight[40] = {
10965 /* -20 */ 88761, 71755, 56483, 46273, 36291,
10966 /* -15 */ 29154, 23254, 18705, 14949, 11916,
10967 /* -10 */ 9548, 7620, 6100, 4904, 3906,
10968 /* -5 */ 3121, 2501, 1991, 1586, 1277,
10969 /* 0 */ 1024, 820, 655, 526, 423,
10970 /* 5 */ 335, 272, 215, 172, 137,
10971 /* 10 */ 110, 87, 70, 56, 45,
10972 /* 15 */ 36, 29, 23, 18, 15,
10973};
10974
10975/*
10976 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
10977 *
10978 * In cases where the weight does not change often, we can use the
10979 * precalculated inverse to speed up arithmetics by turning divisions
10980 * into multiplications:
10981 */
10982const u32 sched_prio_to_wmult[40] = {
10983 /* -20 */ 48388, 59856, 76040, 92818, 118348,
10984 /* -15 */ 147320, 184698, 229616, 287308, 360437,
10985 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
10986 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
10987 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
10988 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
10989 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
10990 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
10991};
14a7405b 10992
9d246053
PA
10993void call_trace_sched_update_nr_running(struct rq *rq, int count)
10994{
10995 trace_sched_update_nr_running_tp(rq, count);
10996}