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