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