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