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