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